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