]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC.pm
Fix pct skiplock
[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);
b1bad293
WB
14use Errno qw(ELOOP ENOTDIR EROFS ECONNREFUSED);
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;
ab3722b3 21use PVE::Tools qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH);
92902047 22use PVE::CpuSet;
68fba17b 23use PVE::Network;
52389a07 24use PVE::AccessControl;
228a5a1d 25use PVE::ProcFSTools;
0389da0d 26use PVE::Syscall;
67afe46e 27use PVE::LXC::Config;
688afc63 28use Time::HiRes qw (gettimeofday);
f76a2828 29
27916659
DM
30my $nodename = PVE::INotify::nodename();
31
688afc63
WL
32my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
33
f76a2828
DM
34sub config_list {
35 my $vmlist = PVE::Cluster::get_vmlist();
36 my $res = {};
37 return $res if !$vmlist || !$vmlist->{ids};
38 my $ids = $vmlist->{ids};
39
40 foreach my $vmid (keys %$ids) {
41 next if !$vmid; # skip CT0
42 my $d = $ids->{$vmid};
43 next if !$d->{node} || $d->{node} ne $nodename;
44 next if !$d->{type} || $d->{type} ne 'lxc';
45 $res->{$vmid}->{type} = 'lxc';
46 }
47 return $res;
48}
49
5b4657d0
DM
50sub destroy_config {
51 my ($vmid) = @_;
52
67afe46e 53 unlink PVE::LXC::Config->config_file($vmid, $nodename);
3cc56749
FG
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
f76a2828
DM
118sub vmstatus {
119 my ($opt_vmid) = @_;
120
121 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc' }} : config_list();
122
822de0c3 123 my $active_hash = list_active_containers();
cbb03fea 124
688afc63
WL
125 my $cpucount = $cpuinfo->{cpus} || 1;
126
127 my $cdtime = gettimeofday;
128
129 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
130
3b5070d4
WB
131 my $unprivileged = {};
132
f76a2828 133 foreach my $vmid (keys %$list) {
f76a2828 134 my $d = $list->{$vmid};
10fc3ba5 135
d5588ee3
DM
136 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
137 warn $@ if $@; # ignore errors (consider them stopped)
cbb03fea 138
d5588ee3 139 $d->{status} = $d->{pid} ? 'running' : 'stopped';
f76a2828 140
67afe46e 141 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
238a56cb 142 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
cbb03fea 143
3b5070d4
WB
144 $unprivileged->{$vmid} = $conf->{unprivileged};
145
27916659 146 $d->{name} = $conf->{'hostname'} || "CT$vmid";
238a56cb 147 $d->{name} =~ s/[\s]//g;
cbb03fea 148
f2357408
DM
149 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
150 $d->{cpus} = $cpucount if !$d->{cpus};
44da0641 151
d0226204
WB
152 $d->{lock} = $conf->{lock} || '';
153
d5588ee3
DM
154 if ($d->{pid}) {
155 my $res = get_container_disk_usage($vmid, $d->{pid});
27916659
DM
156 $d->{disk} = $res->{used};
157 $d->{maxdisk} = $res->{total};
158 } else {
159 $d->{disk} = 0;
160 # use 4GB by default ??
161 if (my $rootfs = $conf->{rootfs}) {
1b4cf758 162 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($rootfs);
af02245c 163 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
27916659
DM
164 } else {
165 $d->{maxdisk} = 4*1024*1024*1024;
10fc3ba5 166 }
238a56cb 167 }
cbb03fea 168
238a56cb
DM
169 $d->{mem} = 0;
170 $d->{swap} = 0;
95df9a12
DM
171 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
172 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
e901d418 173
238a56cb
DM
174 $d->{uptime} = 0;
175 $d->{cpu} = 0;
e901d418 176
238a56cb
DM
177 $d->{netout} = 0;
178 $d->{netin} = 0;
f76a2828 179
238a56cb
DM
180 $d->{diskread} = 0;
181 $d->{diskwrite} = 0;
bb1ac2de 182
67afe46e 183 $d->{template} = PVE::LXC::Config->is_template($conf);
f76a2828 184 }
cbb03fea 185
238a56cb
DM
186 foreach my $vmid (keys %$list) {
187 my $d = $list->{$vmid};
d5588ee3
DM
188 my $pid = $d->{pid};
189
190 next if !$pid; # skip stopped CTs
f76a2828 191
88a8696b
TL
192 my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
193 $d->{uptime} = time - $ctime; # the method lxcfs uses
22a77285 194
3b5070d4
WB
195 my $unpriv = $unprivileged->{$vmid};
196
197 my $memory_stat = read_cgroup_list('memory', $vmid, $unpriv, 'memory.stat');
198 my $mem_usage_in_bytes = read_cgroup_value('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
b3059d35 199
cf8a6472 200 $d->{mem} = $mem_usage_in_bytes - $memory_stat->{total_cache};
3b5070d4 201 $d->{swap} = read_cgroup_value('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
b5289322 202
3b5070d4 203 my $blkio_bytes = read_cgroup_value('blkio', $vmid, $unpriv, 'blkio.throttle.io_service_bytes', 1);
1e647c7c 204 my @bytes = split(/\n/, $blkio_bytes);
b5289322 205 foreach my $byte (@bytes) {
1e647c7c 206 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
41ef9833
PA
207 $d->{diskread} += $2 if $key eq 'Read';
208 $d->{diskwrite} += $2 if $key eq 'Write';
1e647c7c 209 }
b5289322 210 }
688afc63 211
3b5070d4 212 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
688afc63
WL
213
214 my $used = $pstat->{utime} + $pstat->{stime};
215
216 my $old = $last_proc_vmid_stat->{$vmid};
217 if (!$old) {
218 $last_proc_vmid_stat->{$vmid} = {
219 time => $cdtime,
220 used => $used,
221 cpu => 0,
222 };
223 next;
224 }
225
226 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
227
228 if ($dtime > 1000) {
229 my $dutime = $used - $old->{used};
230
231 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
232 $last_proc_vmid_stat->{$vmid} = {
233 time => $cdtime,
234 used => $used,
235 cpu => $d->{cpu},
236 };
237 } else {
238 $d->{cpu} = $old->{cpu};
239 }
238a56cb 240 }
cbb03fea 241
68b8f4d1
WL
242 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
243
244 foreach my $dev (keys %$netdev) {
245 next if $dev !~ m/^veth([1-9]\d*)i/;
246 my $vmid = $1;
247 my $d = $list->{$vmid};
248
249 next if !$d;
250
251 $d->{netout} += $netdev->{$dev}->{receive};
252 $d->{netin} += $netdev->{$dev}->{transmit};
253
254 }
255
f76a2828
DM
256 return $list;
257}
258
3b5070d4
WB
259sub read_cgroup_list($$$$) {
260 my ($group, $vmid, $unprivileged, $name) = @_;
b3059d35 261
3b5070d4 262 my $content = read_cgroup_value($group, $vmid, $unprivileged, $name, 1);
b3059d35
TL
263
264 return { split(/\s+/, $content) };
265}
266
3b5070d4
WB
267sub read_cgroup_value($$$$$) {
268 my ($group, $vmid, $unprivileged, $name, $full) = @_;
238a56cb 269
3b5070d4
WB
270 my $nsdir = $unprivileged ? '' : 'ns/';
271 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
238a56cb
DM
272
273 return PVE::Tools::file_get_contents($path) if $full;
274
275 return PVE::Tools::file_read_firstline($path);
276}
277
bf0b8c43
AD
278sub write_cgroup_value {
279 my ($group, $vmid, $name, $value) = @_;
280
281 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
282 PVE::ProcFSTools::write_proc_entry($path, $value) if -e $path;
283
284}
285
52f1d76b
DM
286sub find_lxc_console_pids {
287
288 my $res = {};
289
290 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
291 my ($pid) = @_;
292
293 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
294 return if !$cmdline;
295
296 my @args = split(/\0/, $cmdline);
297
c31ad455 298 # search for lxc-console -n <vmid>
cbb03fea 299 return if scalar(@args) != 3;
52f1d76b
DM
300 return if $args[1] ne '-n';
301 return if $args[2] !~ m/^\d+$/;
302 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
cbb03fea 303
52f1d76b 304 my $vmid = $args[2];
cbb03fea 305
52f1d76b
DM
306 push @{$res->{$vmid}}, $pid;
307 });
308
309 return $res;
310}
311
bedeaaf1
AD
312sub find_lxc_pid {
313 my ($vmid) = @_;
314
315 my $pid = undef;
316 my $parser = sub {
317 my $line = shift;
8b25977f 318 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
bedeaaf1 319 };
c39aa40a 320 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
bedeaaf1 321
8b25977f 322 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
cbb03fea 323
8b25977f 324 return $pid;
bedeaaf1
AD
325}
326
cbb03fea 327# Note: we cannot use Net:IP, because that only allows strict
55fa4e09
DM
328# CIDR networks
329sub parse_ipv4_cidr {
330 my ($cidr, $noerr) = @_;
331
f7a7b413
WB
332 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
333 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
55fa4e09 334 }
cbb03fea 335
55fa4e09 336 return undef if $noerr;
cbb03fea 337
55fa4e09
DM
338 die "unable to parse ipv4 address/mask\n";
339}
93285df8 340
e22af68f 341
27916659 342sub update_lxc_config {
f91f3669 343 my ($vmid, $conf) = @_;
b80dd50a 344
bb1ac2de
DM
345 my $dir = "/var/lib/lxc/$vmid";
346
347 if ($conf->{template}) {
348
349 unlink "$dir/config";
350
351 return;
352 }
353
27916659 354 my $raw = '';
b80dd50a 355
27916659
DM
356 die "missing 'arch' - internal error" if !$conf->{arch};
357 $raw .= "lxc.arch = $conf->{arch}\n";
b80dd50a 358
425b62cb 359 my $unprivileged = $conf->{unprivileged};
108c6cab 360 my $custom_idmap = grep { $_->[0] eq 'lxc.idmap' } @{$conf->{lxc}};
425b62cb 361
27916659 362 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
866e0611
TL
363
364 my $inc ="/usr/share/lxc/config/$ostype.common.conf";
365 $inc ="/usr/share/lxc/config/common.conf" if !-f $inc;
366 $raw .= "lxc.include = $inc\n";
367 if ($unprivileged || $custom_idmap) {
368 $inc = "/usr/share/lxc/config/$ostype.userns.conf";
369 $inc = "/usr/share/lxc/config/userns.conf" if !-f $inc;
370 $raw .= "lxc.include = $inc\n"
27916659 371 }
b80dd50a 372
50df544c
WB
373 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
374 # cannot be exposed to the container with r/w access (cgroup perms).
375 # When this is enabled mounts will still remain in the monitor's namespace
376 # after the container unmounted them and thus will not detach from their
377 # files while the container is running!
c16b8890 378 $raw .= "lxc.monitor.unshare = 1\n";
58cc92a9 379
425b62cb
WB
380 # Should we read them from /etc/subuid?
381 if ($unprivileged && !$custom_idmap) {
108c6cab
WB
382 $raw .= "lxc.idmap = u 0 100000 65536\n";
383 $raw .= "lxc.idmap = g 0 100000 65536\n";
425b62cb
WB
384 }
385
d250604f 386 if (!PVE::LXC::Config->has_dev_console($conf)) {
108c6cab 387 $raw .= "lxc.console.path = none\n";
eeaea429
DM
388 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
389 }
4f958489 390
1b4cf758 391 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
108c6cab 392 $raw .= "lxc.tty.max = $ttycount\n";
cbb03fea 393
c31ad455 394 # some init scripts expect a linux terminal (turnkey).
a691a5a3
DM
395 $raw .= "lxc.environment = TERM=linux\n";
396
27916659 397 my $utsname = $conf->{hostname} || "CT$vmid";
108c6cab 398 $raw .= "lxc.uts.name = $utsname\n";
cbb03fea 399
27916659
DM
400 my $memory = $conf->{memory} || 512;
401 my $swap = $conf->{swap} // 0;
402
403 my $lxcmem = int($memory*1024*1024);
404 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
a12a36e0 405
27916659
DM
406 my $lxcswap = int(($memory + $swap)*1024*1024);
407 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
408
409 if (my $cpulimit = $conf->{cpulimit}) {
410 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
411 my $value = int(100000*$cpulimit);
412 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
a12a36e0
WL
413 }
414
27916659
DM
415 my $shares = $conf->{cpuunits} || 1024;
416 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
417
fddaa91b
DM
418 die "missing 'rootfs' configuration\n"
419 if !defined($conf->{rootfs});
420
1b4cf758 421 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
a3076d81 422
108c6cab 423 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
27916659 424
e756bdd6 425 foreach my $k (sort keys %$conf) {
27916659
DM
426 next if $k !~ m/^net(\d+)$/;
427 my $ind = $1;
1b4cf758 428 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
108c6cab
WB
429 $raw .= "lxc.net.$ind.type = veth\n";
430 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
431 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
432 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name});
433 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu});
a12a36e0
WL
434 }
435
92902047 436 my $had_cpuset = 0;
e576f689
DM
437 if (my $lxcconf = $conf->{lxc}) {
438 foreach my $entry (@$lxcconf) {
439 my ($k, $v) = @$entry;
92902047 440 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
e576f689
DM
441 $raw .= "$k = $v\n";
442 }
443 }
27916659 444
92902047
WB
445 my $cores = $conf->{cores};
446 if (!$had_cpuset && $cores) {
6560ce0f
WB
447 my $cpuset = eval { PVE::CpuSet->new_from_cgroup('lxc', 'effective_cpus') };
448 $cpuset = PVE::CpuSet->new_from_cgroup('', 'effective_cpus') if !$cpuset;
92902047
WB
449 my @members = $cpuset->members();
450 while (scalar(@members) > $cores) {
451 my $randidx = int(rand(scalar(@members)));
452 $cpuset->delete($members[$randidx]);
453 splice(@members, $randidx, 1); # keep track of the changes
454 }
455 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
456 }
e576f689 457
27916659
DM
458 File::Path::mkpath("$dir/rootfs");
459
460 PVE::Tools::file_set_contents("$dir/config", $raw);
b80dd50a
DM
461}
462
117636e5
DM
463# verify and cleanup nameserver list (replace \0 with ' ')
464sub verify_nameserver_list {
465 my ($nameserver_list) = @_;
466
467 my @list = ();
468 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
469 PVE::JSONSchema::pve_verify_ip($server);
470 push @list, $server;
471 }
472
473 return join(' ', @list);
474}
475
476sub verify_searchdomain_list {
477 my ($searchdomain_list) = @_;
478
479 my @list = ();
480 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
481 # todo: should we add checks for valid dns domains?
482 push @list, $server;
483 }
484
485 return join(' ', @list);
486}
487
aca816ad 488sub get_console_command {
4d494664 489 my ($vmid, $conf, $noescapechar) = @_;
aca816ad 490
1b4cf758 491 my $cmode = PVE::LXC::Config->get_cmode($conf);
aca816ad 492
4d494664 493 my $cmd = [];
aca816ad 494 if ($cmode eq 'console') {
4d494664
DC
495 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
496 push @$cmd, '-e', -1 if $noescapechar;
aca816ad 497 } elsif ($cmode eq 'tty') {
4d494664
DC
498 push @$cmd, 'lxc-console', '-n', $vmid;
499 push @$cmd, '-e', -1 if $noescapechar;
aca816ad 500 } elsif ($cmode eq 'shell') {
4d494664 501 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
aca816ad
DM
502 } else {
503 die "internal error";
504 }
4d494664
DC
505
506 return $cmd;
aca816ad
DM
507}
508
c325b32f
DM
509sub get_primary_ips {
510 my ($conf) = @_;
511
512 # return data from net0
cbb03fea 513
27916659 514 return undef if !defined($conf->{net0});
1b4cf758 515 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
c325b32f
DM
516
517 my $ipv4 = $net->{ip};
db78a181
WB
518 if ($ipv4) {
519 if ($ipv4 =~ /^(dhcp|manual)$/) {
520 $ipv4 = undef
521 } else {
522 $ipv4 =~ s!/\d+$!!;
523 }
524 }
65e5eaa3 525 my $ipv6 = $net->{ip6};
db78a181 526 if ($ipv6) {
5f291c7d 527 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
db78a181
WB
528 $ipv6 = undef;
529 } else {
530 $ipv6 =~ s!/\d+$!!;
531 }
532 }
cbb03fea 533
c325b32f
DM
534 return ($ipv4, $ipv6);
535}
148d1cb4 536
b407293b
WB
537sub delete_mountpoint_volume {
538 my ($storage_cfg, $vmid, $volume) = @_;
539
d250604f 540 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
b407293b
WB
541
542 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
543 PVE::Storage::vdisk_free($storage_cfg, $volume) if $vmid == $owner;
544}
ef241384 545
27916659 546sub destroy_lxc_container {
bccaa371 547 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
148d1cb4 548
d250604f 549 PVE::LXC::Config->foreach_mountpoint($conf, sub {
db8989e1 550 my ($ms, $mountpoint) = @_;
b407293b 551 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
db8989e1
WB
552 });
553
27916659
DM
554 rmdir "/var/lib/lxc/$vmid/rootfs";
555 unlink "/var/lib/lxc/$vmid/config";
556 rmdir "/var/lib/lxc/$vmid";
bccaa371
FG
557 if (defined $replacement_conf) {
558 PVE::LXC::Config->write_config($vmid, $replacement_conf);
559 } else {
560 destroy_config($vmid);
561 }
27916659
DM
562
563 #my $cmd = ['lxc-destroy', '-n', $vmid ];
564 #PVE::Tools::run_command($cmd);
148d1cb4 565}
68fba17b 566
ef241384 567sub vm_stop_cleanup {
5fa890f0 568 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
ef241384
DM
569
570 eval {
571 if (!$keepActive) {
bf9d912c 572
d250604f 573 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
a8b6b8a7 574 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
ef241384
DM
575 }
576 };
577 warn $@ if $@; # avoid errors - just warn
578}
579
93cdbbfb
AD
580my $safe_num_ne = sub {
581 my ($a, $b) = @_;
582
583 return 0 if !defined($a) && !defined($b);
584 return 1 if !defined($a);
585 return 1 if !defined($b);
586
587 return $a != $b;
588};
589
590my $safe_string_ne = sub {
591 my ($a, $b) = @_;
592
593 return 0 if !defined($a) && !defined($b);
594 return 1 if !defined($a);
595 return 1 if !defined($b);
596
597 return $a ne $b;
598};
599
600sub update_net {
bedeaaf1 601 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
93cdbbfb 602
18862537
WB
603 if ($newnet->{type} ne 'veth') {
604 # for when there are physical interfaces
605 die "cannot update interface of type $newnet->{type}";
606 }
607
608 my $veth = "veth${vmid}i${netid}";
93cdbbfb
AD
609 my $eth = $newnet->{name};
610
18862537 611 if (my $oldnetcfg = $conf->{$opt}) {
1b4cf758 612 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
18862537
WB
613
614 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
615 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
93cdbbfb 616
18862537 617 PVE::Network::veth_delete($veth);
bedeaaf1 618 delete $conf->{$opt};
67afe46e 619 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb 620
18862537 621 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
bedeaaf1 622
380962c7
WB
623 } else {
624 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
625 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
626 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
bedeaaf1 627
18862537 628 if ($oldnet->{bridge}) {
bedeaaf1 629 PVE::Network::tap_unplug($veth);
18862537
WB
630 foreach (qw(bridge tag firewall)) {
631 delete $oldnet->{$_};
632 }
1b4cf758 633 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
67afe46e 634 PVE::LXC::Config->write_config($vmid, $conf);
bedeaaf1 635 }
93cdbbfb 636
380962c7
WB
637 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
638 # This includes the rate:
639 foreach (qw(bridge tag firewall rate)) {
18862537
WB
640 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
641 }
380962c7
WB
642 } elsif (&$safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
643 # Rate can be applied on its own but any change above needs to
644 # include the rate in tap_plug since OVS resets everything.
645 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
646 $oldnet->{rate} = $newnet->{rate}
647 }
648 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
649 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
650 }
651 } else {
18862537 652 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
93cdbbfb
AD
653 }
654
bedeaaf1 655 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
93cdbbfb
AD
656}
657
658sub hotplug_net {
18862537 659 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
93cdbbfb 660
18862537 661 my $veth = "veth${vmid}i${netid}";
cbb03fea 662 my $vethpeer = $veth . "p";
93cdbbfb
AD
663 my $eth = $newnet->{name};
664
665 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
380962c7 666 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
93cdbbfb 667
cbb03fea 668 # attach peer in container
93cdbbfb
AD
669 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
670 PVE::Tools::run_command($cmd);
671
cbb03fea 672 # link up peer in container
93cdbbfb
AD
673 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
674 PVE::Tools::run_command($cmd);
bedeaaf1 675
18862537
WB
676 my $done = { type => 'veth' };
677 foreach (qw(bridge tag firewall hwaddr name)) {
678 $done->{$_} = $newnet->{$_} if $newnet->{$_};
679 }
1b4cf758 680 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
bedeaaf1 681
67afe46e 682 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
683}
684
68a05bb3 685sub update_ipconfig {
bedeaaf1
AD
686 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
687
f2104b80 688 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
bedeaaf1 689
1b4cf758 690 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
84e0c123
WB
691 my $deleted = [];
692 my $added = [];
8d723477
WB
693 my $nscmd = sub {
694 my $cmdargs = shift;
695 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
84e0c123 696 };
8d723477 697 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
2bfd1615 698
84e0c123 699 my $change_ip_config = sub {
f39002a6
DM
700 my ($ipversion) = @_;
701
702 my $family_opt = "-$ipversion";
703 my $suffix = $ipversion == 4 ? '' : $ipversion;
84e0c123
WB
704 my $gw= "gw$suffix";
705 my $ip= "ip$suffix";
bedeaaf1 706
6178b0dd
WB
707 my $newip = $newnet->{$ip};
708 my $newgw = $newnet->{$gw};
709 my $oldip = $optdata->{$ip};
710
711 my $change_ip = &$safe_string_ne($oldip, $newip);
712 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
bedeaaf1 713
84e0c123 714 return if !$change_ip && !$change_gw;
68a05bb3 715
84e0c123 716 # step 1: add new IP, if this fails we cancel
292aff54
WB
717 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
718 if ($change_ip && $is_real_ip) {
8d723477 719 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
84e0c123
WB
720 if (my $err = $@) {
721 warn $err;
722 return;
723 }
bedeaaf1 724 }
bedeaaf1 725
84e0c123
WB
726 # step 2: replace gateway
727 # If this fails we delete the added IP and cancel.
728 # If it succeeds we save the config and delete the old IP, ignoring
729 # errors. The config is then saved.
730 # Note: 'ip route replace' can add
731 if ($change_gw) {
6178b0dd 732 if ($newgw) {
292aff54
WB
733 eval {
734 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
735 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
736 }
737 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
738 };
84e0c123
WB
739 if (my $err = $@) {
740 warn $err;
741 # the route was not replaced, the old IP is still available
742 # rollback (delete new IP) and cancel
743 if ($change_ip) {
8d723477 744 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
84e0c123
WB
745 warn $@ if $@; # no need to die here
746 }
747 return;
748 }
749 } else {
8d723477 750 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
84e0c123
WB
751 # if the route was not deleted, the guest might have deleted it manually
752 # warn and continue
753 warn $@ if $@;
754 }
2bfd1615 755 }
2bfd1615 756
6178b0dd 757 # from this point on we save the configuration
84e0c123 758 # step 3: delete old IP ignoring errors
6178b0dd 759 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
8d723477
WB
760 # We need to enable promote_secondaries, otherwise our newly added
761 # address will be removed along with the old one.
762 my $promote = 0;
763 eval {
764 if ($ipversion == 4) {
765 &$nscmd({ outfunc => sub { $promote = int(shift) } },
766 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
767 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
768 }
769 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
770 };
84e0c123 771 warn $@ if $@; # no need to die here
8d723477
WB
772
773 if ($ipversion == 4) {
774 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
775 }
bedeaaf1
AD
776 }
777
84e0c123
WB
778 foreach my $property ($ip, $gw) {
779 if ($newnet->{$property}) {
780 $optdata->{$property} = $newnet->{$property};
781 } else {
782 delete $optdata->{$property};
783 }
bedeaaf1 784 }
1b4cf758 785 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
67afe46e 786 PVE::LXC::Config->write_config($vmid, $conf);
84e0c123
WB
787 $lxc_setup->setup_network($conf);
788 };
bedeaaf1 789
f39002a6
DM
790 &$change_ip_config(4);
791 &$change_ip_config(6);
489e960d
WL
792
793}
794
34fdb3d7
WB
795my $enter_namespace = sub {
796 my ($vmid, $pid, $which, $type) = @_;
797 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
798 or die "failed to open $which namespace of container $vmid: $!\n";
799 PVE::Tools::setns(fileno($fd), $type)
800 or die "failed to enter $which namespace of container $vmid: $!\n";
801 close $fd;
802};
803
804my $do_syncfs = sub {
805 my ($vmid, $pid, $socket) = @_;
806
807 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
808
809 # Tell the parent process to start reading our /proc/mounts
810 print {$socket} "go\n";
811 $socket->flush();
812
813 # Receive /proc/self/mounts
814 my $mountdata = do { local $/ = undef; <$socket> };
815 close $socket;
816
817 # Now sync all mountpoints...
818 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
819 foreach my $mp (@$mounts) {
820 my ($what, $dir, $fs) = @$mp;
821 next if $fs eq 'fuse.lxcfs';
822 eval { PVE::Tools::sync_mountpoint($dir); };
823 warn $@ if $@;
824 }
825};
826
827sub sync_container_namespace {
828 my ($vmid) = @_;
829 my $pid = find_lxc_pid($vmid);
830
831 # SOCK_DGRAM is nicer for barriers but cannot be slurped
832 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
833 or die "failed to create socketpair: $!\n";
834
835 my $child = fork();
836 die "fork failed: $!\n" if !defined($child);
837
838 if (!$child) {
839 eval {
840 close $pfd;
841 &$do_syncfs($vmid, $pid, $cfd);
842 };
843 if (my $err = $@) {
844 warn $err;
845 POSIX::_exit(1);
846 }
847 POSIX::_exit(0);
848 }
849 close $cfd;
850 my $go = <$pfd>;
851 die "failed to enter container namespace\n" if $go ne "go\n";
852
853 open my $mounts, '<', "/proc/$child/mounts"
854 or die "failed to open container's /proc/mounts: $!\n";
855 my $mountdata = do { local $/ = undef; <$mounts> };
856 close $mounts;
857 print {$pfd} $mountdata;
858 close $pfd;
859
860 while (waitpid($child, 0) != $child) {}
861 die "failed to sync container namespace\n" if $? != 0;
862}
863
bb1ac2de
DM
864sub template_create {
865 my ($vmid, $conf) = @_;
866
867 my $storecfg = PVE::Storage::config();
868
1b4cf758 869 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
bb1ac2de
DM
870 my $volid = $rootinfo->{volume};
871
872 die "Template feature is not available for '$volid'\n"
873 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
874
875 PVE::Storage::activate_volumes($storecfg, [$volid]);
876
877 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
878 $rootinfo->{volume} = $template_volid;
1b4cf758 879 $conf->{rootfs} = PVE::LXC::Config->print_ct_mountpoint($rootinfo, 1);
bb1ac2de 880
67afe46e 881 PVE::LXC::Config->write_config($vmid, $conf);
bb1ac2de
DM
882}
883
52389a07 884sub check_ct_modify_config_perm {
f1ba1a4b 885 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
52389a07 886
c81f19d1 887 return 1 if $authuser eq 'root@pam';
52389a07 888
f1ba1a4b
WB
889 my $check = sub {
890 my ($opt, $delete) = @_;
f2357408 891 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
52389a07 892 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
e59a61ed 893 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
52389a07 894 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
f1ba1a4b 895 return if $delete;
1b4cf758
FG
896 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
897 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
9d294016
FG
898 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
899 if $data->{type} ne 'volume';
52389a07
DM
900 } elsif ($opt eq 'memory' || $opt eq 'swap') {
901 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
902 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
903 $opt eq 'searchdomain' || $opt eq 'hostname') {
904 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
905 } else {
906 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
907 }
f1ba1a4b
WB
908 };
909
910 foreach my $opt (keys %$newconf) {
911 &$check($opt, 0);
912 }
913 foreach my $opt (@$delete) {
914 &$check($opt, 1);
52389a07
DM
915 }
916
917 return 1;
918}
919
9622e848 920sub umount_all {
da629848 921 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
9622e848
DM
922
923 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
d250604f 924 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848 925
d250604f 926 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
9622e848
DM
927 my ($ms, $mountpoint) = @_;
928
929 my $volid = $mountpoint->{volume};
930 my $mount = $mountpoint->{mp};
931
932 return if !$volid || !$mount;
933
d18f96b4 934 my $mount_path = "$rootdir/$mount";
f845a93d 935 $mount_path =~ s!/+!/!g;
9622e848 936
228a5a1d
WL
937 return if !PVE::ProcFSTools::is_mounted($mount_path);
938
9622e848 939 eval {
d18f96b4 940 PVE::Tools::run_command(['umount', '-d', $mount_path]);
9622e848
DM
941 };
942 if (my $err = $@) {
943 if ($noerr) {
944 warn $err;
945 } else {
946 die $err;
947 }
948 }
949 });
9622e848
DM
950}
951
952sub mount_all {
25321b68 953 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
9622e848
DM
954
955 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1adc7e53 956 File::Path::make_path($rootdir);
9622e848 957
d250604f 958 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848
DM
959 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
960
961 eval {
d250604f 962 PVE::LXC::Config->foreach_mountpoint($conf, sub {
9622e848
DM
963 my ($ms, $mountpoint) = @_;
964
25321b68
FG
965 $mountpoint->{ro} = 0 if $ignore_ro;
966
da629848 967 mountpoint_mount($mountpoint, $rootdir, $storage_cfg);
9622e848
DM
968 });
969 };
970 if (my $err = $@) {
e2007ac2 971 warn "mounting container failed\n";
9622e848 972 umount_all($vmid, $storage_cfg, $conf, 1);
e2007ac2 973 die $err;
9622e848
DM
974 }
975
da629848 976 return $rootdir;
9622e848
DM
977}
978
979
b15c75fc 980sub mountpoint_mount_path {
da629848 981 my ($mountpoint, $storage_cfg, $snapname) = @_;
b15c75fc 982
da629848 983 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
b15c75fc 984}
cc6b0307 985
21f292ff
WB
986sub query_loopdev {
987 my ($path) = @_;
988 my $found;
989 my $parser = sub {
990 my $line = shift;
991 if ($line =~ m@^(/dev/loop\d+):@) {
992 $found = $1;
993 }
994 };
995 my $cmd = ['losetup', '--associated', $path];
996 PVE::Tools::run_command($cmd, outfunc => $parser);
997 return $found;
998}
999
50df544c
WB
1000# Run a function with a file attached to a loop device.
1001# The loop device is always detached afterwards (or set to autoclear).
1002# Returns the loop device.
1003sub run_with_loopdev {
1004 my ($func, $file) = @_;
54d11e5c
WB
1005 my $device = query_loopdev($file);
1006 # Try to reuse an existing device
1007 if ($device) {
1008 # We assume that whoever setup the loop device is responsible for
1009 # detaching it.
1010 &$func($device);
1011 return $device;
1012 }
1013
50df544c
WB
1014 my $parser = sub {
1015 my $line = shift;
1016 if ($line =~ m@^(/dev/loop\d+)$@) {
1017 $device = $1;
1018 }
1019 };
1020 PVE::Tools::run_command(['losetup', '--show', '-f', $file], outfunc => $parser);
1021 die "failed to setup loop device for $file\n" if !$device;
1022 eval { &$func($device); };
1023 my $err = $@;
1024 PVE::Tools::run_command(['losetup', '-d', $device]);
1025 die $err if $err;
1026 return $device;
1027}
1028
ab3722b3
WB
1029# In scalar mode: returns a file handle to the deepest directory node.
1030# In list context: returns a list of:
1031# * the deepest directory node
1032# * the 2nd deepest directory (parent of the above)
1033# * directory name of the last directory
1034# So that the path $2/$3 should lead to $1 afterwards.
1035sub walk_tree_nofollow($$$) {
1036 my ($start, $subdir, $mkdir) = @_;
1037
1038 # splitdir() returns '' for empty components including the leading /
1039 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1040
1041 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1042 or die "failed to open start directory $start: $!\n";
1043
1044 my $dir = $start;
1045 my $last_component = undef;
1046 my $second = $fd;
1047 foreach my $component (@comps) {
1048 $dir .= "/$component";
1049 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1050
1051 if (!$next) {
1052 # failed, check for symlinks and try to create the path
3eb5f47b 1053 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
ab3722b3
WB
1054 die "cannot open directory $dir: $!\n" if !$mkdir;
1055
1056 # We don't check for errors on mkdirat() here and just try to
1057 # openat() again, since at least one error (EEXIST) is an
1058 # expected possibility if multiple containers start
1059 # simultaneously. If someone else injects a symlink now then
1060 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1061 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1062
1063 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1064 die "failed to create path: $dir: $!\n" if !$next;
1065 }
1066
1067 close $second if defined($last_component);
1068 $last_component = $component;
1069 $second = $fd;
1070 $fd = $next;
1071 }
1072
1073 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1074 close $second if defined($last_component);
1075 return $fd;
1076}
1077
619f27b4
WB
1078# To guard against symlink attack races against other currently running
1079# containers with shared recursive bind mount hierarchies we prepare a
1080# directory handle for the directory we're mounting over to verify the
1081# mountpoint afterwards.
1082sub __bindmount_prepare {
1083 my ($hostroot, $dir) = @_;
1084 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1085 return $srcdh;
1086}
ab3722b3 1087
619f27b4
WB
1088# Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1089# ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1090# we intended to bind mount.
1091sub __bindmount_verify {
1092 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
ab3722b3
WB
1093 my $destdh;
1094 if ($parentfd) {
1095 # Open the mount point path coming from the parent directory since the
1096 # filehandle we would have gotten as first result of walk_tree_nofollow
1097 # earlier is still a handle to the underlying directory instead of the
1098 # mounted path.
619f27b4
WB
1099 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1100 die "failed to open mount point: $!\n" if !$destdh;
1101 if ($ro) {
1102 my $dot = '.';
619f27b4 1103 # no separate function because 99% of the time it's the wrong thing to use.
0389da0d 1104 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
619f27b4
WB
1105 die "failed to mark bind mount read only\n";
1106 }
1107 die "read-only check failed: $!\n" if $! != EROFS;
1108 }
ab3722b3
WB
1109 } else {
1110 # For the rootfs we don't have a parentfd so we open the path directly.
1111 # Note that this means bindmounting any prefix of the host's
1112 # /var/lib/lxc/$vmid path into another container is considered a grave
1113 # security error.
1114 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
619f27b4 1115 die "failed to open mount point: $!\n" if !$destdh;
ab3722b3 1116 }
ab3722b3
WB
1117
1118 my ($srcdev, $srcinode) = stat($srcdh);
1119 my ($dstdev, $dstinode) = stat($destdh);
1120 close $srcdh;
1121 close $destdh;
1122
619f27b4
WB
1123 return ($srcdev == $dstdev && $srcinode == $dstinode);
1124}
1125
1126# Perform the actual bind mounting:
1127sub __bindmount_do {
1128 my ($dir, $dest, $ro, @extra_opts) = @_;
1129 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1130 if ($ro) {
1131 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1132 if (my $err = $@) {
1133 warn "bindmount error\n";
1134 # don't leave writable bind-mounts behind...
1135 PVE::Tools::run_command(['umount', $dest]);
1136 die $err;
1137 }
1138 }
1139}
1140
1141sub bindmount {
1142 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1143
1144 my $srcdh = __bindmount_prepare('/', $dir);
1145
1146 __bindmount_do($dir, $dest, $ro, @extra_opts);
1147
1148 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
ab3722b3
WB
1149 PVE::Tools::run_command(['umount', $dest]);
1150 die "detected mount path change at: $dir\n";
1151 }
c2744c97
WB
1152}
1153
619f27b4
WB
1154# Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1155# from $rootdir and $mount and walk the path from $rootdir to the final
1156# directory to check for symlinks.
1157sub __mount_prepare_rootdir {
1158 my ($rootdir, $mount) = @_;
1159 $rootdir =~ s!/+!/!g;
1160 $rootdir =~ s!/+$!!;
1161 my $mount_path = "$rootdir/$mount";
1162 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1);
1163 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1164}
1165
b15c75fc 1166# use $rootdir = undef to just return the corresponding mount path
cc6b0307 1167sub mountpoint_mount {
da629848 1168 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
cc6b0307
AD
1169
1170 my $volid = $mountpoint->{volume};
1171 my $mount = $mountpoint->{mp};
7c921c80 1172 my $type = $mountpoint->{type};
50df544c
WB
1173 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1174 my $mounted_dev;
b15c75fc 1175
cc6b0307
AD
1176 return if !$volid || !$mount;
1177
ab3722b3
WB
1178 $mount =~ s!/+!/!g;
1179
b15c75fc 1180 my $mount_path;
ab3722b3 1181 my ($mpfd, $parentfd, $last_dir);
b15c75fc
DM
1182
1183 if (defined($rootdir)) {
619f27b4
WB
1184 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1185 __mount_prepare_rootdir($rootdir, $mount);
116ce06f 1186 }
b15c75fc
DM
1187
1188 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
cc6b0307 1189
b15c75fc 1190 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
cc6b0307 1191
471dd315 1192 my $optstring = '';
719129ea
WB
1193 my $acl = $mountpoint->{acl};
1194 if (defined($acl)) {
1195 $optstring .= ($acl ? 'acl' : 'noacl');
471dd315 1196 }
c2744c97 1197 my $readonly = $mountpoint->{ro};
471dd315 1198
c019c56a 1199 my @extra_opts = ('-o', $optstring) if $optstring;
471dd315 1200
b15c75fc
DM
1201 if ($storage) {
1202
1203 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
7c138f58
WB
1204
1205 # early sanity checks:
1206 # we otherwise call realpath on the rbd url
1207 die "containers on rbd storage without krbd are not supported\n"
1208 if $scfg->{type} eq 'rbd' && !$scfg->{krbd};
1209
b15c75fc
DM
1210 my $path = PVE::Storage::path($storage_cfg, $volid, $snapname);
1211
1212 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1213 PVE::Storage::parse_volname($storage_cfg, $volid);
1214
c87b9dd8
DM
1215 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1216
b15c75fc 1217 if ($format eq 'subvol') {
30de33be
DM
1218 if ($mount_path) {
1219 if ($snapname) {
e84f7f5d
DM
1220 if ($scfg->{type} eq 'zfspool') {
1221 my $path_arg = $path;
1222 $path_arg =~ s!^/+!!;
471dd315 1223 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
e84f7f5d 1224 } else {
30de33be
DM
1225 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1226 }
e84f7f5d 1227 } else {
719129ea
WB
1228 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1229 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1230 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1231 $name .= "\@$snapname" if defined($snapname);
1232 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1233 }
ab3722b3 1234 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
50df544c 1235 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
30de33be 1236 }
b15c75fc 1237 }
5f6280cf 1238 return wantarray ? ($path, 0, undef) : $path;
c87b9dd8 1239 } elsif ($format eq 'raw' || $format eq 'iso') {
ada088e6
WB
1240 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1241 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1242 # Our autodev hook expects the /dev/dm-* device currently
1243 # and will create the /dev/mapper symlink accordingly
e439a713
WB
1244 $path = Cwd::realpath($path);
1245 die "failed to get device path\n" if !$path;
1246 ($path) = ($path =~ /^(.*)$/s); #untaint
50df544c
WB
1247 my $domount = sub {
1248 my ($path) = @_;
1249 if ($mount_path) {
1250 if ($format eq 'iso') {
1251 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1252 } elsif ($isBase || defined($snapname)) {
1253 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1254 } else {
1255 if ($quota) {
1256 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1257 }
c2744c97 1258 push @extra_opts, '-o', 'ro' if $readonly;
50df544c
WB
1259 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1260 }
1261 }
1262 };
30de33be 1263 my $use_loopdev = 0;
b15c75fc 1264 if ($scfg->{path}) {
50df544c 1265 $mounted_dev = run_with_loopdev($domount, $path);
30de33be 1266 $use_loopdev = 1;
2e879877
DM
1267 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1268 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
50df544c
WB
1269 $mounted_dev = $path;
1270 &$domount($path);
b15c75fc
DM
1271 } else {
1272 die "unsupported storage type '$scfg->{type}'\n";
1273 }
50df544c 1274 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
b15c75fc
DM
1275 } else {
1276 die "unsupported image format '$format'\n";
1277 }
7c921c80 1278 } elsif ($type eq 'device') {
c9bc95a1 1279 push @extra_opts, '-o', 'ro' if $readonly;
0d449e38
WB
1280 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1281 # See the NOTE above about devicemapper canonicalization
1282 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
471dd315 1283 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
0d449e38 1284 return wantarray ? ($volid, 0, $devpath) : $volid;
e2007ac2
DM
1285 } elsif ($type eq 'bind') {
1286 die "directory '$volid' does not exist\n" if ! -d $volid;
ab3722b3 1287 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
50df544c
WB
1288 warn "cannot enable quota control for bind mounts\n" if $quota;
1289 return wantarray ? ($volid, 0, undef) : $volid;
b15c75fc
DM
1290 }
1291
1292 die "unsupported storage";
cc6b0307
AD
1293}
1294
6c871c36 1295sub mkfs {
d216e891 1296 my ($dev, $rootuid, $rootgid) = @_;
6c871c36 1297
d216e891
WB
1298 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1299 '-E', "root_owner=$rootuid:$rootgid",
1300 $dev]);
6c871c36
DM
1301}
1302
1303sub format_disk {
d216e891 1304 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
6c871c36
DM
1305
1306 if ($volid =~ m!^/dev/.+!) {
1307 mkfs($volid);
1308 return;
1309 }
1310
1311 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1312
1313 die "cannot format volume '$volid' with no storage\n" if !$storage;
1314
08ca136d
DM
1315 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1316
6c871c36
DM
1317 my $path = PVE::Storage::path($storage_cfg, $volid);
1318
1319 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1320 PVE::Storage::parse_volname($storage_cfg, $volid);
1321
1322 die "cannot format volume '$volid' (format == $format)\n"
1323 if $format ne 'raw';
1324
d216e891 1325 mkfs($path, $rootuid, $rootgid);
6c871c36
DM
1326}
1327
1328sub destroy_disks {
1329 my ($storecfg, $vollist) = @_;
1330
1331 foreach my $volid (@$vollist) {
1332 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1333 warn $@ if $@;
1334 }
1335}
1336
c9cf8008
WB
1337sub alloc_disk {
1338 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1339
1340 my $needs_chown = 0;
1341 my $volid;
1342
1343 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1344 # fixme: use better naming ct-$vmid-disk-X.raw?
1345
1346 eval {
1347 my $do_format = 0;
1348 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1349 if ($size_kb > 0) {
1350 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1351 undef, $size_kb);
1352 $do_format = 1;
1353 } else {
1354 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1355 undef, 0);
1356 $needs_chown = 1;
1357 }
1358 } elsif ($scfg->{type} eq 'zfspool') {
1359
1360 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1361 undef, $size_kb);
1362 $needs_chown = 1;
1363 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1364
1365 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1366 $do_format = 1;
1367
1368 } elsif ($scfg->{type} eq 'rbd') {
1369
1370 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd};
1371 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1372 $do_format = 1;
1373 } else {
1374 die "unable to create containers on storage type '$scfg->{type}'\n";
1375 }
1376 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1377 };
1378 if (my $err = $@) {
1379 # in case formatting got interrupted:
1380 if (defined($volid)) {
1381 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1382 warn $@ if $@;
1383 }
1384 die $err;
1385 }
1386
1387 return ($volid, $needs_chown);
1388}
1389
2aee38e5 1390our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
6c871c36
DM
1391sub create_disks {
1392 my ($storecfg, $vmid, $settings, $conf) = @_;
1393
1394 my $vollist = [];
1395
1396 eval {
d216e891
WB
1397 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1398 my $chown_vollist = [];
1399
d250604f 1400 PVE::LXC::Config->foreach_mountpoint($settings, sub {
6c871c36
DM
1401 my ($ms, $mountpoint) = @_;
1402
1403 my $volid = $mountpoint->{volume};
1404 my $mp = $mountpoint->{mp};
1405
1406 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1407
2aee38e5 1408 if ($storage && ($volid =~ $NEW_DISK_RE)) {
8ed5ff9d 1409 my ($storeid, $size_gb) = ($1, $2);
6c871c36 1410
8ed5ff9d 1411 my $size_kb = int(${size_gb}*1024) * 1024;
6c871c36 1412
c9cf8008
WB
1413 my $needs_chown = 0;
1414 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1415 push @$chown_vollist, $volid if $needs_chown;
6c871c36 1416 push @$vollist, $volid;
71c780b9
WB
1417 $mountpoint->{volume} = $volid;
1418 $mountpoint->{size} = $size_kb * 1024;
1b4cf758 1419 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36 1420 } else {
e2007ac2 1421 # use specified/existing volid/dir/device
1b4cf758 1422 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36
DM
1423 }
1424 });
d216e891
WB
1425
1426 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1427 foreach my $volid (@$chown_vollist) {
1428 my $path = PVE::Storage::path($storecfg, $volid, undef);
1429 chown($rootuid, $rootgid, $path);
1430 }
1431 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
6c871c36
DM
1432 };
1433 # free allocated images on error
1434 if (my $err = $@) {
1435 destroy_disks($storecfg, $vollist);
1436 die $err;
1437 }
1438 return $vollist;
1439}
1440
68e8f3c5
DM
1441# bash completion helper
1442
1443sub complete_os_templates {
1444 my ($cmdname, $pname, $cvalue) = @_;
1445
1446 my $cfg = PVE::Storage::config();
1447
9e9bc3a6 1448 my $storeid;
68e8f3c5
DM
1449
1450 if ($cvalue =~ m/^([^:]+):/) {
1451 $storeid = $1;
1452 }
1453
1454 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1455 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1456
1457 my $res = [];
1458 foreach my $id (keys %$data) {
1459 foreach my $item (@{$data->{$id}}) {
1460 push @$res, $item->{volid} if defined($item->{volid});
1461 }
1462 }
1463
1464 return $res;
1465}
1466
68e8f3c5
DM
1467my $complete_ctid_full = sub {
1468 my ($running) = @_;
1469
1470 my $idlist = vmstatus();
1471
1472 my $active_hash = list_active_containers();
1473
1474 my $res = [];
1475
1476 foreach my $id (keys %$idlist) {
1477 my $d = $idlist->{$id};
1478 if (defined($running)) {
1479 next if $d->{template};
1480 next if $running && !$active_hash->{$id};
1481 next if !$running && $active_hash->{$id};
1482 }
1483 push @$res, $id;
1484
1485 }
1486 return $res;
1487};
1488
1489sub complete_ctid {
1490 return &$complete_ctid_full();
1491}
1492
1493sub complete_ctid_stopped {
1494 return &$complete_ctid_full(0);
1495}
1496
1497sub complete_ctid_running {
1498 return &$complete_ctid_full(1);
1499}
1500
c6a605f9
WB
1501sub parse_id_maps {
1502 my ($conf) = @_;
1503
1504 my $id_map = [];
1505 my $rootuid = 0;
1506 my $rootgid = 0;
1507
1508 my $lxc = $conf->{lxc};
1509 foreach my $entry (@$lxc) {
1510 my ($key, $value) = @$entry;
108c6cab
WB
1511 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1512 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
c6a605f9
WB
1513 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1514 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1515 push @$id_map, [$type, $ct, $host, $length];
1516 if ($ct == 0) {
1517 $rootuid = $host if $type eq 'u';
1518 $rootgid = $host if $type eq 'g';
1519 }
1520 } else {
108c6cab 1521 die "failed to parse idmap: $value\n";
c6a605f9
WB
1522 }
1523 }
1524
1525 if (!@$id_map && $conf->{unprivileged}) {
1526 # Should we read them from /etc/subuid?
1527 $id_map = [ ['u', '0', '100000', '65536'],
1528 ['g', '0', '100000', '65536'] ];
1529 $rootuid = $rootgid = 100000;
1530 }
1531
1532 return ($id_map, $rootuid, $rootgid);
1533}
1534
01dce99b
WB
1535sub userns_command {
1536 my ($id_map) = @_;
1537 if (@$id_map) {
1538 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1539 }
1540 return [];
1541}
1542
6725e93c
AA
1543sub vm_start {
1544 my ($vmid, $conf, $skiplock) = @_;
1545
1546 update_lxc_config($vmid, $conf);
1547
2e64f057
AA
1548 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1549
1550 if ($skiplock) {
1551 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1552 close($fh);
1553 }
6725e93c
AA
1554
1555 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1556
2e64f057
AA
1557 eval { PVE::Tools::run_command($cmd); };
1558 if (my $err = $@) {
1559 unlink $skiplock_flag_fn;
1560 die $err if $err;
1561 }
6725e93c
AA
1562
1563 return;
1564}
1565
b1bad293
WB
1566# Helper to stop a container completely and make sure it has stopped completely.
1567# This is necessary because we want the post-stop hook to have completed its
1568# unmount-all step, but post-stop happens after lxc puts the container into the
1569# STOPPED state.
1570sub vm_stop {
1571 my ($vmid, $kill, $shutdown_timeout, $exit_timeout) = @_;
1572
1573 # Open the container's command socket.
1574 my $path = "\0/var/lib/lxc/$vmid/command";
1575 my $sock = IO::Socket::UNIX->new(
1576 Type => SOCK_STREAM(),
1577 Peer => $path,
1578 );
1579 if (!$sock) {
1580 return if $! == ECONNREFUSED; # The container is not running
1581 die "failed to open container ${vmid}'s command socket: $!\n";
1582 }
1583
1584 # Stop the container:
1585
1586 my $cmd = ['lxc-stop', '-n', $vmid];
1587
1588 if ($kill) {
1589 push @$cmd, '--kill'; # doesn't allow timeouts
1590 } elsif (defined($shutdown_timeout)) {
1591 push @$cmd, '--timeout', $shutdown_timeout;
1592 # Give run_command 5 extra seconds
1593 $shutdown_timeout += 5;
1594 }
1595
1596 eval { PVE::Tools::run_command($cmd, timeout => $shutdown_timeout) };
1597 if (my $err = $@) {
1598 warn $@ if $@;
1599 }
1600
1601 my $result = 1;
1602 my $wait = sub { $result = <$sock>; };
1603 if (defined($exit_timeout)) {
1604 PVE::Tools::run_with_timeout($exit_timeout, $wait);
1605 } else {
1606 $wait->();
1607 }
1608
1609 return if !defined $result; # monitor is gone and the ct has stopped.
1610 die "container did not stop\n";
1611}
846a66b0 1612
00501642
WB
1613sub run_unshared {
1614 my ($code) = @_;
1615
1616 return PVE::Tools::run_fork(sub {
1617 # Unshare the mount namespace
1618 die "failed to unshare mount namespace: $!\n"
1619 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
1620 PVE::Tools::run_command(['mount', '--make-rslave', '/']);
1621 return $code->();
1622 });
1623}
1624
1625my $copy_volume = sub {
1626 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname) = @_;
1627
1628 my $src_mp = { volume => $src_volid, mp => '/' };
1629 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
1630
1631 my $dst_mp = { volume => $dst_volid, mp => '/' };
1632 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
1633
1634 my @mounted;
1635 eval {
1636 # mount and copy
1637 mkdir $src;
1638 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname);
1639 push @mounted, $src;
1640 mkdir $dest;
1641 mountpoint_mount($dst_mp, $dest, $storage_cfg);
1642 push @mounted, $dest;
1643
1644 PVE::Tools::run_command(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
1645 '-aH', '--whole-file', '--sparse', '--one-file-system',
1646 "$src/", $dest]);
1647 };
1648 my $err = $@;
1649 foreach my $mount (reverse @mounted) {
1650 eval { PVE::Tools::run_command(['/bin/umount', '--lazy', $mount], errfunc => sub{})};
1651 warn "Can't umount $mount\n" if $@;
1652 }
1653
1654 # If this fails they're used as mount points in a concurrent operation
1655 # (which should not happen but there's also no real need to get rid of them).
1656 rmdir $dest;
1657 rmdir $src;
1658
1659 die $err if $err;
1660};
1661
1662# Should not be called after unsharing the mount namespace!
1663sub copy_volume {
1664 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname) = @_;
1665
1666 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
1667 File::Path::make_path("/var/lib/lxc/$vmid");
1668 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
1669 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
1670
1671 # get id's for unprivileged container
1672 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1673
1674 # Allocate the disk before unsharing in order to make sure zfs subvolumes
1675 # are visible in this namespace, otherwise the host only sees the empty
1676 # (not-mounted) directory.
1677 my $new_volid;
1678 eval {
1679 my $needs_chown;
1680 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
1681 if ($needs_chown) {
1682 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
1683 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
1684 chown($rootuid, $rootgid, $path);
1685 }
1686
1687 run_unshared(sub {
1688 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname);
1689 });
1690 };
1691 if (my $err = $@) {
1692 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
1693 if defined($new_volid);
1694 die $err;
1695 }
1696
1697 return $new_volid;
1698}
1699
f76a2828 17001;