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