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