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