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