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