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