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