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