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