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