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