]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC.pm
Revert "vmstatus: Align name if not set in config to VMs"
[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_WRONLY O_NOFOLLOW O_DIRECTORY);
14 use Errno qw(ELOOP ENOTDIR EROFS ECONNREFUSED ENOSYS EEXIST);
15 use IO::Socket::UNIX;
16
17 use PVE::Exception qw(raise_perm_exc);
18 use PVE::Storage;
19 use PVE::SafeSyslog;
20 use PVE::INotify;
21 use PVE::JSONSchema qw(get_standard_option);
22 use PVE::Tools qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH AT_FDCWD);
23 use PVE::CpuSet;
24 use PVE::Network;
25 use PVE::AccessControl;
26 use PVE::ProcFSTools;
27 use PVE::Syscall qw(:fsmount);
28 use PVE::LXC::Config;
29 use PVE::GuestHelpers;
30 use PVE::LXC::Tools;
31
32 use Time::HiRes qw (gettimeofday);
33
34 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
35
36 my $nodename = PVE::INotify::nodename();
37
38 my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
39
40 sub config_list {
41 my $vmlist = PVE::Cluster::get_vmlist();
42 my $res = {};
43 return $res if !$vmlist || !$vmlist->{ids};
44 my $ids = $vmlist->{ids};
45
46 foreach my $vmid (keys %$ids) {
47 next if !$vmid; # skip CT0
48 my $d = $ids->{$vmid};
49 next if !$d->{node} || $d->{node} ne $nodename;
50 next if !$d->{type} || $d->{type} ne 'lxc';
51 $res->{$vmid} = { type => 'lxc', vmid => $vmid };
52 }
53 return $res;
54 }
55
56 # container status helpers
57
58 sub list_active_containers {
59
60 my $filename = "/proc/net/unix";
61
62 # similar test is used by lcxcontainers.c: list_active_containers
63 my $res = {};
64
65 my $fh = IO::File->new ($filename, "r");
66 return $res if !$fh;
67
68 while (defined(my $line = <$fh>)) {
69 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
70 my $path = $1;
71 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
72 $res->{$1} = 1;
73 }
74 }
75 }
76
77 close($fh);
78
79 return $res;
80 }
81
82 # warning: this is slow
83 sub check_running {
84 my ($vmid) = @_;
85
86 my $active_hash = list_active_containers();
87
88 return 1 if defined($active_hash->{$vmid});
89
90 return undef;
91 }
92
93 sub get_container_disk_usage {
94 my ($vmid, $pid) = @_;
95
96 return PVE::Tools::df("/proc/$pid/root/", 1);
97 }
98
99 my $last_proc_vmid_stat;
100
101 my $parse_cpuacct_stat = sub {
102 my ($vmid, $unprivileged) = @_;
103
104 my $raw = read_cgroup_value('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
105
106 my $stat = {};
107
108 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
109
110 $stat->{utime} = $1;
111 $stat->{stime} = $2;
112
113 }
114
115 return $stat;
116 };
117
118 our $vmstatus_return_properties = {
119 vmid => get_standard_option('pve-vmid'),
120 status => {
121 description => "LXC Container status.",
122 type => 'string',
123 enum => ['stopped', 'running'],
124 },
125 maxmem => {
126 description => "Maximum memory in bytes.",
127 type => 'integer',
128 optional => 1,
129 renderer => 'bytes',
130 },
131 maxswap => {
132 description => "Maximum SWAP memory in bytes.",
133 type => 'integer',
134 optional => 1,
135 renderer => 'bytes',
136 },
137 maxdisk => {
138 description => "Root disk size in bytes.",
139 type => 'integer',
140 optional => 1,
141 renderer => 'bytes',
142 },
143 name => {
144 description => "Container name.",
145 type => 'string',
146 optional => 1,
147 },
148 uptime => {
149 description => "Uptime.",
150 type => 'integer',
151 optional => 1,
152 renderer => 'duration',
153 },
154 cpus => {
155 description => "Maximum usable CPUs.",
156 type => 'number',
157 optional => 1,
158 },
159 lock => {
160 description => "The current config lock, if any.",
161 type => 'string',
162 optional => 1,
163 },
164 tags => {
165 description => "The current configured tags, if any.",
166 type => 'string',
167 optional => 1,
168 }
169 };
170
171 sub vmstatus {
172 my ($opt_vmid) = @_;
173
174 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc', vmid => $opt_vmid }} : config_list();
175
176 my $active_hash = list_active_containers();
177
178 my $cpucount = $cpuinfo->{cpus} || 1;
179
180 my $cdtime = gettimeofday;
181
182 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
183 my $clock_ticks = POSIX::sysconf(&POSIX::_SC_CLK_TCK);
184
185 my $unprivileged = {};
186
187 foreach my $vmid (keys %$list) {
188 my $d = $list->{$vmid};
189
190 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
191 warn $@ if $@; # ignore errors (consider them stopped)
192
193 $d->{status} = $active_hash->{$vmid} ? 'running' : 'stopped';
194
195 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
196 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
197
198 $unprivileged->{$vmid} = $conf->{unprivileged};
199
200 $d->{name} = $conf->{'hostname'} || "CT$vmid";
201 $d->{name} =~ s/[\s]//g;
202
203 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
204 $d->{cpus} = $cpucount if !$d->{cpus};
205
206 $d->{lock} = $conf->{lock} || '';
207 $d->{tags} = $conf->{tags} if defined($conf->{tags});
208
209 if ($d->{pid}) {
210 my $res = get_container_disk_usage($vmid, $d->{pid});
211 $d->{disk} = $res->{used};
212 $d->{maxdisk} = $res->{total};
213 } else {
214 $d->{disk} = 0;
215 # use 4GB by default ??
216 if (my $rootfs = $conf->{rootfs}) {
217 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($rootfs);
218 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
219 } else {
220 $d->{maxdisk} = 4*1024*1024*1024;
221 }
222 }
223
224 $d->{mem} = 0;
225 $d->{swap} = 0;
226 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
227 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
228
229 $d->{uptime} = 0;
230 $d->{cpu} = 0;
231
232 $d->{netout} = 0;
233 $d->{netin} = 0;
234
235 $d->{diskread} = 0;
236 $d->{diskwrite} = 0;
237
238 $d->{template} = PVE::LXC::Config->is_template($conf);
239 $d->{lock} = $conf->{lock} if $conf->{lock};
240 }
241
242 foreach my $vmid (keys %$list) {
243 my $d = $list->{$vmid};
244 my $pid = $d->{pid};
245
246 next if !$pid; # skip stopped CTs
247
248 my $proc_pid_stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
249 $d->{uptime} = int(($uptime - $proc_pid_stat->{starttime}) / $clock_ticks); # the method lxcfs uses
250
251 my $unpriv = $unprivileged->{$vmid};
252
253 if (-d '/sys/fs/cgroup/memory') {
254 my $memory_stat = read_cgroup_list('memory', $vmid, $unpriv, 'memory.stat');
255 my $mem_usage_in_bytes = read_cgroup_value('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
256
257 $d->{mem} = $mem_usage_in_bytes - $memory_stat->{total_cache};
258 $d->{swap} = read_cgroup_value('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
259 } else {
260 $d->{mem} = 0;
261 $d->{swap} = 0;
262 }
263
264 if (-d '/sys/fs/cgroup/blkio') {
265 my $blkio_bytes = read_cgroup_value('blkio', $vmid, 0, 'blkio.throttle.io_service_bytes', 1); # don't check if unpriv
266 my @bytes = split(/\n/, $blkio_bytes);
267 foreach my $byte (@bytes) {
268 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
269 $d->{diskread} += $2 if $key eq 'Read';
270 $d->{diskwrite} += $2 if $key eq 'Write';
271 }
272 }
273 } else {
274 $d->{diskread} = 0;
275 $d->{diskwrite} = 0;
276 }
277
278 if (-d '/sys/fs/cgroup/cpuacct') {
279 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
280
281 my $used = $pstat->{utime} + $pstat->{stime};
282
283 my $old = $last_proc_vmid_stat->{$vmid};
284 if (!$old) {
285 $last_proc_vmid_stat->{$vmid} = {
286 time => $cdtime,
287 used => $used,
288 cpu => 0,
289 };
290 next;
291 }
292
293 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
294
295 if ($dtime > 1000) {
296 my $dutime = $used - $old->{used};
297
298 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
299 $last_proc_vmid_stat->{$vmid} = {
300 time => $cdtime,
301 used => $used,
302 cpu => $d->{cpu},
303 };
304 } else {
305 $d->{cpu} = $old->{cpu};
306 }
307 } else {
308 $d->{cpu} = 0;
309 }
310 }
311
312 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
313
314 foreach my $dev (keys %$netdev) {
315 next if $dev !~ m/^veth([1-9]\d*)i/;
316 my $vmid = $1;
317 my $d = $list->{$vmid};
318
319 next if !$d;
320
321 $d->{netout} += $netdev->{$dev}->{receive};
322 $d->{netin} += $netdev->{$dev}->{transmit};
323
324 }
325
326 return $list;
327 }
328
329 sub read_cgroup_list($$$$) {
330 my ($group, $vmid, $unprivileged, $name) = @_;
331
332 my $content = read_cgroup_value($group, $vmid, $unprivileged, $name, 1);
333
334 return { split(/\s+/, $content) };
335 }
336
337 sub read_cgroup_value($$$$$) {
338 my ($group, $vmid, $unprivileged, $name, $full) = @_;
339
340 my $nsdir = $unprivileged ? '' : 'ns/';
341 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
342
343 return PVE::Tools::file_get_contents($path) if $full;
344
345 return PVE::Tools::file_read_firstline($path);
346 }
347
348 sub write_cgroup_value {
349 my ($group, $vmid, $name, $value) = @_;
350
351 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
352 PVE::ProcFSTools::write_proc_entry($path, $value) if -e $path;
353
354 }
355
356 sub find_lxc_console_pids {
357
358 my $res = {};
359
360 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
361 my ($pid) = @_;
362
363 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
364 return if !$cmdline;
365
366 my @args = split(/\0/, $cmdline);
367
368 # search for lxc-console -n <vmid>
369 return if scalar(@args) != 3;
370 return if $args[1] ne '-n';
371 return if $args[2] !~ m/^\d+$/;
372 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
373
374 my $vmid = $args[2];
375
376 push @{$res->{$vmid}}, $pid;
377 });
378
379 return $res;
380 }
381
382 sub find_lxc_pid {
383 my ($vmid) = @_;
384
385 my $pid = undef;
386 my $parser = sub {
387 my $line = shift;
388 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
389 };
390 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
391
392 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
393
394 return $pid;
395 }
396
397 sub open_pid_fd($) {
398 my ($pid) = @_;
399 sysopen(my $fd, "/proc/$pid", O_RDONLY | O_DIRECTORY)
400 or die "failed to open /proc/$pid pid fd\n";
401 return $fd;
402 }
403
404 sub open_lxc_pid {
405 my ($vmid) = @_;
406
407 # Find the pid and open:
408 my $pid = find_lxc_pid($vmid);
409 my $fd = open_pid_fd($pid);
410
411 # Verify:
412 my $pid2 = find_lxc_pid($vmid);
413
414 return () if $pid != $pid2;
415 return ($pid, $fd);
416 }
417
418 sub open_ppid {
419 my ($pid) = @_;
420
421 # Find the parent pid via proc and open it:
422 my $stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
423 my $ppid = $stat->{ppid} // die "failed to get parent pid\n";
424
425 my $fd = open_pid_fd($ppid);
426
427 # Verify:
428 $stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
429 my $ppid2 = $stat->{ppid} // die "failed to get parent pid for verification\n";
430
431 return () if $ppid != $ppid2;
432 return ($ppid, $fd);
433 }
434
435 # Note: we cannot use Net:IP, because that only allows strict
436 # CIDR networks
437 sub parse_ipv4_cidr {
438 my ($cidr, $noerr) = @_;
439
440 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
441 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
442 }
443
444 return undef if $noerr;
445
446 die "unable to parse ipv4 address/mask\n";
447 }
448
449 sub get_cgroup_subsystems {
450 my $v1 = {};
451 my $v2 = 0;
452 my $data = PVE::Tools::file_get_contents('/proc/self/cgroup');
453 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
454 my $type = $1;
455 if (length($type)) {
456 $v1->{$_} = 1 foreach split(/,/, $type);
457 } else {
458 $v2 = 1;
459 }
460 }
461 return wantarray ? ($v1, $v2) : $v1;
462 }
463
464 # Currently we do not need to create seccomp profile 'files' as the only
465 # choice our configuration actually allows is "with or without keyctl()",
466 # so we distinguish between using lxc's "default" seccomp profile and our
467 # added pve-userns.seccomp file.
468 #
469 # This returns a configuration line added to the raw lxc config.
470 sub make_seccomp_config {
471 my ($conf, $unprivileged, $features) = @_;
472 # User-configured profile has precedence, note that the user's entry would
473 # be written 'after' this line anyway...
474 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.seccomp.profile')) {
475 # Warn the user if this conflicts with a feature:
476 if ($features->{keyctl}) {
477 warn "explicitly configured lxc.seccomp.profile overrides the following settings: features:keyctl\n";
478 }
479 return '';
480 }
481
482 # Privileged containers keep using the default (which is already part of
483 # the files included via lxc.include, so we don't need to write it out,
484 # that way it stays admin-configurable via /usr/share/lxc/config/... as
485 # well)
486 return '' if !$unprivileged;
487
488 # Unprivileged containers will get keyctl() disabled by default as a
489 # workaround for systemd-networkd behavior. But we have an option to
490 # explicitly enable it:
491 return '' if $features->{keyctl};
492
493 # Finally we're in an unprivileged container without `keyctl` set
494 # explicitly. We have a file prepared for this:
495 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
496 }
497
498 # Since lxc-3.0.2 we can have lxc generate a profile for the container
499 # automatically. The default should be equivalent to the old
500 # `lxc-container-default-cgns` profile.
501 #
502 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
503 # additional lines into the profile. We can use that to allow mounting specific
504 # file systems.
505 sub make_apparmor_config {
506 my ($conf, $unprivileged, $features) = @_;
507
508 # user-configured profile has precedence, but first we go through our own
509 # code to figure out whether we should warn the user:
510
511 my $raw = "lxc.apparmor.profile = generated\n";
512 my @profile_uses;
513
514 if ($features->{fuse}) {
515 # For the informational warning:
516 push @profile_uses, 'features:fuse';
517 }
518
519 # There's lxc.apparmor.allow_nesting now, which will add the necessary
520 # apparmor lines, create an apparmor namespace for the container, but also
521 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
522 # lxcfs mounted over them, because that would prevent the container from
523 # mounting new instances of them for nested containers.
524 if ($features->{nesting}) {
525 push @profile_uses, 'features:nesting';
526 $raw .= "lxc.apparmor.allow_nesting = 1\n"
527 } else {
528 # In the default profile in /etc/apparmor.d we patch this in because
529 # otherwise a container can for example run `chown` on /sys, breaking
530 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
531 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
532 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
533 # Preferably we could use the 'remount' flag but this does not sit well
534 # with apparmor_parser currently:
535 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
536 }
537
538 if (my $mount = $features->{mount}) {
539 push @profile_uses, 'features:mount';
540 foreach my $fs (PVE::Tools::split_list($mount)) {
541 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
542 }
543 }
544
545 # More to come?
546
547 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.apparmor.profile')) {
548 if (length(my $used = join(', ', @profile_uses))) {
549 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
550 }
551 return '';
552 }
553
554 return $raw;
555 }
556
557 sub update_lxc_config {
558 my ($vmid, $conf) = @_;
559
560 my $dir = "/var/lib/lxc/$vmid";
561
562 if ($conf->{template}) {
563
564 unlink "$dir/config";
565
566 return;
567 }
568
569 my $raw = '';
570
571 die "missing 'arch' - internal error" if !$conf->{arch};
572 $raw .= "lxc.arch = $conf->{arch}\n";
573
574 my $custom_idmap = PVE::LXC::Config->has_lxc_entry($conf, 'lxc.idmap');
575 my $unprivileged = $conf->{unprivileged} || $custom_idmap;
576
577 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
578
579 my $cfgpath = '/usr/share/lxc/config';
580 my $inc = "$cfgpath/$ostype.common.conf";
581 $inc ="$cfgpath/common.conf" if !-f $inc;
582 $raw .= "lxc.include = $inc\n";
583 if ($unprivileged) {
584 $inc = "$cfgpath/$ostype.userns.conf";
585 $inc = "$cfgpath/userns.conf" if !-f $inc;
586 $raw .= "lxc.include = $inc\n";
587 }
588
589 my $features = PVE::LXC::Config->parse_features($conf->{features});
590
591 $raw .= make_seccomp_config($conf, $unprivileged, $features);
592 $raw .= make_apparmor_config($conf, $unprivileged, $features);
593 if ($features->{fuse}) {
594 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
595 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
596 }
597
598 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
599 # cannot be exposed to the container with r/w access (cgroup perms).
600 # When this is enabled mounts will still remain in the monitor's namespace
601 # after the container unmounted them and thus will not detach from their
602 # files while the container is running!
603 $raw .= "lxc.monitor.unshare = 1\n";
604
605 my $cgv1 = get_cgroup_subsystems();
606
607 # Should we read them from /etc/subuid?
608 if ($unprivileged && !$custom_idmap) {
609 $raw .= "lxc.idmap = u 0 100000 65536\n";
610 $raw .= "lxc.idmap = g 0 100000 65536\n";
611 }
612
613 if (!PVE::LXC::Config->has_dev_console($conf)) {
614 $raw .= "lxc.console.path = none\n";
615 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices};
616 }
617
618 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
619 $raw .= "lxc.tty.max = $ttycount\n";
620
621 # some init scripts expect a linux terminal (turnkey).
622 $raw .= "lxc.environment = TERM=linux\n";
623
624 my $utsname = $conf->{hostname} || "CT$vmid";
625 $raw .= "lxc.uts.name = $utsname\n";
626
627 if ($cgv1->{memory}) {
628 my $memory = $conf->{memory} || 512;
629 my $swap = $conf->{swap} // 0;
630
631 my $lxcmem = int($memory*1024*1024);
632 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
633
634 my $lxcswap = int(($memory + $swap)*1024*1024);
635 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
636 }
637
638 if ($cgv1->{cpu}) {
639 if (my $cpulimit = $conf->{cpulimit}) {
640 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
641 my $value = int(100000*$cpulimit);
642 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
643 }
644
645 my $shares = $conf->{cpuunits} || 1024;
646 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
647 }
648
649 die "missing 'rootfs' configuration\n"
650 if !defined($conf->{rootfs});
651
652 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
653
654 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
655
656 foreach my $k (sort keys %$conf) {
657 next if $k !~ m/^net(\d+)$/;
658 my $ind = $1;
659 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
660 $raw .= "lxc.net.$ind.type = veth\n";
661 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
662 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
663 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name});
664 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu});
665 }
666
667 if ($cgv1->{cpuset}) {
668 my $had_cpuset = 0;
669 if (my $lxcconf = $conf->{lxc}) {
670 foreach my $entry (@$lxcconf) {
671 my ($k, $v) = @$entry;
672 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
673 $raw .= "$k = $v\n";
674 }
675 }
676
677 my $cores = $conf->{cores};
678 if (!$had_cpuset && $cores) {
679 my $cpuset = eval { PVE::CpuSet->new_from_cgroup('lxc', 'effective_cpus') };
680 $cpuset = PVE::CpuSet->new_from_cgroup('', 'effective_cpus') if !$cpuset;
681 my @members = $cpuset->members();
682 while (scalar(@members) > $cores) {
683 my $randidx = int(rand(scalar(@members)));
684 $cpuset->delete($members[$randidx]);
685 splice(@members, $randidx, 1); # keep track of the changes
686 }
687 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
688 }
689 }
690
691 File::Path::mkpath("$dir/rootfs");
692
693 PVE::Tools::file_set_contents("$dir/config", $raw);
694 }
695
696 # verify and cleanup nameserver list (replace \0 with ' ')
697 sub verify_nameserver_list {
698 my ($nameserver_list) = @_;
699
700 my @list = ();
701 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
702 PVE::JSONSchema::pve_verify_ip($server);
703 push @list, $server;
704 }
705
706 return join(' ', @list);
707 }
708
709 sub verify_searchdomain_list {
710 my ($searchdomain_list) = @_;
711
712 my @list = ();
713 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
714 # todo: should we add checks for valid dns domains?
715 push @list, $server;
716 }
717
718 return join(' ', @list);
719 }
720
721 sub get_console_command {
722 my ($vmid, $conf, $escapechar) = @_;
723
724 # '-1' as $escapechar disables keyboard escape sequence
725 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
726
727 my $cmode = PVE::LXC::Config->get_cmode($conf);
728
729 my $cmd = [];
730 if ($cmode eq 'console') {
731 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
732 push @$cmd, '-e', $escapechar if $escapechar;
733 } elsif ($cmode eq 'tty') {
734 push @$cmd, 'lxc-console', '-n', $vmid;
735 push @$cmd, '-e', $escapechar if $escapechar;
736 } elsif ($cmode eq 'shell') {
737 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
738 } else {
739 die "internal error";
740 }
741
742 return $cmd;
743 }
744
745 sub get_primary_ips {
746 my ($conf) = @_;
747
748 # return data from net0
749
750 return undef if !defined($conf->{net0});
751 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
752
753 my $ipv4 = $net->{ip};
754 if ($ipv4) {
755 if ($ipv4 =~ /^(dhcp|manual)$/) {
756 $ipv4 = undef
757 } else {
758 $ipv4 =~ s!/\d+$!!;
759 }
760 }
761 my $ipv6 = $net->{ip6};
762 if ($ipv6) {
763 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
764 $ipv6 = undef;
765 } else {
766 $ipv6 =~ s!/\d+$!!;
767 }
768 }
769
770 return ($ipv4, $ipv6);
771 }
772
773 sub delete_mountpoint_volume {
774 my ($storage_cfg, $vmid, $volume) = @_;
775
776 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
777
778 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
779
780 if ($vmid == $owner) {
781 PVE::Storage::vdisk_free($storage_cfg, $volume);
782 } else {
783 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
784 }
785 }
786
787 sub destroy_lxc_container {
788 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
789
790 PVE::LXC::Config->foreach_mountpoint($conf, sub {
791 my ($ms, $mountpoint) = @_;
792 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
793 });
794
795 rmdir "/var/lib/lxc/$vmid/rootfs";
796 unlink "/var/lib/lxc/$vmid/config";
797 rmdir "/var/lib/lxc/$vmid";
798 if (defined $replacement_conf) {
799 PVE::LXC::Config->write_config($vmid, $replacement_conf);
800 } else {
801 PVE::LXC::Config->destroy_config($vmid);
802 }
803 }
804
805 sub vm_stop_cleanup {
806 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
807
808 return if $keepActive;
809
810 eval {
811 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
812 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
813 };
814 warn $@ if $@; # avoid errors - just warn
815 }
816
817 my $safe_num_ne = sub {
818 my ($a, $b) = @_;
819
820 return 0 if !defined($a) && !defined($b);
821 return 1 if !defined($a);
822 return 1 if !defined($b);
823
824 return $a != $b;
825 };
826
827 my $safe_string_ne = sub {
828 my ($a, $b) = @_;
829
830 return 0 if !defined($a) && !defined($b);
831 return 1 if !defined($a);
832 return 1 if !defined($b);
833
834 return $a ne $b;
835 };
836
837 sub update_net {
838 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
839
840 if ($newnet->{type} ne 'veth') {
841 # for when there are physical interfaces
842 die "cannot update interface of type $newnet->{type}";
843 }
844
845 my $veth = "veth${vmid}i${netid}";
846 my $eth = $newnet->{name};
847
848 if (my $oldnetcfg = $conf->{$opt}) {
849 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
850
851 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
852 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
853
854 PVE::Network::veth_delete($veth);
855 delete $conf->{$opt};
856 PVE::LXC::Config->write_config($vmid, $conf);
857
858 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
859
860 } else {
861 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
862 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
863 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
864
865 if ($oldnet->{bridge}) {
866 PVE::Network::tap_unplug($veth);
867 foreach (qw(bridge tag firewall)) {
868 delete $oldnet->{$_};
869 }
870 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
871 PVE::LXC::Config->write_config($vmid, $conf);
872 }
873
874 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
875 # This includes the rate:
876 foreach (qw(bridge tag firewall rate)) {
877 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
878 }
879 } elsif (&$safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
880 # Rate can be applied on its own but any change above needs to
881 # include the rate in tap_plug since OVS resets everything.
882 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
883 $oldnet->{rate} = $newnet->{rate}
884 }
885 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
886 PVE::LXC::Config->write_config($vmid, $conf);
887 }
888 } else {
889 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
890 }
891
892 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
893 }
894
895 sub hotplug_net {
896 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
897
898 my $veth = "veth${vmid}i${netid}";
899 my $vethpeer = $veth . "p";
900 my $eth = $newnet->{name};
901
902 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
903 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
904
905 # attach peer in container
906 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
907 PVE::Tools::run_command($cmd);
908
909 # link up peer in container
910 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
911 PVE::Tools::run_command($cmd);
912
913 my $done = { type => 'veth' };
914 foreach (qw(bridge tag firewall hwaddr name)) {
915 $done->{$_} = $newnet->{$_} if $newnet->{$_};
916 }
917 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
918
919 PVE::LXC::Config->write_config($vmid, $conf);
920 }
921
922 sub update_ipconfig {
923 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
924
925 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
926
927 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
928 my $deleted = [];
929 my $added = [];
930 my $nscmd = sub {
931 my $cmdargs = shift;
932 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
933 };
934 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
935
936 my $change_ip_config = sub {
937 my ($ipversion) = @_;
938
939 my $family_opt = "-$ipversion";
940 my $suffix = $ipversion == 4 ? '' : $ipversion;
941 my $gw= "gw$suffix";
942 my $ip= "ip$suffix";
943
944 my $newip = $newnet->{$ip};
945 my $newgw = $newnet->{$gw};
946 my $oldip = $optdata->{$ip};
947 my $oldgw = $optdata->{$gw};
948
949 my $change_ip = &$safe_string_ne($oldip, $newip);
950 my $change_gw = &$safe_string_ne($oldgw, $newgw);
951
952 return if !$change_ip && !$change_gw;
953
954 # step 1: add new IP, if this fails we cancel
955 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
956 if ($change_ip && $is_real_ip) {
957 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
958 if (my $err = $@) {
959 warn $err;
960 return;
961 }
962 }
963
964 # step 2: replace gateway
965 # If this fails we delete the added IP and cancel.
966 # If it succeeds we save the config and delete the old IP, ignoring
967 # errors. The config is then saved.
968 # Note: 'ip route replace' can add
969 if ($change_gw) {
970 if ($newgw) {
971 eval {
972 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
973 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
974 }
975 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
976 };
977 if (my $err = $@) {
978 warn $err;
979 # the route was not replaced, the old IP is still available
980 # rollback (delete new IP) and cancel
981 if ($change_ip) {
982 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
983 warn $@ if $@; # no need to die here
984 }
985 return;
986 }
987 } else {
988 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
989 # if the route was not deleted, the guest might have deleted it manually
990 # warn and continue
991 warn $@ if $@;
992 }
993 if ($oldgw && $oldip && !PVE::Network::is_ip_in_cidr($oldgw, $oldip)) {
994 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
995 # warn if the route was deleted manually
996 warn $@ if $@;
997 }
998 }
999
1000 # from this point on we save the configuration
1001 # step 3: delete old IP ignoring errors
1002 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
1003 # We need to enable promote_secondaries, otherwise our newly added
1004 # address will be removed along with the old one.
1005 my $promote = 0;
1006 eval {
1007 if ($ipversion == 4) {
1008 &$nscmd({ outfunc => sub { $promote = int(shift) } },
1009 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1010 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1011 }
1012 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1013 };
1014 warn $@ if $@; # no need to die here
1015
1016 if ($ipversion == 4) {
1017 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1018 }
1019 }
1020
1021 foreach my $property ($ip, $gw) {
1022 if ($newnet->{$property}) {
1023 $optdata->{$property} = $newnet->{$property};
1024 } else {
1025 delete $optdata->{$property};
1026 }
1027 }
1028 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
1029 PVE::LXC::Config->write_config($vmid, $conf);
1030 $lxc_setup->setup_network($conf);
1031 };
1032
1033 &$change_ip_config(4);
1034 &$change_ip_config(6);
1035
1036 }
1037
1038 my $open_namespace = sub {
1039 my ($vmid, $pid, $kind) = @_;
1040 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1041 or die "failed to open $kind namespace of container $vmid: $!\n";
1042 return $fd;
1043 };
1044
1045 my $enter_namespace = sub {
1046 my ($vmid, $pid, $kind, $type) = @_;
1047 my $fd = $open_namespace->($vmid, $pid, $kind);
1048 PVE::Tools::setns(fileno($fd), $type)
1049 or die "failed to enter $kind namespace of container $vmid: $!\n";
1050 close $fd;
1051 };
1052
1053 my $get_container_namespace = sub {
1054 my ($vmid, $pid, $kind) = @_;
1055
1056 my $pidfd;
1057 if (!defined($pid)) {
1058 # Pin the pid while we're grabbing its stuff from /proc
1059 ($pid, $pidfd) = open_lxc_pid($vmid)
1060 or die "failed to open pidfd of container $vmid\'s init process\n";
1061 }
1062
1063 return $open_namespace->($vmid, $pid, $kind);
1064 };
1065
1066 my $do_syncfs = sub {
1067 my ($vmid, $pid, $socket) = @_;
1068
1069 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
1070
1071 # Tell the parent process to start reading our /proc/mounts
1072 print {$socket} "go\n";
1073 $socket->flush();
1074
1075 # Receive /proc/self/mounts
1076 my $mountdata = do { local $/ = undef; <$socket> };
1077 close $socket;
1078
1079 # Now sync all mountpoints...
1080 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
1081 foreach my $mp (@$mounts) {
1082 my ($what, $dir, $fs) = @$mp;
1083 next if $fs eq 'fuse.lxcfs';
1084 eval { PVE::Tools::sync_mountpoint($dir); };
1085 warn $@ if $@;
1086 }
1087 };
1088
1089 sub sync_container_namespace {
1090 my ($vmid) = @_;
1091 my $pid = find_lxc_pid($vmid);
1092
1093 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1094 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
1095 or die "failed to create socketpair: $!\n";
1096
1097 my $child = fork();
1098 die "fork failed: $!\n" if !defined($child);
1099
1100 if (!$child) {
1101 eval {
1102 close $pfd;
1103 &$do_syncfs($vmid, $pid, $cfd);
1104 };
1105 if (my $err = $@) {
1106 warn $err;
1107 POSIX::_exit(1);
1108 }
1109 POSIX::_exit(0);
1110 }
1111 close $cfd;
1112 my $go = <$pfd>;
1113 die "failed to enter container namespace\n" if $go ne "go\n";
1114
1115 open my $mounts, '<', "/proc/$child/mounts"
1116 or die "failed to open container's /proc/mounts: $!\n";
1117 my $mountdata = do { local $/ = undef; <$mounts> };
1118 close $mounts;
1119 print {$pfd} $mountdata;
1120 close $pfd;
1121
1122 while (waitpid($child, 0) != $child) {}
1123 die "failed to sync container namespace\n" if $? != 0;
1124 }
1125
1126 sub template_create {
1127 my ($vmid, $conf) = @_;
1128
1129 my $storecfg = PVE::Storage::config();
1130
1131 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1132 my ($ms, $mountpoint) = @_;
1133
1134 my $volid = $mountpoint->{volume};
1135
1136 die "Template feature is not available for '$volid'\n"
1137 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
1138 });
1139
1140 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1141 my ($ms, $mountpoint) = @_;
1142
1143 my $volid = $mountpoint->{volume};
1144
1145 PVE::Storage::activate_volumes($storecfg, [$volid]);
1146
1147 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
1148 $mountpoint->{volume} = $template_volid;
1149 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1150 });
1151
1152 PVE::LXC::Config->write_config($vmid, $conf);
1153 }
1154
1155 sub check_ct_modify_config_perm {
1156 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
1157
1158 return 1 if $authuser eq 'root@pam';
1159
1160 my $check = sub {
1161 my ($opt, $delete) = @_;
1162 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1163 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1164 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1165 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1166 return if $delete;
1167 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
1168 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
1169 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
1170 if $data->{type} ne 'volume';
1171 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1172 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1173 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1174 $opt eq 'searchdomain' || $opt eq 'hostname') {
1175 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1176 } elsif ($opt eq 'features') {
1177 # For now this is restricted to root@pam
1178 raise_perm_exc("changing feature flags is only allowed for root\@pam");
1179 } elsif ($opt eq 'hookscript') {
1180 # For now this is restricted to root@pam
1181 raise_perm_exc("changing the hookscript is only allowed for root\@pam");
1182 } else {
1183 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1184 }
1185 };
1186
1187 foreach my $opt (keys %$newconf) {
1188 &$check($opt, 0);
1189 }
1190 foreach my $opt (@$delete) {
1191 &$check($opt, 1);
1192 }
1193
1194 return 1;
1195 }
1196
1197 sub umount_all {
1198 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1199
1200 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1201 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1202
1203 my $res = 1;
1204
1205 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
1206 my ($ms, $mountpoint) = @_;
1207
1208 my $volid = $mountpoint->{volume};
1209 my $mount = $mountpoint->{mp};
1210
1211 return if !$volid || !$mount;
1212
1213 my $mount_path = "$rootdir/$mount";
1214 $mount_path =~ s!/+!/!g;
1215
1216 return if !PVE::ProcFSTools::is_mounted($mount_path);
1217
1218 eval {
1219 PVE::Tools::run_command(['umount', '-d', $mount_path]);
1220 };
1221 if (my $err = $@) {
1222 if ($noerr) {
1223 $res = 0;
1224 warn $err;
1225 } else {
1226 die $err;
1227 }
1228 }
1229 });
1230
1231 return $res; # tell caller if (some) umounts failed for the noerr case
1232 }
1233
1234 sub mount_all {
1235 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1236
1237 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1238 File::Path::make_path($rootdir);
1239
1240 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1241 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
1242
1243 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1244
1245 eval {
1246 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1247 my ($ms, $mountpoint) = @_;
1248
1249 $mountpoint->{ro} = 0 if $ignore_ro;
1250
1251 mountpoint_mount($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1252 });
1253 };
1254 if (my $err = $@) {
1255 warn "mounting container failed\n";
1256 umount_all($vmid, $storage_cfg, $conf, 1);
1257 die $err;
1258 }
1259
1260 return $rootdir;
1261 }
1262
1263
1264 sub mountpoint_mount_path {
1265 my ($mountpoint, $storage_cfg, $snapname) = @_;
1266
1267 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
1268 }
1269
1270 sub query_loopdev {
1271 my ($path) = @_;
1272 my $found;
1273 my $parser = sub {
1274 my $line = shift;
1275 if ($line =~ m@^(/dev/loop\d+):@) {
1276 $found = $1;
1277 }
1278 };
1279 my $cmd = ['losetup', '--associated', $path];
1280 PVE::Tools::run_command($cmd, outfunc => $parser);
1281 return $found;
1282 }
1283
1284 # Run a function with a file attached to a loop device.
1285 # The loop device is always detached afterwards (or set to autoclear).
1286 # Returns the loop device.
1287 sub run_with_loopdev {
1288 my ($func, $file, $readonly) = @_;
1289 my $device = query_loopdev($file);
1290 # Try to reuse an existing device
1291 if ($device) {
1292 # We assume that whoever setup the loop device is responsible for
1293 # detaching it.
1294 &$func($device);
1295 return $device;
1296 }
1297
1298 my $parser = sub {
1299 my $line = shift;
1300 if ($line =~ m@^(/dev/loop\d+)$@) {
1301 $device = $1;
1302 }
1303 };
1304 my $losetup_cmd = [
1305 'losetup',
1306 '--show',
1307 '-f',
1308 $file,
1309 ];
1310 push @$losetup_cmd, '-r' if $readonly;
1311 PVE::Tools::run_command($losetup_cmd, outfunc => $parser);
1312 die "failed to setup loop device for $file\n" if !$device;
1313 eval { &$func($device); };
1314 my $err = $@;
1315 PVE::Tools::run_command(['losetup', '-d', $device]);
1316 die $err if $err;
1317 return $device;
1318 }
1319
1320 # In scalar mode: returns a file handle to the deepest directory node.
1321 # In list context: returns a list of:
1322 # * the deepest directory node
1323 # * the 2nd deepest directory (parent of the above)
1324 # * directory name of the last directory
1325 # So that the path $2/$3 should lead to $1 afterwards.
1326 sub walk_tree_nofollow($$$;$$) {
1327 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1328
1329 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1330 or die "failed to open start directory $start: $!\n";
1331
1332 return walk_tree_nofollow_fd($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1333 }
1334
1335
1336 sub walk_tree_nofollow_fd($$$$;$$) {
1337 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1338
1339 # splitdir() returns '' for empty components including the leading /
1340 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1341
1342 my $fd = $start_fd;
1343 my $dir = $start_dirname;
1344 my $last_component = undef;
1345 my $second = $fd;
1346 foreach my $component (@comps) {
1347 $dir .= "/$component";
1348 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1349
1350 if (!$next) {
1351 # failed, check for symlinks and try to create the path
1352 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
1353 die "cannot open directory $dir: $!\n" if !$mkdir;
1354
1355 # We don't check for errors on mkdirat() here and just try to
1356 # openat() again, since at least one error (EEXIST) is an
1357 # expected possibility if multiple containers start
1358 # simultaneously. If someone else injects a symlink now then
1359 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1360 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1361
1362 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1363 die "failed to create path: $dir: $!\n" if !$next;
1364
1365 PVE::Tools::fchownat(fileno($next), '', $rootuid, $rootgid, PVE::Tools::AT_EMPTY_PATH)
1366 if defined($rootuid) && defined($rootgid);
1367 }
1368
1369 close $second if defined($last_component) && $second != $start_fd;
1370 $last_component = $component;
1371 $second = $fd;
1372 $fd = $next;
1373 }
1374
1375 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1376 close $second if defined($last_component) && $second != $start_fd;
1377 return $fd;
1378 }
1379
1380 # To guard against symlink attack races against other currently running
1381 # containers with shared recursive bind mount hierarchies we prepare a
1382 # directory handle for the directory we're mounting over to verify the
1383 # mountpoint afterwards.
1384 sub __bindmount_prepare {
1385 my ($hostroot, $dir) = @_;
1386 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1387 return $srcdh;
1388 }
1389
1390 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1391 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1392 # we intended to bind mount.
1393 sub __bindmount_verify {
1394 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1395 my $destdh;
1396 if ($parentfd) {
1397 # Open the mount point path coming from the parent directory since the
1398 # filehandle we would have gotten as first result of walk_tree_nofollow
1399 # earlier is still a handle to the underlying directory instead of the
1400 # mounted path.
1401 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1402 die "failed to open mount point: $!\n" if !$destdh;
1403 if ($ro) {
1404 my $dot = '.';
1405 # no separate function because 99% of the time it's the wrong thing to use.
1406 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
1407 die "failed to mark bind mount read only\n";
1408 }
1409 die "read-only check failed: $!\n" if $! != EROFS;
1410 }
1411 } else {
1412 # For the rootfs we don't have a parentfd so we open the path directly.
1413 # Note that this means bindmounting any prefix of the host's
1414 # /var/lib/lxc/$vmid path into another container is considered a grave
1415 # security error.
1416 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
1417 die "failed to open mount point: $!\n" if !$destdh;
1418 }
1419
1420 my ($srcdev, $srcinode) = stat($srcdh);
1421 my ($dstdev, $dstinode) = stat($destdh);
1422 close $srcdh;
1423 close $destdh;
1424
1425 return ($srcdev == $dstdev && $srcinode == $dstinode);
1426 }
1427
1428 # Perform the actual bind mounting:
1429 sub __bindmount_do {
1430 my ($dir, $dest, $ro, @extra_opts) = @_;
1431 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1432 if ($ro) {
1433 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1434 if (my $err = $@) {
1435 warn "bindmount error\n";
1436 # don't leave writable bind-mounts behind...
1437 PVE::Tools::run_command(['umount', $dest]);
1438 die $err;
1439 }
1440 }
1441 }
1442
1443 sub bindmount {
1444 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1445
1446 my $srcdh = __bindmount_prepare('/', $dir);
1447
1448 __bindmount_do($dir, $dest, $ro, @extra_opts);
1449
1450 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
1451 PVE::Tools::run_command(['umount', $dest]);
1452 die "detected mount path change at: $dir\n";
1453 }
1454 }
1455
1456 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1457 # from $rootdir and $mount and walk the path from $rootdir to the final
1458 # directory to check for symlinks.
1459 sub __mount_prepare_rootdir {
1460 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1461 $rootdir =~ s!/+!/!g;
1462 $rootdir =~ s!/+$!!;
1463 my $mount_path = "$rootdir/$mount";
1464 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1, $rootuid, $rootgid);
1465 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1466 }
1467
1468 # use $rootdir = undef to just return the corresponding mount path
1469 sub mountpoint_mount {
1470 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1471 return __mountpoint_mount($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1472 }
1473
1474 sub mountpoint_stage {
1475 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1476 my ($path, $loop, $dev) =
1477 __mountpoint_mount($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1478
1479 if (!defined($path)) {
1480 return undef if $! == ENOSYS;
1481 die "failed to mount subvolume: $!\n";
1482 }
1483
1484 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1485 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1486 # point).
1487 my $err;
1488 my $fd = PVE::Tools::open_tree(&AT_FDCWD, $stage_dir, &OPEN_TREE_CLOEXEC | &OPEN_TREE_CLONE)
1489 or die "open_tree() on mount point failed: $!\n";
1490
1491 return wantarray ? ($path, $loop, $dev, $fd) : $fd;
1492 }
1493
1494 sub mountpoint_insert_staged {
1495 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1496
1497 if (!defined($rootdir_fd)) {
1498 sysopen($rootdir_fd, '.', O_PATH | O_DIRECTORY)
1499 or die "failed to open '.': $!\n";
1500 }
1501
1502 my $dest_fd = walk_tree_nofollow_fd('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1503
1504 PVE::Tools::move_mount(
1505 fileno($mount_fd),
1506 '',
1507 fileno($dest_fd),
1508 '',
1509 &MOVE_MOUNT_F_EMPTY_PATH | &MOVE_MOUNT_T_EMPTY_PATH,
1510 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1511 }
1512
1513 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1514 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1515 # Note that if the kernel does not support the new mount API, this will not perform any action
1516 # and return `undef` with $! = ENOSYS.
1517 sub __mountpoint_mount {
1518 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1519
1520 if (defined($stage_mount) && !PVE::LXC::Tools::can_use_new_mount_api()) {
1521 $! = ENOSYS;
1522 return undef;
1523 }
1524
1525 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1526 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1527 # which we use in __bindmount_verify()!
1528 my $mount = $stage_mount ? '/': $mountpoint->{mp};
1529
1530 my $volid = $mountpoint->{volume};
1531 my $type = $mountpoint->{type};
1532 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1533 my $mounted_dev;
1534
1535 return if !$volid || !$mount;
1536
1537 $mount =~ s!/+!/!g;
1538
1539 my $mount_path;
1540 my ($mpfd, $parentfd, $last_dir);
1541
1542 if (defined($rootdir)) {
1543 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1544 __mount_prepare_rootdir($rootdir, $mount, $rootuid, $rootgid);
1545 }
1546
1547 if (defined($stage_mount)) {
1548 $mount_path = $rootdir;
1549 }
1550
1551 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1552
1553 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1554
1555 my $optlist = [];
1556
1557 if (my $mountopts = $mountpoint->{mountoptions}) {
1558 my @opts = split(/;/, $mountpoint->{mountoptions});
1559 push @$optlist, grep { PVE::LXC::Config::is_valid_mount_option($_) } @opts;
1560 }
1561
1562 my $acl = $mountpoint->{acl};
1563 if (defined($acl)) {
1564 push @$optlist, ($acl ? 'acl' : 'noacl');
1565 }
1566
1567 my $optstring = join(',', @$optlist);
1568 my $readonly = $mountpoint->{ro};
1569
1570 my @extra_opts;
1571 @extra_opts = ('-o', $optstring) if $optstring;
1572
1573 if ($storage) {
1574
1575 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1576
1577 my $path = PVE::Storage::map_volume($storage_cfg, $volid, $snapname);
1578
1579 $path = PVE::Storage::path($storage_cfg, $volid, $snapname) if !defined($path);
1580
1581 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1582 PVE::Storage::parse_volname($storage_cfg, $volid);
1583
1584 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1585
1586 if ($format eq 'subvol') {
1587 if ($mount_path) {
1588 if ($snapname) {
1589 if ($scfg->{type} eq 'zfspool') {
1590 my $path_arg = $path;
1591 $path_arg =~ s!^/+!!;
1592 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1593 } else {
1594 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1595 }
1596 } else {
1597 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1598 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1599 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1600 $name .= "\@$snapname" if defined($snapname);
1601 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1602 }
1603 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1604 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1605 }
1606 }
1607 return wantarray ? ($path, 0, undef) : $path;
1608 } elsif ($format eq 'raw' || $format eq 'iso') {
1609 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1610 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1611 # Our autodev hook expects the /dev/dm-* device currently
1612 # and will create the /dev/mapper symlink accordingly
1613 $path = Cwd::realpath($path);
1614 die "failed to get device path\n" if !$path;
1615 ($path) = ($path =~ /^(.*)$/s); #untaint
1616 my $domount = sub {
1617 my ($path) = @_;
1618 if ($mount_path) {
1619 if ($format eq 'iso') {
1620 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1621 } elsif ($isBase || defined($snapname)) {
1622 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1623 } else {
1624 if ($quota) {
1625 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1626 }
1627 push @extra_opts, '-o', 'ro' if $readonly;
1628 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1629 }
1630 }
1631 };
1632 my $use_loopdev = 0;
1633 if ($scfg->{path}) {
1634 $mounted_dev = run_with_loopdev($domount, $path, $readonly);
1635 $use_loopdev = 1;
1636 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1637 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
1638 $mounted_dev = $path;
1639 &$domount($path);
1640 } else {
1641 die "unsupported storage type '$scfg->{type}'\n";
1642 }
1643 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
1644 } else {
1645 die "unsupported image format '$format'\n";
1646 }
1647 } elsif ($type eq 'device') {
1648 push @extra_opts, '-o', 'ro' if $readonly;
1649 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1650 # See the NOTE above about devicemapper canonicalization
1651 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
1652 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1653 return wantarray ? ($volid, 0, $devpath) : $volid;
1654 } elsif ($type eq 'bind') {
1655 die "directory '$volid' does not exist\n" if ! -d $volid;
1656 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1657 warn "cannot enable quota control for bind mounts\n" if $quota;
1658 return wantarray ? ($volid, 0, undef) : $volid;
1659 }
1660
1661 die "unsupported storage";
1662 }
1663
1664 sub mountpoint_hotplug($$$) {
1665 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1666
1667 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1668
1669 # We do the rest in a fork with an unshared mount namespace, because:
1670 # -) change our papparmor profile to that of /usr/bin/lxc-start
1671 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1672 # container's namespace, then mount it.
1673
1674 PVE::Tools::run_fork(sub {
1675 # Pin the container pid longer, we also need to get its monitor/parent:
1676 my ($ct_pid, $ct_pidfd) = open_lxc_pid($vmid)
1677 or die "failed to open pidfd of container $vmid\'s init process\n";
1678
1679 my ($monitor_pid, $monitor_pidfd) = open_ppid($ct_pid)
1680 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1681
1682 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1683 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1684
1685 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1686 # profile to lower our privileges to the same level we have in the start hook:
1687 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY)
1688 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1689 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1690 # apparmor.
1691
1692 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1693 # namespace for it to remain active there since the container will be able to unmount
1694 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1695 # concern.
1696 PVE::Tools::setns(fileno($monitor_mnt_ns), PVE::Tools::CLONE_NEWNS);
1697 chdir('/')
1698 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1699
1700 my $dir = get_staging_mount_path($opt);
1701
1702 # Now switch our apparmor profile before mounting:
1703 my $data = 'changeprofile /usr/bin/lxc-start';
1704 if (syswrite($aa_fd, $data, length($data)) != length($data)) {
1705 die "failed to change apparmor profile: $!\n";
1706 }
1707 # Check errors on close as well:
1708 close($aa_fd)
1709 or die "failed to change apparmor profile (close() failed): $!\n";
1710
1711 my $mount_fd = mountpoint_stage($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1712
1713 PVE::Tools::setns(fileno($ct_mnt_ns), PVE::Tools::CLONE_NEWNS);
1714 chdir('/')
1715 or die "failed to change root directory within the container's mount namespace: $!\n";
1716
1717 mountpoint_insert_staged($mount_fd, undef, $mp->{mp}, $opt, $rootuid, $rootgid);
1718 });
1719 }
1720
1721 # Create a directory in the mountpoint staging tempfs.
1722 sub get_staging_mount_path($) {
1723 my ($opt) = @_;
1724
1725 my $target = get_staging_tempfs() . "/$opt";
1726 if (!mkdir($target) && $! != EEXIST) {
1727 die "failed to create directory $target: $!\n";
1728 }
1729
1730 return $target;
1731 }
1732
1733 # Mount /run/pve/mountpoints as tmpfs
1734 sub get_staging_tempfs() {
1735 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
1736 # mounts to that.
1737 my $target = '/var/lib/lxc/.pve-staged-mounts';
1738 if (!mkdir($target)) {
1739 return $target if $! == EEXIST;
1740 die "failed to create directory $target: $!\n";
1741 }
1742
1743 PVE::Tools::mount("none", $target, 'tmpfs', 0, "size=8k,mode=755")
1744 or die "failed to mount $target as tmpfs: $!\n";
1745
1746 return $target;
1747 }
1748
1749 sub mkfs {
1750 my ($dev, $rootuid, $rootgid) = @_;
1751
1752 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1753 '-E', "root_owner=$rootuid:$rootgid",
1754 $dev]);
1755 }
1756
1757 sub format_disk {
1758 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1759
1760 if ($volid =~ m!^/dev/.+!) {
1761 mkfs($volid);
1762 return;
1763 }
1764
1765 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1766
1767 die "cannot format volume '$volid' with no storage\n" if !$storage;
1768
1769 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1770
1771 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
1772
1773 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
1774
1775 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1776 PVE::Storage::parse_volname($storage_cfg, $volid);
1777
1778 die "cannot format volume '$volid' (format == $format)\n"
1779 if $format ne 'raw';
1780
1781 mkfs($path, $rootuid, $rootgid);
1782 }
1783
1784 sub destroy_disks {
1785 my ($storecfg, $vollist) = @_;
1786
1787 foreach my $volid (@$vollist) {
1788 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1789 warn $@ if $@;
1790 }
1791 }
1792
1793 sub alloc_disk {
1794 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1795
1796 my $needs_chown = 0;
1797 my $volid;
1798
1799 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1800 # fixme: use better naming ct-$vmid-disk-X.raw?
1801
1802 eval {
1803 my $do_format = 0;
1804 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs' || $scfg->{type} eq 'cifs' ) {
1805 if ($size_kb > 0) {
1806 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1807 undef, $size_kb);
1808 $do_format = 1;
1809 } else {
1810 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1811 undef, 0);
1812 $needs_chown = 1;
1813 }
1814 } elsif ($scfg->{type} eq 'zfspool') {
1815
1816 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1817 undef, $size_kb);
1818 $needs_chown = 1;
1819 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1820
1821 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1822 $do_format = 1;
1823
1824 } elsif ($scfg->{type} eq 'rbd') {
1825
1826 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1827 $do_format = 1;
1828 } else {
1829 die "unable to create containers on storage type '$scfg->{type}'\n";
1830 }
1831 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1832 };
1833 if (my $err = $@) {
1834 # in case formatting got interrupted:
1835 if (defined($volid)) {
1836 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1837 warn $@ if $@;
1838 }
1839 die $err;
1840 }
1841
1842 return ($volid, $needs_chown);
1843 }
1844
1845 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1846 sub create_disks {
1847 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
1848
1849 my $vollist = [];
1850
1851 eval {
1852 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1853 my $chown_vollist = [];
1854
1855 PVE::LXC::Config->foreach_mountpoint($settings, sub {
1856 my ($ms, $mountpoint) = @_;
1857
1858 my $volid = $mountpoint->{volume};
1859 my $mp = $mountpoint->{mp};
1860
1861 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1862
1863 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1864 my ($storeid, $size_gb) = ($1, $2);
1865
1866 my $size_kb = int(${size_gb}*1024) * 1024;
1867
1868 my $needs_chown = 0;
1869 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1870 push @$chown_vollist, $volid if $needs_chown;
1871 push @$vollist, $volid;
1872 $mountpoint->{volume} = $volid;
1873 $mountpoint->{size} = $size_kb * 1024;
1874 if ($pending) {
1875 $conf->{pending}->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1876 } else {
1877 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1878 }
1879 } else {
1880 # use specified/existing volid/dir/device
1881 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1882 }
1883 });
1884
1885 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1886 foreach my $volid (@$chown_vollist) {
1887 my $path = PVE::Storage::path($storecfg, $volid, undef);
1888 chown($rootuid, $rootgid, $path);
1889 }
1890 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
1891 };
1892 # free allocated images on error
1893 if (my $err = $@) {
1894 destroy_disks($storecfg, $vollist);
1895 die $err;
1896 }
1897 return $vollist;
1898 }
1899
1900 sub update_disksize {
1901 my ($vmid, $conf, $all_volumes) = @_;
1902
1903 my $changes;
1904 my $prefix = "CT $vmid:";
1905
1906 my $update_mp = sub {
1907 my ($key, $mp, @param) = @_;
1908 my $size = $all_volumes->{$mp->{volume}}->{size} // 0;
1909
1910 if (!defined($mp->{size}) || $size != $mp->{size}) {
1911 $changes = 1;
1912 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1913 $mp->{size} = $size;
1914 my $nomp = 1 if ($key eq 'rootfs');
1915 $conf->{$key} = PVE::LXC::Config->print_ct_mountpoint($mp, $nomp);
1916 }
1917 };
1918
1919 PVE::LXC::Config->foreach_mountpoint($conf, $update_mp);
1920
1921 return $changes;
1922 }
1923
1924 sub update_unused {
1925 my ($vmid, $conf, $all_volumes) = @_;
1926
1927 my $changes;
1928 my $prefix = "CT $vmid:";
1929
1930 # Note: it is allowed to define multiple storage entries with the same path
1931 # (alias), so we need to check both 'volid' and real 'path' (two different
1932 # volid can point to the same path).
1933
1934 # used and unused disks
1935 my $refpath = {};
1936 my $orphans = {};
1937
1938 foreach my $opt (keys %$conf) {
1939 next if ($opt !~ m/^unused\d+$/);
1940 my $vol = $all_volumes->{$conf->{$opt}};
1941 $refpath->{$vol->{path}} = $vol->{volid};
1942 }
1943
1944 foreach my $key (keys %$all_volumes) {
1945 my $vol = $all_volumes->{$key};
1946 my $in_use = PVE::LXC::Config->is_volume_in_use($conf, $vol->{volid});
1947 my $path = $vol->{path};
1948
1949 if ($in_use) {
1950 $refpath->{$path} = $key;
1951 delete $orphans->{$path};
1952 } else {
1953 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
1954 $orphans->{$path} = $key;
1955 }
1956 }
1957 }
1958
1959 for my $key (keys %$orphans) {
1960 my $disk = $orphans->{$key};
1961 my $unused = PVE::LXC::Config->add_unused_volume($conf, $disk);
1962
1963 if ($unused) {
1964 $changes = 1;
1965 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
1966 }
1967 }
1968
1969 return $changes;
1970 }
1971
1972 sub scan_volids {
1973 my ($cfg, $vmid) = @_;
1974
1975 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid);
1976
1977 my $all_volumes = {};
1978 foreach my $storeid (keys %$info) {
1979 foreach my $item (@{$info->{$storeid}}) {
1980 my $volid = $item->{volid};
1981 next if !($volid && $item->{size});
1982 $item->{path} = PVE::Storage::path($cfg, $volid);
1983 $all_volumes->{$volid} = $item;
1984 }
1985 }
1986
1987 return $all_volumes;
1988 }
1989
1990 sub rescan {
1991 my ($vmid, $nolock, $dryrun) = @_;
1992
1993 my $cfg = PVE::Storage::config();
1994
1995 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
1996 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
1997 foreach my $stor (keys %{$cfg->{ids}}) {
1998 delete($cfg->{ids}->{$stor}) if !$cfg->{ids}->{$stor}->{content}->{rootdir};
1999 }
2000
2001 print "rescan volumes...\n";
2002 my $all_volumes = scan_volids($cfg, $vmid);
2003
2004 my $updatefn = sub {
2005 my ($vmid) = @_;
2006
2007 my $changes;
2008 my $conf = PVE::LXC::Config->load_config($vmid);
2009
2010 PVE::LXC::Config->check_lock($conf);
2011
2012 my $vm_volids = {};
2013 foreach my $volid (keys %$all_volumes) {
2014 my $info = $all_volumes->{$volid};
2015 $vm_volids->{$volid} = $info if $info->{vmid} == $vmid;
2016 }
2017
2018 my $upu = update_unused($vmid, $conf, $vm_volids);
2019 my $upd = update_disksize($vmid, $conf, $vm_volids);
2020 $changes = $upu || $upd;
2021
2022 PVE::LXC::Config->write_config($vmid, $conf) if $changes && !$dryrun;
2023 };
2024
2025 if (defined($vmid)) {
2026 if ($nolock) {
2027 &$updatefn($vmid);
2028 } else {
2029 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2030 }
2031 } else {
2032 my $vmlist = config_list();
2033 foreach my $vmid (keys %$vmlist) {
2034 if ($nolock) {
2035 &$updatefn($vmid);
2036 } else {
2037 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2038 }
2039 }
2040 }
2041 }
2042
2043
2044 # bash completion helper
2045
2046 sub complete_os_templates {
2047 my ($cmdname, $pname, $cvalue) = @_;
2048
2049 my $cfg = PVE::Storage::config();
2050
2051 my $storeid;
2052
2053 if ($cvalue =~ m/^([^:]+):/) {
2054 $storeid = $1;
2055 }
2056
2057 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
2058 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
2059
2060 my $res = [];
2061 foreach my $id (keys %$data) {
2062 foreach my $item (@{$data->{$id}}) {
2063 push @$res, $item->{volid} if defined($item->{volid});
2064 }
2065 }
2066
2067 return $res;
2068 }
2069
2070 my $complete_ctid_full = sub {
2071 my ($running) = @_;
2072
2073 my $idlist = vmstatus();
2074
2075 my $active_hash = list_active_containers();
2076
2077 my $res = [];
2078
2079 foreach my $id (keys %$idlist) {
2080 my $d = $idlist->{$id};
2081 if (defined($running)) {
2082 next if $d->{template};
2083 next if $running && !$active_hash->{$id};
2084 next if !$running && $active_hash->{$id};
2085 }
2086 push @$res, $id;
2087
2088 }
2089 return $res;
2090 };
2091
2092 sub complete_ctid {
2093 return &$complete_ctid_full();
2094 }
2095
2096 sub complete_ctid_stopped {
2097 return &$complete_ctid_full(0);
2098 }
2099
2100 sub complete_ctid_running {
2101 return &$complete_ctid_full(1);
2102 }
2103
2104 sub parse_id_maps {
2105 my ($conf) = @_;
2106
2107 my $id_map = [];
2108 my $rootuid = 0;
2109 my $rootgid = 0;
2110
2111 my $lxc = $conf->{lxc};
2112 foreach my $entry (@$lxc) {
2113 my ($key, $value) = @$entry;
2114 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
2115 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
2116 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2117 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2118 push @$id_map, [$type, $ct, $host, $length];
2119 if ($ct == 0) {
2120 $rootuid = $host if $type eq 'u';
2121 $rootgid = $host if $type eq 'g';
2122 }
2123 } else {
2124 die "failed to parse idmap: $value\n";
2125 }
2126 }
2127
2128 if (!@$id_map && $conf->{unprivileged}) {
2129 # Should we read them from /etc/subuid?
2130 $id_map = [ ['u', '0', '100000', '65536'],
2131 ['g', '0', '100000', '65536'] ];
2132 $rootuid = $rootgid = 100000;
2133 }
2134
2135 return ($id_map, $rootuid, $rootgid);
2136 }
2137
2138 sub userns_command {
2139 my ($id_map) = @_;
2140 if (@$id_map) {
2141 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2142 }
2143 return [];
2144 }
2145
2146 sub vm_start {
2147 my ($vmid, $conf, $skiplock) = @_;
2148
2149 # apply pending changes while starting
2150 if (scalar(keys %{$conf->{pending}})) {
2151 my $storecfg = PVE::Storage::config();
2152 PVE::LXC::Config->vmconfig_apply_pending($vmid, $conf, $storecfg);
2153 $conf = PVE::LXC::Config->load_config($vmid); # update/reload
2154 }
2155
2156 update_lxc_config($vmid, $conf);
2157
2158 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2159
2160 if ($skiplock) {
2161 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2162 close($fh);
2163 }
2164
2165 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
2166
2167 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
2168 eval { PVE::Tools::run_command($cmd); };
2169 if (my $err = $@) {
2170 unlink $skiplock_flag_fn;
2171 die $err;
2172 }
2173 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
2174
2175 return;
2176 }
2177
2178 # Helper to stop a container completely and make sure it has stopped completely.
2179 # This is necessary because we want the post-stop hook to have completed its
2180 # unmount-all step, but post-stop happens after lxc puts the container into the
2181 # STOPPED state.
2182 # $kill - if true it will always do an immediate hard-stop
2183 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2184 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2185 sub vm_stop {
2186 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2187
2188 # Open the container's command socket.
2189 my $path = "\0/var/lib/lxc/$vmid/command";
2190 my $sock = IO::Socket::UNIX->new(
2191 Type => SOCK_STREAM(),
2192 Peer => $path,
2193 );
2194 if (!$sock) {
2195 return if $! == ECONNREFUSED; # The container is not running
2196 die "failed to open container ${vmid}'s command socket: $!\n";
2197 }
2198
2199 my $conf = PVE::LXC::Config->load_config($vmid);
2200 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
2201
2202 # Stop the container:
2203
2204 my $cmd = ['lxc-stop', '-n', $vmid];
2205
2206 if ($kill) {
2207 push @$cmd, '--kill'; # doesn't allow timeouts
2208 } else {
2209 # lxc-stop uses a default timeout
2210 push @$cmd, '--nokill' if !$kill_after_timeout;
2211
2212 if (defined($shutdown_timeout)) {
2213 push @$cmd, '--timeout', $shutdown_timeout;
2214 # Give run_command 5 extra seconds
2215 $shutdown_timeout += 5;
2216 }
2217 }
2218
2219 eval { PVE::Tools::run_command($cmd, timeout => $shutdown_timeout) };
2220 if (my $err = $@) {
2221 warn $@ if $@;
2222 }
2223
2224 my $result = <$sock>;
2225
2226 return if !defined $result; # monitor is gone and the ct has stopped.
2227 die "container did not stop\n";
2228 }
2229
2230 sub vm_reboot {
2231 my ($vmid, $timeout, $skiplock) = @_;
2232
2233 PVE::LXC::Config->lock_config($vmid, sub {
2234 return if !check_running($vmid);
2235
2236 vm_stop($vmid, 0, $timeout, 1); # kill if timeout exceeds
2237
2238 my $conf = PVE::LXC::Config->load_config($vmid);
2239 vm_start($vmid, $conf);
2240 });
2241 }
2242
2243 sub run_unshared {
2244 my ($code) = @_;
2245
2246 return PVE::Tools::run_fork(sub {
2247 # Unshare the mount namespace
2248 die "failed to unshare mount namespace: $!\n"
2249 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
2250 PVE::Tools::run_command(['mount', '--make-rslave', '/']);
2251 return $code->();
2252 });
2253 }
2254
2255 my $copy_volume = sub {
2256 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2257
2258 my $src_mp = { volume => $src_volid, mp => '/', ro => 1 };
2259 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
2260
2261 my $dst_mp = { volume => $dst_volid, mp => '/', ro => 0 };
2262 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
2263
2264 my @mounted;
2265 eval {
2266 # mount and copy
2267 mkdir $src;
2268 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2269 push @mounted, $src;
2270 mkdir $dest;
2271 mountpoint_mount($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2272 push @mounted, $dest;
2273
2274 $bwlimit //= 0;
2275
2276 PVE::Tools::run_command(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2277 '-aH', '--whole-file', '--sparse', '--one-file-system',
2278 "--bwlimit=$bwlimit", "$src/", $dest]);
2279 };
2280 my $err = $@;
2281
2282 # Wait for rsync's children to release dest so that
2283 # consequent file operations (umount, remove) are possible
2284 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2285
2286 foreach my $mount (reverse @mounted) {
2287 eval { PVE::Tools::run_command(['/bin/umount', $mount], errfunc => sub{})};
2288 warn "Can't umount $mount\n" if $@;
2289 }
2290
2291 # If this fails they're used as mount points in a concurrent operation
2292 # (which should not happen but there's also no real need to get rid of them).
2293 rmdir $dest;
2294 rmdir $src;
2295
2296 die $err if $err;
2297 };
2298
2299 # Should not be called after unsharing the mount namespace!
2300 sub copy_volume {
2301 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2302
2303 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
2304 File::Path::make_path("/var/lib/lxc/$vmid");
2305 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2306 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2307
2308 # get id's for unprivileged container
2309 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
2310
2311 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2312 # are visible in this namespace, otherwise the host only sees the empty
2313 # (not-mounted) directory.
2314 my $new_volid;
2315 eval {
2316 # Make sure $mp contains a correct size.
2317 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
2318 my $needs_chown;
2319 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
2320 if ($needs_chown) {
2321 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
2322 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
2323 chown($rootuid, $rootgid, $path);
2324 }
2325
2326 run_unshared(sub {
2327 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2328 });
2329 };
2330 if (my $err = $@) {
2331 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
2332 if defined($new_volid);
2333 die $err;
2334 }
2335
2336 return $new_volid;
2337 }
2338
2339 1;