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