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