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