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