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