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