]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC.pm
62b6b8ca62e233577cede2bbf52ec4adf03eb24b
[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 $optstring = '';
1419 my $acl = $mountpoint->{acl};
1420 if (defined($acl)) {
1421 $optstring .= ($acl ? 'acl' : 'noacl');
1422 }
1423 my $readonly = $mountpoint->{ro};
1424
1425 my @extra_opts;
1426 @extra_opts = ('-o', $optstring) if $optstring;
1427
1428 if ($storage) {
1429
1430 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1431
1432 my $path = PVE::Storage::map_volume($storage_cfg, $volid, $snapname);
1433
1434 $path = PVE::Storage::path($storage_cfg, $volid, $snapname) if !defined($path);
1435
1436 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1437 PVE::Storage::parse_volname($storage_cfg, $volid);
1438
1439 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1440
1441 if ($format eq 'subvol') {
1442 if ($mount_path) {
1443 if ($snapname) {
1444 if ($scfg->{type} eq 'zfspool') {
1445 my $path_arg = $path;
1446 $path_arg =~ s!^/+!!;
1447 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1448 } else {
1449 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1450 }
1451 } else {
1452 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1453 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1454 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1455 $name .= "\@$snapname" if defined($snapname);
1456 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1457 }
1458 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1459 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1460 }
1461 }
1462 return wantarray ? ($path, 0, undef) : $path;
1463 } elsif ($format eq 'raw' || $format eq 'iso') {
1464 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1465 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1466 # Our autodev hook expects the /dev/dm-* device currently
1467 # and will create the /dev/mapper symlink accordingly
1468 $path = Cwd::realpath($path);
1469 die "failed to get device path\n" if !$path;
1470 ($path) = ($path =~ /^(.*)$/s); #untaint
1471 my $domount = sub {
1472 my ($path) = @_;
1473 if ($mount_path) {
1474 if ($format eq 'iso') {
1475 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1476 } elsif ($isBase || defined($snapname)) {
1477 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1478 } else {
1479 if ($quota) {
1480 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1481 }
1482 push @extra_opts, '-o', 'ro' if $readonly;
1483 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1484 }
1485 }
1486 };
1487 my $use_loopdev = 0;
1488 if ($scfg->{path}) {
1489 $mounted_dev = run_with_loopdev($domount, $path, $readonly);
1490 $use_loopdev = 1;
1491 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1492 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
1493 $mounted_dev = $path;
1494 &$domount($path);
1495 } else {
1496 die "unsupported storage type '$scfg->{type}'\n";
1497 }
1498 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
1499 } else {
1500 die "unsupported image format '$format'\n";
1501 }
1502 } elsif ($type eq 'device') {
1503 push @extra_opts, '-o', 'ro' if $readonly;
1504 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1505 # See the NOTE above about devicemapper canonicalization
1506 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
1507 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1508 return wantarray ? ($volid, 0, $devpath) : $volid;
1509 } elsif ($type eq 'bind') {
1510 die "directory '$volid' does not exist\n" if ! -d $volid;
1511 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1512 warn "cannot enable quota control for bind mounts\n" if $quota;
1513 return wantarray ? ($volid, 0, undef) : $volid;
1514 }
1515
1516 die "unsupported storage";
1517 }
1518
1519 sub mkfs {
1520 my ($dev, $rootuid, $rootgid) = @_;
1521
1522 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1523 '-E', "root_owner=$rootuid:$rootgid",
1524 $dev]);
1525 }
1526
1527 sub format_disk {
1528 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1529
1530 if ($volid =~ m!^/dev/.+!) {
1531 mkfs($volid);
1532 return;
1533 }
1534
1535 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1536
1537 die "cannot format volume '$volid' with no storage\n" if !$storage;
1538
1539 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1540
1541 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
1542
1543 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
1544
1545 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1546 PVE::Storage::parse_volname($storage_cfg, $volid);
1547
1548 die "cannot format volume '$volid' (format == $format)\n"
1549 if $format ne 'raw';
1550
1551 mkfs($path, $rootuid, $rootgid);
1552 }
1553
1554 sub destroy_disks {
1555 my ($storecfg, $vollist) = @_;
1556
1557 foreach my $volid (@$vollist) {
1558 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1559 warn $@ if $@;
1560 }
1561 }
1562
1563 sub alloc_disk {
1564 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1565
1566 my $needs_chown = 0;
1567 my $volid;
1568
1569 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1570 # fixme: use better naming ct-$vmid-disk-X.raw?
1571
1572 eval {
1573 my $do_format = 0;
1574 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs' || $scfg->{type} eq 'cifs' ) {
1575 if ($size_kb > 0) {
1576 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1577 undef, $size_kb);
1578 $do_format = 1;
1579 } else {
1580 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1581 undef, 0);
1582 $needs_chown = 1;
1583 }
1584 } elsif ($scfg->{type} eq 'zfspool') {
1585
1586 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1587 undef, $size_kb);
1588 $needs_chown = 1;
1589 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1590
1591 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1592 $do_format = 1;
1593
1594 } elsif ($scfg->{type} eq 'rbd') {
1595
1596 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1597 $do_format = 1;
1598 } else {
1599 die "unable to create containers on storage type '$scfg->{type}'\n";
1600 }
1601 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1602 };
1603 if (my $err = $@) {
1604 # in case formatting got interrupted:
1605 if (defined($volid)) {
1606 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1607 warn $@ if $@;
1608 }
1609 die $err;
1610 }
1611
1612 return ($volid, $needs_chown);
1613 }
1614
1615 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1616 sub create_disks {
1617 my ($storecfg, $vmid, $settings, $conf) = @_;
1618
1619 my $vollist = [];
1620
1621 eval {
1622 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1623 my $chown_vollist = [];
1624
1625 PVE::LXC::Config->foreach_mountpoint($settings, sub {
1626 my ($ms, $mountpoint) = @_;
1627
1628 my $volid = $mountpoint->{volume};
1629 my $mp = $mountpoint->{mp};
1630
1631 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1632
1633 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1634 my ($storeid, $size_gb) = ($1, $2);
1635
1636 my $size_kb = int(${size_gb}*1024) * 1024;
1637
1638 my $needs_chown = 0;
1639 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1640 push @$chown_vollist, $volid if $needs_chown;
1641 push @$vollist, $volid;
1642 $mountpoint->{volume} = $volid;
1643 $mountpoint->{size} = $size_kb * 1024;
1644 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1645 } else {
1646 # use specified/existing volid/dir/device
1647 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1648 }
1649 });
1650
1651 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1652 foreach my $volid (@$chown_vollist) {
1653 my $path = PVE::Storage::path($storecfg, $volid, undef);
1654 chown($rootuid, $rootgid, $path);
1655 }
1656 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
1657 };
1658 # free allocated images on error
1659 if (my $err = $@) {
1660 destroy_disks($storecfg, $vollist);
1661 die $err;
1662 }
1663 return $vollist;
1664 }
1665
1666 sub update_disksize {
1667 my ($vmid, $conf, $all_volumes) = @_;
1668
1669 my $changes;
1670 my $prefix = "CT $vmid:";
1671
1672 my $update_mp = sub {
1673 my ($key, $mp, @param) = @_;
1674 my $size = $all_volumes->{$mp->{volume}}->{size} // 0;
1675
1676 if (!defined($mp->{size}) || $size != $mp->{size}) {
1677 $changes = 1;
1678 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1679 $mp->{size} = $size;
1680 my $nomp = 1 if ($key eq 'rootfs');
1681 $conf->{$key} = PVE::LXC::Config->print_ct_mountpoint($mp, $nomp);
1682 }
1683 };
1684
1685 PVE::LXC::Config->foreach_mountpoint($conf, $update_mp);
1686
1687 return $changes;
1688 }
1689
1690 sub update_unused {
1691 my ($vmid, $conf, $all_volumes) = @_;
1692
1693 my $changes;
1694 my $prefix = "CT $vmid:";
1695
1696 # Note: it is allowed to define multiple storage entries with the same path
1697 # (alias), so we need to check both 'volid' and real 'path' (two different
1698 # volid can point to the same path).
1699
1700 # used and unused disks
1701 my $refpath = {};
1702 my $orphans = {};
1703
1704 foreach my $opt (keys %$conf) {
1705 next if ($opt !~ m/^unused\d+$/);
1706 my $vol = $all_volumes->{$conf->{$opt}};
1707 $refpath->{$vol->{path}} = $vol->{volid};
1708 }
1709
1710 foreach my $key (keys %$all_volumes) {
1711 my $vol = $all_volumes->{$key};
1712 my $in_use = PVE::LXC::Config->is_volume_in_use($conf, $vol->{volid});
1713 my $path = $vol->{path};
1714
1715 if ($in_use) {
1716 $refpath->{$path} = $key;
1717 delete $orphans->{$path};
1718 } else {
1719 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
1720 $orphans->{$path} = $key;
1721 }
1722 }
1723 }
1724
1725 for my $key (keys %$orphans) {
1726 my $disk = $orphans->{$key};
1727 my $unused = PVE::LXC::Config->add_unused_volume($conf, $disk);
1728
1729 if ($unused) {
1730 $changes = 1;
1731 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
1732 }
1733 }
1734
1735 return $changes;
1736 }
1737
1738 sub scan_volids {
1739 my ($cfg, $vmid) = @_;
1740
1741 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid);
1742
1743 my $all_volumes = {};
1744 foreach my $storeid (keys %$info) {
1745 foreach my $item (@{$info->{$storeid}}) {
1746 my $volid = $item->{volid};
1747 next if !($volid && $item->{size});
1748 $item->{path} = PVE::Storage::path($cfg, $volid);
1749 $all_volumes->{$volid} = $item;
1750 }
1751 }
1752
1753 return $all_volumes;
1754 }
1755
1756 sub rescan {
1757 my ($vmid, $nolock, $dryrun) = @_;
1758
1759 my $cfg = PVE::Storage::config();
1760
1761 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
1762 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
1763 foreach my $stor (keys %{$cfg->{ids}}) {
1764 delete($cfg->{ids}->{$stor}) if !$cfg->{ids}->{$stor}->{content}->{rootdir};
1765 }
1766
1767 print "rescan volumes...\n";
1768 my $all_volumes = scan_volids($cfg, $vmid);
1769
1770 my $updatefn = sub {
1771 my ($vmid) = @_;
1772
1773 my $changes;
1774 my $conf = PVE::LXC::Config->load_config($vmid);
1775
1776 PVE::LXC::Config->check_lock($conf);
1777
1778 my $vm_volids = {};
1779 foreach my $volid (keys %$all_volumes) {
1780 my $info = $all_volumes->{$volid};
1781 $vm_volids->{$volid} = $info if $info->{vmid} == $vmid;
1782 }
1783
1784 my $upu = update_unused($vmid, $conf, $vm_volids);
1785 my $upd = update_disksize($vmid, $conf, $vm_volids);
1786 $changes = $upu || $upd;
1787
1788 PVE::LXC::Config->write_config($vmid, $conf) if $changes && !$dryrun;
1789 };
1790
1791 if (defined($vmid)) {
1792 if ($nolock) {
1793 &$updatefn($vmid);
1794 } else {
1795 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
1796 }
1797 } else {
1798 my $vmlist = config_list();
1799 foreach my $vmid (keys %$vmlist) {
1800 if ($nolock) {
1801 &$updatefn($vmid);
1802 } else {
1803 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
1804 }
1805 }
1806 }
1807 }
1808
1809
1810 # bash completion helper
1811
1812 sub complete_os_templates {
1813 my ($cmdname, $pname, $cvalue) = @_;
1814
1815 my $cfg = PVE::Storage::config();
1816
1817 my $storeid;
1818
1819 if ($cvalue =~ m/^([^:]+):/) {
1820 $storeid = $1;
1821 }
1822
1823 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1824 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1825
1826 my $res = [];
1827 foreach my $id (keys %$data) {
1828 foreach my $item (@{$data->{$id}}) {
1829 push @$res, $item->{volid} if defined($item->{volid});
1830 }
1831 }
1832
1833 return $res;
1834 }
1835
1836 my $complete_ctid_full = sub {
1837 my ($running) = @_;
1838
1839 my $idlist = vmstatus();
1840
1841 my $active_hash = list_active_containers();
1842
1843 my $res = [];
1844
1845 foreach my $id (keys %$idlist) {
1846 my $d = $idlist->{$id};
1847 if (defined($running)) {
1848 next if $d->{template};
1849 next if $running && !$active_hash->{$id};
1850 next if !$running && $active_hash->{$id};
1851 }
1852 push @$res, $id;
1853
1854 }
1855 return $res;
1856 };
1857
1858 sub complete_ctid {
1859 return &$complete_ctid_full();
1860 }
1861
1862 sub complete_ctid_stopped {
1863 return &$complete_ctid_full(0);
1864 }
1865
1866 sub complete_ctid_running {
1867 return &$complete_ctid_full(1);
1868 }
1869
1870 sub parse_id_maps {
1871 my ($conf) = @_;
1872
1873 my $id_map = [];
1874 my $rootuid = 0;
1875 my $rootgid = 0;
1876
1877 my $lxc = $conf->{lxc};
1878 foreach my $entry (@$lxc) {
1879 my ($key, $value) = @$entry;
1880 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1881 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
1882 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1883 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1884 push @$id_map, [$type, $ct, $host, $length];
1885 if ($ct == 0) {
1886 $rootuid = $host if $type eq 'u';
1887 $rootgid = $host if $type eq 'g';
1888 }
1889 } else {
1890 die "failed to parse idmap: $value\n";
1891 }
1892 }
1893
1894 if (!@$id_map && $conf->{unprivileged}) {
1895 # Should we read them from /etc/subuid?
1896 $id_map = [ ['u', '0', '100000', '65536'],
1897 ['g', '0', '100000', '65536'] ];
1898 $rootuid = $rootgid = 100000;
1899 }
1900
1901 return ($id_map, $rootuid, $rootgid);
1902 }
1903
1904 sub userns_command {
1905 my ($id_map) = @_;
1906 if (@$id_map) {
1907 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1908 }
1909 return [];
1910 }
1911
1912 sub vm_start {
1913 my ($vmid, $conf, $skiplock) = @_;
1914
1915 update_lxc_config($vmid, $conf);
1916
1917 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1918
1919 if ($skiplock) {
1920 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1921 close($fh);
1922 }
1923
1924 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1925
1926 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
1927 eval { PVE::Tools::run_command($cmd); };
1928 if (my $err = $@) {
1929 unlink $skiplock_flag_fn;
1930 die $err;
1931 }
1932 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
1933
1934 return;
1935 }
1936
1937 # Helper to stop a container completely and make sure it has stopped completely.
1938 # This is necessary because we want the post-stop hook to have completed its
1939 # unmount-all step, but post-stop happens after lxc puts the container into the
1940 # STOPPED state.
1941 # $kill - if true it will always do an immediate hard-stop
1942 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
1943 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
1944 sub vm_stop {
1945 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
1946
1947 # Open the container's command socket.
1948 my $path = "\0/var/lib/lxc/$vmid/command";
1949 my $sock = IO::Socket::UNIX->new(
1950 Type => SOCK_STREAM(),
1951 Peer => $path,
1952 );
1953 if (!$sock) {
1954 return if $! == ECONNREFUSED; # The container is not running
1955 die "failed to open container ${vmid}'s command socket: $!\n";
1956 }
1957
1958 my $conf = PVE::LXC::Config->load_config($vmid);
1959 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
1960
1961 # Stop the container:
1962
1963 my $cmd = ['lxc-stop', '-n', $vmid];
1964
1965 if ($kill) {
1966 push @$cmd, '--kill'; # doesn't allow timeouts
1967 } else {
1968 # lxc-stop uses a default timeout
1969 push @$cmd, '--nokill' if !$kill_after_timeout;
1970
1971 if (defined($shutdown_timeout)) {
1972 push @$cmd, '--timeout', $shutdown_timeout;
1973 # Give run_command 5 extra seconds
1974 $shutdown_timeout += 5;
1975 }
1976 }
1977
1978 eval { PVE::Tools::run_command($cmd, timeout => $shutdown_timeout) };
1979 if (my $err = $@) {
1980 warn $@ if $@;
1981 }
1982
1983 my $result = <$sock>;
1984
1985 return if !defined $result; # monitor is gone and the ct has stopped.
1986 die "container did not stop\n";
1987 }
1988
1989 sub run_unshared {
1990 my ($code) = @_;
1991
1992 return PVE::Tools::run_fork(sub {
1993 # Unshare the mount namespace
1994 die "failed to unshare mount namespace: $!\n"
1995 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
1996 PVE::Tools::run_command(['mount', '--make-rslave', '/']);
1997 return $code->();
1998 });
1999 }
2000
2001 my $copy_volume = sub {
2002 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit) = @_;
2003
2004 my $src_mp = { volume => $src_volid, mp => '/', ro => 1 };
2005 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
2006
2007 my $dst_mp = { volume => $dst_volid, mp => '/', ro => 0 };
2008 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
2009
2010 my @mounted;
2011 eval {
2012 # mount and copy
2013 mkdir $src;
2014 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname);
2015 push @mounted, $src;
2016 mkdir $dest;
2017 mountpoint_mount($dst_mp, $dest, $storage_cfg);
2018 push @mounted, $dest;
2019
2020 $bwlimit //= 0;
2021
2022 PVE::Tools::run_command(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2023 '-aH', '--whole-file', '--sparse', '--one-file-system',
2024 "--bwlimit=$bwlimit", "$src/", $dest]);
2025 };
2026 my $err = $@;
2027 foreach my $mount (reverse @mounted) {
2028 eval { PVE::Tools::run_command(['/bin/umount', '--lazy', $mount], errfunc => sub{})};
2029 warn "Can't umount $mount\n" if $@;
2030 }
2031
2032 # If this fails they're used as mount points in a concurrent operation
2033 # (which should not happen but there's also no real need to get rid of them).
2034 rmdir $dest;
2035 rmdir $src;
2036
2037 die $err if $err;
2038 };
2039
2040 # Should not be called after unsharing the mount namespace!
2041 sub copy_volume {
2042 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2043
2044 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
2045 File::Path::make_path("/var/lib/lxc/$vmid");
2046 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2047 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2048
2049 # get id's for unprivileged container
2050 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
2051
2052 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2053 # are visible in this namespace, otherwise the host only sees the empty
2054 # (not-mounted) directory.
2055 my $new_volid;
2056 eval {
2057 # Make sure $mp contains a correct size.
2058 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
2059 my $needs_chown;
2060 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
2061 if ($needs_chown) {
2062 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
2063 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
2064 chown($rootuid, $rootgid, $path);
2065 }
2066
2067 run_unshared(sub {
2068 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit);
2069 });
2070 };
2071 if (my $err = $@) {
2072 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
2073 if defined($new_volid);
2074 die $err;
2075 }
2076
2077 return $new_volid;
2078 }
2079
2080 1;