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