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