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