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