]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC.pm
update_lxc_config: remove ostype check
[pve-container.git] / src / PVE / LXC.pm
1 package PVE::LXC;
2
3 use strict;
4 use warnings;
5
6 use POSIX qw(EINTR);
7
8 use Socket;
9
10 use File::Path;
11 use File::Spec;
12 use Cwd qw();
13 use Fcntl qw(O_RDONLY O_NOFOLLOW O_DIRECTORY);
14 use Errno qw(ELOOP ENOTDIR EROFS);
15
16 use PVE::Exception qw(raise_perm_exc);
17 use PVE::Storage;
18 use PVE::SafeSyslog;
19 use PVE::INotify;
20 use PVE::Tools qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH);
21 use PVE::CpuSet;
22 use PVE::Network;
23 use PVE::AccessControl;
24 use PVE::ProcFSTools;
25 use PVE::Syscall;
26 use PVE::LXC::Config;
27 use Time::HiRes qw (gettimeofday);
28
29 my $nodename = PVE::INotify::nodename();
30
31 my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
32
33 sub config_list {
34 my $vmlist = PVE::Cluster::get_vmlist();
35 my $res = {};
36 return $res if !$vmlist || !$vmlist->{ids};
37 my $ids = $vmlist->{ids};
38
39 foreach my $vmid (keys %$ids) {
40 next if !$vmid; # skip CT0
41 my $d = $ids->{$vmid};
42 next if !$d->{node} || $d->{node} ne $nodename;
43 next if !$d->{type} || $d->{type} ne 'lxc';
44 $res->{$vmid}->{type} = 'lxc';
45 }
46 return $res;
47 }
48
49 sub destroy_config {
50 my ($vmid) = @_;
51
52 unlink PVE::LXC::Config->config_file($vmid, $nodename);
53 }
54
55 # container status helpers
56
57 sub list_active_containers {
58
59 my $filename = "/proc/net/unix";
60
61 # similar test is used by lcxcontainers.c: list_active_containers
62 my $res = {};
63
64 my $fh = IO::File->new ($filename, "r");
65 return $res if !$fh;
66
67 while (defined(my $line = <$fh>)) {
68 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
69 my $path = $1;
70 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
71 $res->{$1} = 1;
72 }
73 }
74 }
75
76 close($fh);
77
78 return $res;
79 }
80
81 # warning: this is slow
82 sub check_running {
83 my ($vmid) = @_;
84
85 my $active_hash = list_active_containers();
86
87 return 1 if defined($active_hash->{$vmid});
88
89 return undef;
90 }
91
92 sub get_container_disk_usage {
93 my ($vmid, $pid) = @_;
94
95 return PVE::Tools::df("/proc/$pid/root/", 1);
96 }
97
98 my $last_proc_vmid_stat;
99
100 my $parse_cpuacct_stat = sub {
101 my ($vmid) = @_;
102
103 my $raw = read_cgroup_value('cpuacct', $vmid, 'cpuacct.stat', 1);
104
105 my $stat = {};
106
107 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
108
109 $stat->{utime} = $1;
110 $stat->{stime} = $2;
111
112 }
113
114 return $stat;
115 };
116
117 sub vmstatus {
118 my ($opt_vmid) = @_;
119
120 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc' }} : config_list();
121
122 my $active_hash = list_active_containers();
123
124 my $cpucount = $cpuinfo->{cpus} || 1;
125
126 my $cdtime = gettimeofday;
127
128 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
129
130 foreach my $vmid (keys %$list) {
131 my $d = $list->{$vmid};
132
133 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
134 warn $@ if $@; # ignore errors (consider them stopped)
135
136 $d->{status} = $d->{pid} ? 'running' : 'stopped';
137
138 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
139 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
140
141 $d->{name} = $conf->{'hostname'} || "CT$vmid";
142 $d->{name} =~ s/[\s]//g;
143
144 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
145 $d->{cpus} = $cpucount if !$d->{cpus};
146
147 $d->{lock} = $conf->{lock} || '';
148
149 if ($d->{pid}) {
150 my $res = get_container_disk_usage($vmid, $d->{pid});
151 $d->{disk} = $res->{used};
152 $d->{maxdisk} = $res->{total};
153 } else {
154 $d->{disk} = 0;
155 # use 4GB by default ??
156 if (my $rootfs = $conf->{rootfs}) {
157 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($rootfs);
158 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
159 } else {
160 $d->{maxdisk} = 4*1024*1024*1024;
161 }
162 }
163
164 $d->{mem} = 0;
165 $d->{swap} = 0;
166 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
167 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
168
169 $d->{uptime} = 0;
170 $d->{cpu} = 0;
171
172 $d->{netout} = 0;
173 $d->{netin} = 0;
174
175 $d->{diskread} = 0;
176 $d->{diskwrite} = 0;
177
178 $d->{template} = PVE::LXC::Config->is_template($conf);
179 }
180
181 foreach my $vmid (keys %$list) {
182 my $d = $list->{$vmid};
183 my $pid = $d->{pid};
184
185 next if !$pid; # skip stopped CTs
186
187 my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
188 $d->{uptime} = time - $ctime; # the method lxcfs uses
189
190 my $memory_stat = read_cgroup_list('memory', $vmid, 'memory.stat');
191 my $mem_usage_in_bytes = read_cgroup_value('memory', $vmid, 'memory.usage_in_bytes');
192
193 $d->{mem} = $mem_usage_in_bytes - $memory_stat->{total_cache};
194 $d->{swap} = read_cgroup_value('memory', $vmid, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
195
196 my $blkio_bytes = read_cgroup_value('blkio', $vmid, 'blkio.throttle.io_service_bytes', 1);
197 my @bytes = split(/\n/, $blkio_bytes);
198 foreach my $byte (@bytes) {
199 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
200 $d->{diskread} = $2 if $key eq 'Read';
201 $d->{diskwrite} = $2 if $key eq 'Write';
202 }
203 }
204
205 my $pstat = &$parse_cpuacct_stat($vmid);
206
207 my $used = $pstat->{utime} + $pstat->{stime};
208
209 my $old = $last_proc_vmid_stat->{$vmid};
210 if (!$old) {
211 $last_proc_vmid_stat->{$vmid} = {
212 time => $cdtime,
213 used => $used,
214 cpu => 0,
215 };
216 next;
217 }
218
219 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
220
221 if ($dtime > 1000) {
222 my $dutime = $used - $old->{used};
223
224 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
225 $last_proc_vmid_stat->{$vmid} = {
226 time => $cdtime,
227 used => $used,
228 cpu => $d->{cpu},
229 };
230 } else {
231 $d->{cpu} = $old->{cpu};
232 }
233 }
234
235 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
236
237 foreach my $dev (keys %$netdev) {
238 next if $dev !~ m/^veth([1-9]\d*)i/;
239 my $vmid = $1;
240 my $d = $list->{$vmid};
241
242 next if !$d;
243
244 $d->{netout} += $netdev->{$dev}->{receive};
245 $d->{netin} += $netdev->{$dev}->{transmit};
246
247 }
248
249 return $list;
250 }
251
252 sub read_cgroup_list {
253 my ($group, $vmid, $name) = @_;
254
255 my $content = read_cgroup_value($group, $vmid, $name, 1);
256
257 return { split(/\s+/, $content) };
258 }
259
260 sub read_cgroup_value {
261 my ($group, $vmid, $name, $full) = @_;
262
263 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
264
265 return PVE::Tools::file_get_contents($path) if $full;
266
267 return PVE::Tools::file_read_firstline($path);
268 }
269
270 sub write_cgroup_value {
271 my ($group, $vmid, $name, $value) = @_;
272
273 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
274 PVE::ProcFSTools::write_proc_entry($path, $value) if -e $path;
275
276 }
277
278 sub find_lxc_console_pids {
279
280 my $res = {};
281
282 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
283 my ($pid) = @_;
284
285 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
286 return if !$cmdline;
287
288 my @args = split(/\0/, $cmdline);
289
290 # search for lxc-console -n <vmid>
291 return if scalar(@args) != 3;
292 return if $args[1] ne '-n';
293 return if $args[2] !~ m/^\d+$/;
294 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
295
296 my $vmid = $args[2];
297
298 push @{$res->{$vmid}}, $pid;
299 });
300
301 return $res;
302 }
303
304 sub find_lxc_pid {
305 my ($vmid) = @_;
306
307 my $pid = undef;
308 my $parser = sub {
309 my $line = shift;
310 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
311 };
312 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
313
314 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
315
316 return $pid;
317 }
318
319 # Note: we cannot use Net:IP, because that only allows strict
320 # CIDR networks
321 sub parse_ipv4_cidr {
322 my ($cidr, $noerr) = @_;
323
324 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
325 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
326 }
327
328 return undef if $noerr;
329
330 die "unable to parse ipv4 address/mask\n";
331 }
332
333
334 sub update_lxc_config {
335 my ($vmid, $conf) = @_;
336
337 my $dir = "/var/lib/lxc/$vmid";
338
339 if ($conf->{template}) {
340
341 unlink "$dir/config";
342
343 return;
344 }
345
346 my $raw = '';
347
348 die "missing 'arch' - internal error" if !$conf->{arch};
349 $raw .= "lxc.arch = $conf->{arch}\n";
350
351 my $unprivileged = $conf->{unprivileged};
352 my $custom_idmap = grep { $_->[0] eq 'lxc.id_map' } @{$conf->{lxc}};
353
354 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
355
356 my $inc ="/usr/share/lxc/config/$ostype.common.conf";
357 $inc ="/usr/share/lxc/config/common.conf" if !-f $inc;
358 $raw .= "lxc.include = $inc\n";
359 if ($unprivileged || $custom_idmap) {
360 $inc = "/usr/share/lxc/config/$ostype.userns.conf";
361 $inc = "/usr/share/lxc/config/userns.conf" if !-f $inc;
362 $raw .= "lxc.include = $inc\n"
363 }
364
365 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
366 # cannot be exposed to the container with r/w access (cgroup perms).
367 # When this is enabled mounts will still remain in the monitor's namespace
368 # after the container unmounted them and thus will not detach from their
369 # files while the container is running!
370 $raw .= "lxc.monitor.unshare = 1\n";
371
372 # Should we read them from /etc/subuid?
373 if ($unprivileged && !$custom_idmap) {
374 $raw .= "lxc.id_map = u 0 100000 65536\n";
375 $raw .= "lxc.id_map = g 0 100000 65536\n";
376 }
377
378 if (!PVE::LXC::Config->has_dev_console($conf)) {
379 $raw .= "lxc.console = none\n";
380 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
381 }
382
383 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
384 $raw .= "lxc.tty = $ttycount\n";
385
386 # some init scripts expect a linux terminal (turnkey).
387 $raw .= "lxc.environment = TERM=linux\n";
388
389 my $utsname = $conf->{hostname} || "CT$vmid";
390 $raw .= "lxc.utsname = $utsname\n";
391
392 my $memory = $conf->{memory} || 512;
393 my $swap = $conf->{swap} // 0;
394
395 my $lxcmem = int($memory*1024*1024);
396 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
397
398 my $lxcswap = int(($memory + $swap)*1024*1024);
399 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
400
401 if (my $cpulimit = $conf->{cpulimit}) {
402 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
403 my $value = int(100000*$cpulimit);
404 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
405 }
406
407 my $shares = $conf->{cpuunits} || 1024;
408 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
409
410 die "missing 'rootfs' configuration\n"
411 if !defined($conf->{rootfs});
412
413 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
414
415 $raw .= "lxc.rootfs = $dir/rootfs\n";
416
417 my $netcount = 0;
418 foreach my $k (sort keys %$conf) {
419 next if $k !~ m/^net(\d+)$/;
420 my $ind = $1;
421 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
422 $netcount++;
423 $raw .= "lxc.network.type = veth\n";
424 $raw .= "lxc.network.veth.pair = veth${vmid}i${ind}\n";
425 $raw .= "lxc.network.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
426 $raw .= "lxc.network.name = $d->{name}\n" if defined($d->{name});
427 $raw .= "lxc.network.mtu = $d->{mtu}\n" if defined($d->{mtu});
428 }
429
430 my $had_cpuset = 0;
431 if (my $lxcconf = $conf->{lxc}) {
432 foreach my $entry (@$lxcconf) {
433 my ($k, $v) = @$entry;
434 $netcount++ if $k eq 'lxc.network.type';
435 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
436 $raw .= "$k = $v\n";
437 }
438 }
439
440 $raw .= "lxc.network.type = empty\n" if !$netcount;
441
442 my $cores = $conf->{cores};
443 if (!$had_cpuset && $cores) {
444 my $cpuset = eval { PVE::CpuSet->new_from_cgroup('lxc', 'effective_cpus') };
445 $cpuset = PVE::CpuSet->new_from_cgroup('', 'effective_cpus') if !$cpuset;
446 my @members = $cpuset->members();
447 while (scalar(@members) > $cores) {
448 my $randidx = int(rand(scalar(@members)));
449 $cpuset->delete($members[$randidx]);
450 splice(@members, $randidx, 1); # keep track of the changes
451 }
452 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
453 }
454
455 File::Path::mkpath("$dir/rootfs");
456
457 PVE::Tools::file_set_contents("$dir/config", $raw);
458 }
459
460 # verify and cleanup nameserver list (replace \0 with ' ')
461 sub verify_nameserver_list {
462 my ($nameserver_list) = @_;
463
464 my @list = ();
465 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
466 PVE::JSONSchema::pve_verify_ip($server);
467 push @list, $server;
468 }
469
470 return join(' ', @list);
471 }
472
473 sub verify_searchdomain_list {
474 my ($searchdomain_list) = @_;
475
476 my @list = ();
477 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
478 # todo: should we add checks for valid dns domains?
479 push @list, $server;
480 }
481
482 return join(' ', @list);
483 }
484
485 sub get_console_command {
486 my ($vmid, $conf) = @_;
487
488 my $cmode = PVE::LXC::Config->get_cmode($conf);
489
490 if ($cmode eq 'console') {
491 return ['lxc-console', '-n', $vmid, '-t', 0];
492 } elsif ($cmode eq 'tty') {
493 return ['lxc-console', '-n', $vmid];
494 } elsif ($cmode eq 'shell') {
495 return ['lxc-attach', '--clear-env', '-n', $vmid];
496 } else {
497 die "internal error";
498 }
499 }
500
501 sub get_primary_ips {
502 my ($conf) = @_;
503
504 # return data from net0
505
506 return undef if !defined($conf->{net0});
507 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
508
509 my $ipv4 = $net->{ip};
510 if ($ipv4) {
511 if ($ipv4 =~ /^(dhcp|manual)$/) {
512 $ipv4 = undef
513 } else {
514 $ipv4 =~ s!/\d+$!!;
515 }
516 }
517 my $ipv6 = $net->{ip6};
518 if ($ipv6) {
519 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
520 $ipv6 = undef;
521 } else {
522 $ipv6 =~ s!/\d+$!!;
523 }
524 }
525
526 return ($ipv4, $ipv6);
527 }
528
529 sub delete_mountpoint_volume {
530 my ($storage_cfg, $vmid, $volume) = @_;
531
532 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
533
534 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
535 PVE::Storage::vdisk_free($storage_cfg, $volume) if $vmid == $owner;
536 }
537
538 sub destroy_lxc_container {
539 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
540
541 PVE::LXC::Config->foreach_mountpoint($conf, sub {
542 my ($ms, $mountpoint) = @_;
543 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
544 });
545
546 rmdir "/var/lib/lxc/$vmid/rootfs";
547 unlink "/var/lib/lxc/$vmid/config";
548 rmdir "/var/lib/lxc/$vmid";
549 if (defined $replacement_conf) {
550 PVE::LXC::Config->write_config($vmid, $replacement_conf);
551 } else {
552 destroy_config($vmid);
553 }
554
555 #my $cmd = ['lxc-destroy', '-n', $vmid ];
556 #PVE::Tools::run_command($cmd);
557 }
558
559 sub vm_stop_cleanup {
560 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
561
562 eval {
563 if (!$keepActive) {
564
565 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
566 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
567 }
568 };
569 warn $@ if $@; # avoid errors - just warn
570 }
571
572 my $safe_num_ne = sub {
573 my ($a, $b) = @_;
574
575 return 0 if !defined($a) && !defined($b);
576 return 1 if !defined($a);
577 return 1 if !defined($b);
578
579 return $a != $b;
580 };
581
582 my $safe_string_ne = sub {
583 my ($a, $b) = @_;
584
585 return 0 if !defined($a) && !defined($b);
586 return 1 if !defined($a);
587 return 1 if !defined($b);
588
589 return $a ne $b;
590 };
591
592 sub update_net {
593 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
594
595 if ($newnet->{type} ne 'veth') {
596 # for when there are physical interfaces
597 die "cannot update interface of type $newnet->{type}";
598 }
599
600 my $veth = "veth${vmid}i${netid}";
601 my $eth = $newnet->{name};
602
603 if (my $oldnetcfg = $conf->{$opt}) {
604 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
605
606 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
607 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
608
609 PVE::Network::veth_delete($veth);
610 delete $conf->{$opt};
611 PVE::LXC::Config->write_config($vmid, $conf);
612
613 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
614
615 } else {
616 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
617 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
618 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
619
620 if ($oldnet->{bridge}) {
621 PVE::Network::tap_unplug($veth);
622 foreach (qw(bridge tag firewall)) {
623 delete $oldnet->{$_};
624 }
625 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
626 PVE::LXC::Config->write_config($vmid, $conf);
627 }
628
629 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
630 # This includes the rate:
631 foreach (qw(bridge tag firewall rate)) {
632 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
633 }
634 } elsif (&$safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
635 # Rate can be applied on its own but any change above needs to
636 # include the rate in tap_plug since OVS resets everything.
637 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
638 $oldnet->{rate} = $newnet->{rate}
639 }
640 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
641 PVE::LXC::Config->write_config($vmid, $conf);
642 }
643 } else {
644 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
645 }
646
647 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
648 }
649
650 sub hotplug_net {
651 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
652
653 my $veth = "veth${vmid}i${netid}";
654 my $vethpeer = $veth . "p";
655 my $eth = $newnet->{name};
656
657 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
658 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
659
660 # attach peer in container
661 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
662 PVE::Tools::run_command($cmd);
663
664 # link up peer in container
665 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
666 PVE::Tools::run_command($cmd);
667
668 my $done = { type => 'veth' };
669 foreach (qw(bridge tag firewall hwaddr name)) {
670 $done->{$_} = $newnet->{$_} if $newnet->{$_};
671 }
672 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
673
674 PVE::LXC::Config->write_config($vmid, $conf);
675 }
676
677 sub update_ipconfig {
678 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
679
680 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
681
682 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
683 my $deleted = [];
684 my $added = [];
685 my $nscmd = sub {
686 my $cmdargs = shift;
687 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
688 };
689 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
690
691 my $change_ip_config = sub {
692 my ($ipversion) = @_;
693
694 my $family_opt = "-$ipversion";
695 my $suffix = $ipversion == 4 ? '' : $ipversion;
696 my $gw= "gw$suffix";
697 my $ip= "ip$suffix";
698
699 my $newip = $newnet->{$ip};
700 my $newgw = $newnet->{$gw};
701 my $oldip = $optdata->{$ip};
702
703 my $change_ip = &$safe_string_ne($oldip, $newip);
704 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
705
706 return if !$change_ip && !$change_gw;
707
708 # step 1: add new IP, if this fails we cancel
709 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
710 if ($change_ip && $is_real_ip) {
711 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
712 if (my $err = $@) {
713 warn $err;
714 return;
715 }
716 }
717
718 # step 2: replace gateway
719 # If this fails we delete the added IP and cancel.
720 # If it succeeds we save the config and delete the old IP, ignoring
721 # errors. The config is then saved.
722 # Note: 'ip route replace' can add
723 if ($change_gw) {
724 if ($newgw) {
725 eval {
726 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
727 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
728 }
729 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
730 };
731 if (my $err = $@) {
732 warn $err;
733 # the route was not replaced, the old IP is still available
734 # rollback (delete new IP) and cancel
735 if ($change_ip) {
736 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
737 warn $@ if $@; # no need to die here
738 }
739 return;
740 }
741 } else {
742 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
743 # if the route was not deleted, the guest might have deleted it manually
744 # warn and continue
745 warn $@ if $@;
746 }
747 }
748
749 # from this point on we save the configuration
750 # step 3: delete old IP ignoring errors
751 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
752 # We need to enable promote_secondaries, otherwise our newly added
753 # address will be removed along with the old one.
754 my $promote = 0;
755 eval {
756 if ($ipversion == 4) {
757 &$nscmd({ outfunc => sub { $promote = int(shift) } },
758 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
759 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
760 }
761 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
762 };
763 warn $@ if $@; # no need to die here
764
765 if ($ipversion == 4) {
766 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
767 }
768 }
769
770 foreach my $property ($ip, $gw) {
771 if ($newnet->{$property}) {
772 $optdata->{$property} = $newnet->{$property};
773 } else {
774 delete $optdata->{$property};
775 }
776 }
777 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
778 PVE::LXC::Config->write_config($vmid, $conf);
779 $lxc_setup->setup_network($conf);
780 };
781
782 &$change_ip_config(4);
783 &$change_ip_config(6);
784
785 }
786
787 my $enter_namespace = sub {
788 my ($vmid, $pid, $which, $type) = @_;
789 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
790 or die "failed to open $which namespace of container $vmid: $!\n";
791 PVE::Tools::setns(fileno($fd), $type)
792 or die "failed to enter $which namespace of container $vmid: $!\n";
793 close $fd;
794 };
795
796 my $do_syncfs = sub {
797 my ($vmid, $pid, $socket) = @_;
798
799 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
800
801 # Tell the parent process to start reading our /proc/mounts
802 print {$socket} "go\n";
803 $socket->flush();
804
805 # Receive /proc/self/mounts
806 my $mountdata = do { local $/ = undef; <$socket> };
807 close $socket;
808
809 # Now sync all mountpoints...
810 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
811 foreach my $mp (@$mounts) {
812 my ($what, $dir, $fs) = @$mp;
813 next if $fs eq 'fuse.lxcfs';
814 eval { PVE::Tools::sync_mountpoint($dir); };
815 warn $@ if $@;
816 }
817 };
818
819 sub sync_container_namespace {
820 my ($vmid) = @_;
821 my $pid = find_lxc_pid($vmid);
822
823 # SOCK_DGRAM is nicer for barriers but cannot be slurped
824 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
825 or die "failed to create socketpair: $!\n";
826
827 my $child = fork();
828 die "fork failed: $!\n" if !defined($child);
829
830 if (!$child) {
831 eval {
832 close $pfd;
833 &$do_syncfs($vmid, $pid, $cfd);
834 };
835 if (my $err = $@) {
836 warn $err;
837 POSIX::_exit(1);
838 }
839 POSIX::_exit(0);
840 }
841 close $cfd;
842 my $go = <$pfd>;
843 die "failed to enter container namespace\n" if $go ne "go\n";
844
845 open my $mounts, '<', "/proc/$child/mounts"
846 or die "failed to open container's /proc/mounts: $!\n";
847 my $mountdata = do { local $/ = undef; <$mounts> };
848 close $mounts;
849 print {$pfd} $mountdata;
850 close $pfd;
851
852 while (waitpid($child, 0) != $child) {}
853 die "failed to sync container namespace\n" if $? != 0;
854 }
855
856 sub template_create {
857 my ($vmid, $conf) = @_;
858
859 my $storecfg = PVE::Storage::config();
860
861 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
862 my $volid = $rootinfo->{volume};
863
864 die "Template feature is not available for '$volid'\n"
865 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
866
867 PVE::Storage::activate_volumes($storecfg, [$volid]);
868
869 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
870 $rootinfo->{volume} = $template_volid;
871 $conf->{rootfs} = PVE::LXC::Config->print_ct_mountpoint($rootinfo, 1);
872
873 PVE::LXC::Config->write_config($vmid, $conf);
874 }
875
876 sub check_ct_modify_config_perm {
877 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
878
879 return 1 if $authuser eq 'root@pam';
880
881 my $check = sub {
882 my ($opt, $delete) = @_;
883 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
884 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
885 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
886 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
887 return if $delete;
888 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
889 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
890 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
891 if $data->{type} ne 'volume';
892 } elsif ($opt eq 'memory' || $opt eq 'swap') {
893 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
894 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
895 $opt eq 'searchdomain' || $opt eq 'hostname') {
896 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
897 } else {
898 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
899 }
900 };
901
902 foreach my $opt (keys %$newconf) {
903 &$check($opt, 0);
904 }
905 foreach my $opt (@$delete) {
906 &$check($opt, 1);
907 }
908
909 return 1;
910 }
911
912 sub umount_all {
913 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
914
915 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
916 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
917
918 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
919 my ($ms, $mountpoint) = @_;
920
921 my $volid = $mountpoint->{volume};
922 my $mount = $mountpoint->{mp};
923
924 return if !$volid || !$mount;
925
926 my $mount_path = "$rootdir/$mount";
927 $mount_path =~ s!/+!/!g;
928
929 return if !PVE::ProcFSTools::is_mounted($mount_path);
930
931 eval {
932 PVE::Tools::run_command(['umount', '-d', $mount_path]);
933 };
934 if (my $err = $@) {
935 if ($noerr) {
936 warn $err;
937 } else {
938 die $err;
939 }
940 }
941 });
942 }
943
944 sub mount_all {
945 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
946
947 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
948 File::Path::make_path($rootdir);
949
950 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
951 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
952
953 eval {
954 PVE::LXC::Config->foreach_mountpoint($conf, sub {
955 my ($ms, $mountpoint) = @_;
956
957 $mountpoint->{ro} = 0 if $ignore_ro;
958
959 mountpoint_mount($mountpoint, $rootdir, $storage_cfg);
960 });
961 };
962 if (my $err = $@) {
963 warn "mounting container failed\n";
964 umount_all($vmid, $storage_cfg, $conf, 1);
965 die $err;
966 }
967
968 return $rootdir;
969 }
970
971
972 sub mountpoint_mount_path {
973 my ($mountpoint, $storage_cfg, $snapname) = @_;
974
975 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
976 }
977
978 sub query_loopdev {
979 my ($path) = @_;
980 my $found;
981 my $parser = sub {
982 my $line = shift;
983 if ($line =~ m@^(/dev/loop\d+):@) {
984 $found = $1;
985 }
986 };
987 my $cmd = ['losetup', '--associated', $path];
988 PVE::Tools::run_command($cmd, outfunc => $parser);
989 return $found;
990 }
991
992 # Run a function with a file attached to a loop device.
993 # The loop device is always detached afterwards (or set to autoclear).
994 # Returns the loop device.
995 sub run_with_loopdev {
996 my ($func, $file) = @_;
997 my $device = query_loopdev($file);
998 # Try to reuse an existing device
999 if ($device) {
1000 # We assume that whoever setup the loop device is responsible for
1001 # detaching it.
1002 &$func($device);
1003 return $device;
1004 }
1005
1006 my $parser = sub {
1007 my $line = shift;
1008 if ($line =~ m@^(/dev/loop\d+)$@) {
1009 $device = $1;
1010 }
1011 };
1012 PVE::Tools::run_command(['losetup', '--show', '-f', $file], outfunc => $parser);
1013 die "failed to setup loop device for $file\n" if !$device;
1014 eval { &$func($device); };
1015 my $err = $@;
1016 PVE::Tools::run_command(['losetup', '-d', $device]);
1017 die $err if $err;
1018 return $device;
1019 }
1020
1021 # In scalar mode: returns a file handle to the deepest directory node.
1022 # In list context: returns a list of:
1023 # * the deepest directory node
1024 # * the 2nd deepest directory (parent of the above)
1025 # * directory name of the last directory
1026 # So that the path $2/$3 should lead to $1 afterwards.
1027 sub walk_tree_nofollow($$$) {
1028 my ($start, $subdir, $mkdir) = @_;
1029
1030 # splitdir() returns '' for empty components including the leading /
1031 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1032
1033 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1034 or die "failed to open start directory $start: $!\n";
1035
1036 my $dir = $start;
1037 my $last_component = undef;
1038 my $second = $fd;
1039 foreach my $component (@comps) {
1040 $dir .= "/$component";
1041 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1042
1043 if (!$next) {
1044 # failed, check for symlinks and try to create the path
1045 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
1046 die "cannot open directory $dir: $!\n" if !$mkdir;
1047
1048 # We don't check for errors on mkdirat() here and just try to
1049 # openat() again, since at least one error (EEXIST) is an
1050 # expected possibility if multiple containers start
1051 # simultaneously. If someone else injects a symlink now then
1052 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1053 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1054
1055 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1056 die "failed to create path: $dir: $!\n" if !$next;
1057 }
1058
1059 close $second if defined($last_component);
1060 $last_component = $component;
1061 $second = $fd;
1062 $fd = $next;
1063 }
1064
1065 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1066 close $second if defined($last_component);
1067 return $fd;
1068 }
1069
1070 # To guard against symlink attack races against other currently running
1071 # containers with shared recursive bind mount hierarchies we prepare a
1072 # directory handle for the directory we're mounting over to verify the
1073 # mountpoint afterwards.
1074 sub __bindmount_prepare {
1075 my ($hostroot, $dir) = @_;
1076 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1077 return $srcdh;
1078 }
1079
1080 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1081 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1082 # we intended to bind mount.
1083 sub __bindmount_verify {
1084 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1085 my $destdh;
1086 if ($parentfd) {
1087 # Open the mount point path coming from the parent directory since the
1088 # filehandle we would have gotten as first result of walk_tree_nofollow
1089 # earlier is still a handle to the underlying directory instead of the
1090 # mounted path.
1091 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1092 die "failed to open mount point: $!\n" if !$destdh;
1093 if ($ro) {
1094 my $dot = '.';
1095 # no separate function because 99% of the time it's the wrong thing to use.
1096 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
1097 die "failed to mark bind mount read only\n";
1098 }
1099 die "read-only check failed: $!\n" if $! != EROFS;
1100 }
1101 } else {
1102 # For the rootfs we don't have a parentfd so we open the path directly.
1103 # Note that this means bindmounting any prefix of the host's
1104 # /var/lib/lxc/$vmid path into another container is considered a grave
1105 # security error.
1106 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
1107 die "failed to open mount point: $!\n" if !$destdh;
1108 }
1109
1110 my ($srcdev, $srcinode) = stat($srcdh);
1111 my ($dstdev, $dstinode) = stat($destdh);
1112 close $srcdh;
1113 close $destdh;
1114
1115 return ($srcdev == $dstdev && $srcinode == $dstinode);
1116 }
1117
1118 # Perform the actual bind mounting:
1119 sub __bindmount_do {
1120 my ($dir, $dest, $ro, @extra_opts) = @_;
1121 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1122 if ($ro) {
1123 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1124 if (my $err = $@) {
1125 warn "bindmount error\n";
1126 # don't leave writable bind-mounts behind...
1127 PVE::Tools::run_command(['umount', $dest]);
1128 die $err;
1129 }
1130 }
1131 }
1132
1133 sub bindmount {
1134 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1135
1136 my $srcdh = __bindmount_prepare('/', $dir);
1137
1138 __bindmount_do($dir, $dest, $ro, @extra_opts);
1139
1140 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
1141 PVE::Tools::run_command(['umount', $dest]);
1142 die "detected mount path change at: $dir\n";
1143 }
1144 }
1145
1146 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1147 # from $rootdir and $mount and walk the path from $rootdir to the final
1148 # directory to check for symlinks.
1149 sub __mount_prepare_rootdir {
1150 my ($rootdir, $mount) = @_;
1151 $rootdir =~ s!/+!/!g;
1152 $rootdir =~ s!/+$!!;
1153 my $mount_path = "$rootdir/$mount";
1154 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1);
1155 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1156 }
1157
1158 # use $rootdir = undef to just return the corresponding mount path
1159 sub mountpoint_mount {
1160 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1161
1162 my $volid = $mountpoint->{volume};
1163 my $mount = $mountpoint->{mp};
1164 my $type = $mountpoint->{type};
1165 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1166 my $mounted_dev;
1167
1168 return if !$volid || !$mount;
1169
1170 $mount =~ s!/+!/!g;
1171
1172 my $mount_path;
1173 my ($mpfd, $parentfd, $last_dir);
1174
1175 if (defined($rootdir)) {
1176 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1177 __mount_prepare_rootdir($rootdir, $mount);
1178 }
1179
1180 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1181
1182 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1183
1184 my $optstring = '';
1185 my $acl = $mountpoint->{acl};
1186 if (defined($acl)) {
1187 $optstring .= ($acl ? 'acl' : 'noacl');
1188 }
1189 my $readonly = $mountpoint->{ro};
1190
1191 my @extra_opts = ('-o', $optstring) if $optstring;
1192
1193 if ($storage) {
1194
1195 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1196
1197 # early sanity checks:
1198 # we otherwise call realpath on the rbd url
1199 die "containers on rbd storage without krbd are not supported\n"
1200 if $scfg->{type} eq 'rbd' && !$scfg->{krbd};
1201
1202 my $path = PVE::Storage::path($storage_cfg, $volid, $snapname);
1203
1204 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1205 PVE::Storage::parse_volname($storage_cfg, $volid);
1206
1207 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1208
1209 if ($format eq 'subvol') {
1210 if ($mount_path) {
1211 if ($snapname) {
1212 if ($scfg->{type} eq 'zfspool') {
1213 my $path_arg = $path;
1214 $path_arg =~ s!^/+!!;
1215 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1216 } else {
1217 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1218 }
1219 } else {
1220 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1221 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1222 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1223 $name .= "\@$snapname" if defined($snapname);
1224 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1225 }
1226 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1227 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1228 }
1229 }
1230 return wantarray ? ($path, 0, undef) : $path;
1231 } elsif ($format eq 'raw' || $format eq 'iso') {
1232 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1233 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1234 # Our autodev hook expects the /dev/dm-* device currently
1235 # and will create the /dev/mapper symlink accordingly
1236 $path = Cwd::realpath($path);
1237 die "failed to get device path\n" if !$path;
1238 ($path) = ($path =~ /^(.*)$/s); #untaint
1239 my $domount = sub {
1240 my ($path) = @_;
1241 if ($mount_path) {
1242 if ($format eq 'iso') {
1243 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1244 } elsif ($isBase || defined($snapname)) {
1245 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1246 } else {
1247 if ($quota) {
1248 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1249 }
1250 push @extra_opts, '-o', 'ro' if $readonly;
1251 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1252 }
1253 }
1254 };
1255 my $use_loopdev = 0;
1256 if ($scfg->{path}) {
1257 $mounted_dev = run_with_loopdev($domount, $path);
1258 $use_loopdev = 1;
1259 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1260 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
1261 $mounted_dev = $path;
1262 &$domount($path);
1263 } else {
1264 die "unsupported storage type '$scfg->{type}'\n";
1265 }
1266 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
1267 } else {
1268 die "unsupported image format '$format'\n";
1269 }
1270 } elsif ($type eq 'device') {
1271 push @extra_opts, '-o', 'ro' if $readonly;
1272 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1273 # See the NOTE above about devicemapper canonicalization
1274 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
1275 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1276 return wantarray ? ($volid, 0, $devpath) : $volid;
1277 } elsif ($type eq 'bind') {
1278 die "directory '$volid' does not exist\n" if ! -d $volid;
1279 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1280 warn "cannot enable quota control for bind mounts\n" if $quota;
1281 return wantarray ? ($volid, 0, undef) : $volid;
1282 }
1283
1284 die "unsupported storage";
1285 }
1286
1287 sub mkfs {
1288 my ($dev, $rootuid, $rootgid) = @_;
1289
1290 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1291 '-E', "root_owner=$rootuid:$rootgid",
1292 $dev]);
1293 }
1294
1295 sub format_disk {
1296 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1297
1298 if ($volid =~ m!^/dev/.+!) {
1299 mkfs($volid);
1300 return;
1301 }
1302
1303 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1304
1305 die "cannot format volume '$volid' with no storage\n" if !$storage;
1306
1307 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1308
1309 my $path = PVE::Storage::path($storage_cfg, $volid);
1310
1311 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1312 PVE::Storage::parse_volname($storage_cfg, $volid);
1313
1314 die "cannot format volume '$volid' (format == $format)\n"
1315 if $format ne 'raw';
1316
1317 mkfs($path, $rootuid, $rootgid);
1318 }
1319
1320 sub destroy_disks {
1321 my ($storecfg, $vollist) = @_;
1322
1323 foreach my $volid (@$vollist) {
1324 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1325 warn $@ if $@;
1326 }
1327 }
1328
1329 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1330 sub create_disks {
1331 my ($storecfg, $vmid, $settings, $conf) = @_;
1332
1333 my $vollist = [];
1334
1335 eval {
1336 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1337 my $chown_vollist = [];
1338
1339 PVE::LXC::Config->foreach_mountpoint($settings, sub {
1340 my ($ms, $mountpoint) = @_;
1341
1342 my $volid = $mountpoint->{volume};
1343 my $mp = $mountpoint->{mp};
1344
1345 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1346
1347 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1348 my ($storeid, $size_gb) = ($1, $2);
1349
1350 my $size_kb = int(${size_gb}*1024) * 1024;
1351
1352 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1353 # fixme: use better naming ct-$vmid-disk-X.raw?
1354
1355 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1356 if ($size_kb > 0) {
1357 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1358 undef, $size_kb);
1359 format_disk($storecfg, $volid, $rootuid, $rootgid);
1360 } else {
1361 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1362 undef, 0);
1363 push @$chown_vollist, $volid;
1364 }
1365 } elsif ($scfg->{type} eq 'zfspool') {
1366
1367 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1368 undef, $size_kb);
1369 push @$chown_vollist, $volid;
1370 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1371
1372 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1373 format_disk($storecfg, $volid, $rootuid, $rootgid);
1374
1375 } elsif ($scfg->{type} eq 'rbd') {
1376
1377 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd};
1378 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1379 format_disk($storecfg, $volid, $rootuid, $rootgid);
1380 } else {
1381 die "unable to create containers on storage type '$scfg->{type}'\n";
1382 }
1383 push @$vollist, $volid;
1384 $mountpoint->{volume} = $volid;
1385 $mountpoint->{size} = $size_kb * 1024;
1386 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1387 } else {
1388 # use specified/existing volid/dir/device
1389 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1390 }
1391 });
1392
1393 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1394 foreach my $volid (@$chown_vollist) {
1395 my $path = PVE::Storage::path($storecfg, $volid, undef);
1396 chown($rootuid, $rootgid, $path);
1397 }
1398 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
1399 };
1400 # free allocated images on error
1401 if (my $err = $@) {
1402 destroy_disks($storecfg, $vollist);
1403 die $err;
1404 }
1405 return $vollist;
1406 }
1407
1408 # bash completion helper
1409
1410 sub complete_os_templates {
1411 my ($cmdname, $pname, $cvalue) = @_;
1412
1413 my $cfg = PVE::Storage::config();
1414
1415 my $storeid;
1416
1417 if ($cvalue =~ m/^([^:]+):/) {
1418 $storeid = $1;
1419 }
1420
1421 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1422 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1423
1424 my $res = [];
1425 foreach my $id (keys %$data) {
1426 foreach my $item (@{$data->{$id}}) {
1427 push @$res, $item->{volid} if defined($item->{volid});
1428 }
1429 }
1430
1431 return $res;
1432 }
1433
1434 my $complete_ctid_full = sub {
1435 my ($running) = @_;
1436
1437 my $idlist = vmstatus();
1438
1439 my $active_hash = list_active_containers();
1440
1441 my $res = [];
1442
1443 foreach my $id (keys %$idlist) {
1444 my $d = $idlist->{$id};
1445 if (defined($running)) {
1446 next if $d->{template};
1447 next if $running && !$active_hash->{$id};
1448 next if !$running && $active_hash->{$id};
1449 }
1450 push @$res, $id;
1451
1452 }
1453 return $res;
1454 };
1455
1456 sub complete_ctid {
1457 return &$complete_ctid_full();
1458 }
1459
1460 sub complete_ctid_stopped {
1461 return &$complete_ctid_full(0);
1462 }
1463
1464 sub complete_ctid_running {
1465 return &$complete_ctid_full(1);
1466 }
1467
1468 sub parse_id_maps {
1469 my ($conf) = @_;
1470
1471 my $id_map = [];
1472 my $rootuid = 0;
1473 my $rootgid = 0;
1474
1475 my $lxc = $conf->{lxc};
1476 foreach my $entry (@$lxc) {
1477 my ($key, $value) = @$entry;
1478 next if $key ne 'lxc.id_map';
1479 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1480 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1481 push @$id_map, [$type, $ct, $host, $length];
1482 if ($ct == 0) {
1483 $rootuid = $host if $type eq 'u';
1484 $rootgid = $host if $type eq 'g';
1485 }
1486 } else {
1487 die "failed to parse id_map: $value\n";
1488 }
1489 }
1490
1491 if (!@$id_map && $conf->{unprivileged}) {
1492 # Should we read them from /etc/subuid?
1493 $id_map = [ ['u', '0', '100000', '65536'],
1494 ['g', '0', '100000', '65536'] ];
1495 $rootuid = $rootgid = 100000;
1496 }
1497
1498 return ($id_map, $rootuid, $rootgid);
1499 }
1500
1501 sub userns_command {
1502 my ($id_map) = @_;
1503 if (@$id_map) {
1504 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1505 }
1506 return [];
1507 }
1508
1509
1510 1;