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