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