]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC.pm
split walk_tree_nofollow to allow a start fd
[pve-container.git] / src / PVE / LXC.pm
CommitLineData
f76a2828
DM
1package PVE::LXC;
2
3use strict;
4use warnings;
67afe46e 5
d14a9a1b 6use POSIX qw(EINTR);
f76a2828 7
34fdb3d7
WB
8use Socket;
9
f76a2828 10use File::Path;
2cfae16e
WB
11use File::Spec;
12use Cwd qw();
ab3722b3 13use Fcntl qw(O_RDONLY O_NOFOLLOW O_DIRECTORY);
b1bad293
WB
14use Errno qw(ELOOP ENOTDIR EROFS ECONNREFUSED);
15use IO::Socket::UNIX;
f76a2828 16
f1ba1a4b 17use PVE::Exception qw(raise_perm_exc);
c65e0a6d 18use PVE::Storage;
f76a2828
DM
19use PVE::SafeSyslog;
20use PVE::INotify;
8233d33d 21use PVE::JSONSchema qw(get_standard_option);
ab3722b3 22use PVE::Tools qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH);
92902047 23use PVE::CpuSet;
68fba17b 24use PVE::Network;
52389a07 25use PVE::AccessControl;
228a5a1d 26use PVE::ProcFSTools;
0389da0d 27use PVE::Syscall;
67afe46e 28use PVE::LXC::Config;
1a416433 29use PVE::GuestHelpers;
8233d33d 30
688afc63 31use Time::HiRes qw (gettimeofday);
f76a2828 32
5a63f1c5
WB
33my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
34
27916659
DM
35my $nodename = PVE::INotify::nodename();
36
688afc63
WL
37my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
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';
8233d33d 50 $res->{$vmid} = { type => 'lxc', vmid => $vmid };
f76a2828
DM
51 }
52 return $res;
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 {
3b5070d4 101 my ($vmid, $unprivileged) = @_;
688afc63 102
3b5070d4 103 my $raw = read_cgroup_value('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
688afc63
WL
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
8233d33d
DM
117our $vmstatus_return_properties = {
118 vmid => get_standard_option('pve-vmid'),
119 status => {
120 description => "LXC Container status.",
121 type => 'string',
122 enum => ['stopped', 'running'],
123 },
124 maxmem => {
125 description => "Maximum memory in bytes.",
126 type => 'integer',
127 optional => 1,
128 renderer => 'bytes',
129 },
130 maxswap => {
131 description => "Maximum SWAP memory in bytes.",
132 type => 'integer',
133 optional => 1,
134 renderer => 'bytes',
135 },
136 maxdisk => {
137 description => "Root disk size in bytes.",
138 type => 'integer',
139 optional => 1,
140 renderer => 'bytes',
141 },
142 name => {
143 description => "Container name.",
144 type => 'string',
145 optional => 1,
146 },
147 uptime => {
148 description => "Uptime.",
149 type => 'integer',
150 optional => 1,
151 renderer => 'duration',
152 },
153 cpus => {
154 description => "Maximum usable CPUs.",
155 type => 'number',
156 optional => 1,
157 },
440b6427 158 lock => {
87c5dc96 159 description => "The current config lock, if any.",
440b6427
DC
160 type => 'string',
161 optional => 1,
162 }
8233d33d
DM
163};
164
f76a2828
DM
165sub vmstatus {
166 my ($opt_vmid) = @_;
167
8233d33d 168 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc', vmid => $opt_vmid }} : config_list();
f76a2828 169
822de0c3 170 my $active_hash = list_active_containers();
cbb03fea 171
688afc63
WL
172 my $cpucount = $cpuinfo->{cpus} || 1;
173
174 my $cdtime = gettimeofday;
175
176 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
80d56111 177 my $clock_ticks = POSIX::sysconf(&POSIX::_SC_CLK_TCK);
688afc63 178
3b5070d4
WB
179 my $unprivileged = {};
180
f76a2828 181 foreach my $vmid (keys %$list) {
f76a2828 182 my $d = $list->{$vmid};
10fc3ba5 183
d5588ee3
DM
184 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
185 warn $@ if $@; # ignore errors (consider them stopped)
cbb03fea 186
2ff1c49c 187 $d->{status} = $active_hash->{$vmid} ? 'running' : 'stopped';
f76a2828 188
67afe46e 189 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
238a56cb 190 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
cbb03fea 191
3b5070d4
WB
192 $unprivileged->{$vmid} = $conf->{unprivileged};
193
27916659 194 $d->{name} = $conf->{'hostname'} || "CT$vmid";
238a56cb 195 $d->{name} =~ s/[\s]//g;
cbb03fea 196
f2357408
DM
197 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
198 $d->{cpus} = $cpucount if !$d->{cpus};
44da0641 199
d0226204
WB
200 $d->{lock} = $conf->{lock} || '';
201
d5588ee3
DM
202 if ($d->{pid}) {
203 my $res = get_container_disk_usage($vmid, $d->{pid});
27916659
DM
204 $d->{disk} = $res->{used};
205 $d->{maxdisk} = $res->{total};
206 } else {
207 $d->{disk} = 0;
208 # use 4GB by default ??
209 if (my $rootfs = $conf->{rootfs}) {
1b4cf758 210 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($rootfs);
af02245c 211 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
27916659
DM
212 } else {
213 $d->{maxdisk} = 4*1024*1024*1024;
10fc3ba5 214 }
238a56cb 215 }
cbb03fea 216
238a56cb
DM
217 $d->{mem} = 0;
218 $d->{swap} = 0;
95df9a12
DM
219 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
220 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
e901d418 221
238a56cb
DM
222 $d->{uptime} = 0;
223 $d->{cpu} = 0;
e901d418 224
238a56cb
DM
225 $d->{netout} = 0;
226 $d->{netin} = 0;
f76a2828 227
238a56cb
DM
228 $d->{diskread} = 0;
229 $d->{diskwrite} = 0;
bb1ac2de 230
67afe46e 231 $d->{template} = PVE::LXC::Config->is_template($conf);
440b6427 232 $d->{lock} = $conf->{lock} if $conf->{lock};
f76a2828 233 }
cbb03fea 234
238a56cb
DM
235 foreach my $vmid (keys %$list) {
236 my $d = $list->{$vmid};
d5588ee3
DM
237 my $pid = $d->{pid};
238
239 next if !$pid; # skip stopped CTs
f76a2828 240
80d56111
DC
241 my $proc_pid_stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
242 $d->{uptime} = int(($uptime - $proc_pid_stat->{starttime}) / $clock_ticks); # the method lxcfs uses
22a77285 243
3b5070d4
WB
244 my $unpriv = $unprivileged->{$vmid};
245
0b6a2f0e
WB
246 if (-d '/sys/fs/cgroup/memory') {
247 my $memory_stat = read_cgroup_list('memory', $vmid, $unpriv, 'memory.stat');
248 my $mem_usage_in_bytes = read_cgroup_value('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
249
250 $d->{mem} = $mem_usage_in_bytes - $memory_stat->{total_cache};
251 $d->{swap} = read_cgroup_value('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
252 } else {
253 $d->{mem} = 0;
254 $d->{swap} = 0;
255 }
256
257 if (-d '/sys/fs/cgroup/blkio') {
0defbe08 258 my $blkio_bytes = read_cgroup_value('blkio', $vmid, 0, 'blkio.throttle.io_service_bytes', 1); # don't check if unpriv
0b6a2f0e
WB
259 my @bytes = split(/\n/, $blkio_bytes);
260 foreach my $byte (@bytes) {
261 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
262 $d->{diskread} += $2 if $key eq 'Read';
263 $d->{diskwrite} += $2 if $key eq 'Write';
264 }
1e647c7c 265 }
0b6a2f0e
WB
266 } else {
267 $d->{diskread} = 0;
268 $d->{diskwrite} = 0;
b5289322 269 }
688afc63 270
0b6a2f0e
WB
271 if (-d '/sys/fs/cgroup/cpuacct') {
272 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
688afc63 273
0b6a2f0e 274 my $used = $pstat->{utime} + $pstat->{stime};
688afc63 275
0b6a2f0e
WB
276 my $old = $last_proc_vmid_stat->{$vmid};
277 if (!$old) {
278 $last_proc_vmid_stat->{$vmid} = {
279 time => $cdtime,
280 used => $used,
281 cpu => 0,
282 };
283 next;
284 }
688afc63 285
0b6a2f0e 286 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
688afc63 287
0b6a2f0e
WB
288 if ($dtime > 1000) {
289 my $dutime = $used - $old->{used};
688afc63 290
0b6a2f0e
WB
291 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
292 $last_proc_vmid_stat->{$vmid} = {
293 time => $cdtime,
294 used => $used,
295 cpu => $d->{cpu},
296 };
297 } else {
298 $d->{cpu} = $old->{cpu};
299 }
688afc63 300 } else {
0b6a2f0e 301 $d->{cpu} = 0;
688afc63 302 }
238a56cb 303 }
cbb03fea 304
68b8f4d1
WL
305 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
306
307 foreach my $dev (keys %$netdev) {
308 next if $dev !~ m/^veth([1-9]\d*)i/;
309 my $vmid = $1;
310 my $d = $list->{$vmid};
311
312 next if !$d;
313
314 $d->{netout} += $netdev->{$dev}->{receive};
315 $d->{netin} += $netdev->{$dev}->{transmit};
316
317 }
318
f76a2828
DM
319 return $list;
320}
321
3b5070d4
WB
322sub read_cgroup_list($$$$) {
323 my ($group, $vmid, $unprivileged, $name) = @_;
b3059d35 324
3b5070d4 325 my $content = read_cgroup_value($group, $vmid, $unprivileged, $name, 1);
b3059d35
TL
326
327 return { split(/\s+/, $content) };
328}
329
3b5070d4
WB
330sub read_cgroup_value($$$$$) {
331 my ($group, $vmid, $unprivileged, $name, $full) = @_;
238a56cb 332
3b5070d4
WB
333 my $nsdir = $unprivileged ? '' : 'ns/';
334 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
238a56cb
DM
335
336 return PVE::Tools::file_get_contents($path) if $full;
337
338 return PVE::Tools::file_read_firstline($path);
339}
340
bf0b8c43
AD
341sub write_cgroup_value {
342 my ($group, $vmid, $name, $value) = @_;
343
344 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
345 PVE::ProcFSTools::write_proc_entry($path, $value) if -e $path;
346
347}
348
52f1d76b
DM
349sub find_lxc_console_pids {
350
351 my $res = {};
352
353 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
354 my ($pid) = @_;
355
356 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
357 return if !$cmdline;
358
359 my @args = split(/\0/, $cmdline);
360
c31ad455 361 # search for lxc-console -n <vmid>
cbb03fea 362 return if scalar(@args) != 3;
52f1d76b
DM
363 return if $args[1] ne '-n';
364 return if $args[2] !~ m/^\d+$/;
365 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
cbb03fea 366
52f1d76b 367 my $vmid = $args[2];
cbb03fea 368
52f1d76b
DM
369 push @{$res->{$vmid}}, $pid;
370 });
371
372 return $res;
373}
374
bedeaaf1
AD
375sub find_lxc_pid {
376 my ($vmid) = @_;
377
378 my $pid = undef;
379 my $parser = sub {
380 my $line = shift;
8b25977f 381 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
bedeaaf1 382 };
c39aa40a 383 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
bedeaaf1 384
8b25977f 385 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
cbb03fea 386
8b25977f 387 return $pid;
bedeaaf1
AD
388}
389
cbb03fea 390# Note: we cannot use Net:IP, because that only allows strict
55fa4e09
DM
391# CIDR networks
392sub parse_ipv4_cidr {
393 my ($cidr, $noerr) = @_;
394
f7a7b413
WB
395 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
396 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
55fa4e09 397 }
cbb03fea 398
55fa4e09 399 return undef if $noerr;
cbb03fea 400
55fa4e09
DM
401 die "unable to parse ipv4 address/mask\n";
402}
93285df8 403
0b6a2f0e
WB
404sub get_cgroup_subsystems {
405 my $v1 = {};
406 my $v2 = 0;
407 my $data = PVE::Tools::file_get_contents('/proc/self/cgroup');
408 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
409 my $type = $1;
410 if (length($type)) {
411 $v1->{$_} = 1 foreach split(/,/, $type);
412 } else {
413 $v2 = 1;
414 }
415 }
416 return wantarray ? ($v1, $v2) : $v1;
417}
e22af68f 418
5a63f1c5
WB
419# Currently we do not need to create seccomp profile 'files' as the only
420# choice our configuration actually allows is "with or without keyctl()",
421# so we distinguish between using lxc's "default" seccomp profile and our
422# added pve-userns.seccomp file.
423#
424# This returns a configuration line added to the raw lxc config.
425sub make_seccomp_config {
426 my ($conf, $unprivileged, $features) = @_;
427 # User-configured profile has precedence, note that the user's entry would
428 # be written 'after' this line anyway...
429 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.seccomp.profile')) {
430 # Warn the user if this conflicts with a feature:
431 if ($features->{keyctl}) {
432 warn "explicitly configured lxc.seccomp.profile overrides the following settings: features:keyctl\n";
433 }
434 return '';
435 }
436
437 # Privileged containers keep using the default (which is already part of
438 # the files included via lxc.include, so we don't need to write it out,
439 # that way it stays admin-configurable via /usr/share/lxc/config/... as
440 # well)
441 return '' if !$unprivileged;
442
443 # Unprivileged containers will get keyctl() disabled by default as a
444 # workaround for systemd-networkd behavior. But we have an option to
445 # explicitly enable it:
446 return '' if $features->{keyctl};
447
448 # Finally we're in an unprivileged container without `keyctl` set
449 # explicitly. We have a file prepared for this:
450 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
451}
452
453# Since lxc-3.0.2 we can have lxc generate a profile for the container
454# automatically. The default should be equivalent to the old
455# `lxc-container-default-cgns` profile.
456#
457# Additionally this also added `lxc.apparmor.raw` which can be used to inject
458# additional lines into the profile. We can use that to allow mounting specific
459# file systems.
460sub make_apparmor_config {
461 my ($conf, $unprivileged, $features) = @_;
462
463 # user-configured profile has precedence, but first we go through our own
464 # code to figure out whether we should warn the user:
465
466 my $raw = "lxc.apparmor.profile = generated\n";
467 my @profile_uses;
468
96f8d2a2
WB
469 if ($features->{fuse}) {
470 # For the informational warning:
471 push @profile_uses, 'features:fuse';
472 }
473
5a63f1c5
WB
474 # There's lxc.apparmor.allow_nesting now, which will add the necessary
475 # apparmor lines, create an apparmor namespace for the container, but also
476 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
477 # lxcfs mounted over them, because that would prevent the container from
478 # mounting new instances of them for nested containers.
479 if ($features->{nesting}) {
480 push @profile_uses, 'features:nesting';
481 $raw .= "lxc.apparmor.allow_nesting = 1\n"
482 } else {
483 # In the default profile in /etc/apparmor.d we patch this in because
484 # otherwise a container can for example run `chown` on /sys, breaking
485 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
486 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
487 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
488 # Preferably we could use the 'remount' flag but this does not sit well
489 # with apparmor_parser currently:
490 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
491 }
492
493 if (my $mount = $features->{mount}) {
494 push @profile_uses, 'features:mount';
495 foreach my $fs (PVE::Tools::split_list($mount)) {
496 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
497 }
498 }
499
500 # More to come?
501
502 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.apparmor.profile')) {
503 if (length(my $used = join(', ', @profile_uses))) {
504 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
505 }
506 return '';
507 }
508
509 return $raw;
510}
511
27916659 512sub update_lxc_config {
f91f3669 513 my ($vmid, $conf) = @_;
b80dd50a 514
bb1ac2de
DM
515 my $dir = "/var/lib/lxc/$vmid";
516
517 if ($conf->{template}) {
518
519 unlink "$dir/config";
520
521 return;
522 }
523
27916659 524 my $raw = '';
b80dd50a 525
27916659
DM
526 die "missing 'arch' - internal error" if !$conf->{arch};
527 $raw .= "lxc.arch = $conf->{arch}\n";
b80dd50a 528
5a63f1c5
WB
529 my $custom_idmap = PVE::LXC::Config->has_lxc_entry($conf, 'lxc.idmap');
530 my $unprivileged = $conf->{unprivileged} || $custom_idmap;
425b62cb 531
27916659 532 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
866e0611 533
059f7bb4
WB
534 my $cfgpath = '/usr/share/lxc/config';
535 my $inc = "$cfgpath/$ostype.common.conf";
536 $inc ="$cfgpath/common.conf" if !-f $inc;
866e0611 537 $raw .= "lxc.include = $inc\n";
5a63f1c5 538 if ($unprivileged) {
059f7bb4
WB
539 $inc = "$cfgpath/$ostype.userns.conf";
540 $inc = "$cfgpath/userns.conf" if !-f $inc;
541 $raw .= "lxc.include = $inc\n";
27916659 542 }
b80dd50a 543
5a63f1c5
WB
544 my $features = PVE::LXC::Config->parse_features($conf->{features});
545
546 $raw .= make_seccomp_config($conf, $unprivileged, $features);
547 $raw .= make_apparmor_config($conf, $unprivileged, $features);
96f8d2a2
WB
548 if ($features->{fuse}) {
549 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
550 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
551 }
5a63f1c5 552
50df544c
WB
553 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
554 # cannot be exposed to the container with r/w access (cgroup perms).
555 # When this is enabled mounts will still remain in the monitor's namespace
556 # after the container unmounted them and thus will not detach from their
557 # files while the container is running!
c16b8890 558 $raw .= "lxc.monitor.unshare = 1\n";
58cc92a9 559
0b6a2f0e
WB
560 my $cgv1 = get_cgroup_subsystems();
561
425b62cb
WB
562 # Should we read them from /etc/subuid?
563 if ($unprivileged && !$custom_idmap) {
108c6cab
WB
564 $raw .= "lxc.idmap = u 0 100000 65536\n";
565 $raw .= "lxc.idmap = g 0 100000 65536\n";
425b62cb
WB
566 }
567
d250604f 568 if (!PVE::LXC::Config->has_dev_console($conf)) {
108c6cab 569 $raw .= "lxc.console.path = none\n";
0b6a2f0e 570 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices};
eeaea429 571 }
4f958489 572
1b4cf758 573 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
108c6cab 574 $raw .= "lxc.tty.max = $ttycount\n";
cbb03fea 575
c31ad455 576 # some init scripts expect a linux terminal (turnkey).
a691a5a3
DM
577 $raw .= "lxc.environment = TERM=linux\n";
578
27916659 579 my $utsname = $conf->{hostname} || "CT$vmid";
108c6cab 580 $raw .= "lxc.uts.name = $utsname\n";
cbb03fea 581
0b6a2f0e
WB
582 if ($cgv1->{memory}) {
583 my $memory = $conf->{memory} || 512;
584 my $swap = $conf->{swap} // 0;
a12a36e0 585
0b6a2f0e
WB
586 my $lxcmem = int($memory*1024*1024);
587 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
27916659 588
0b6a2f0e
WB
589 my $lxcswap = int(($memory + $swap)*1024*1024);
590 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
a12a36e0
WL
591 }
592
0b6a2f0e
WB
593 if ($cgv1->{cpu}) {
594 if (my $cpulimit = $conf->{cpulimit}) {
595 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
596 my $value = int(100000*$cpulimit);
597 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
598 }
599
600 my $shares = $conf->{cpuunits} || 1024;
601 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
602 }
27916659 603
fddaa91b
DM
604 die "missing 'rootfs' configuration\n"
605 if !defined($conf->{rootfs});
606
1b4cf758 607 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
a3076d81 608
108c6cab 609 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
27916659 610
e756bdd6 611 foreach my $k (sort keys %$conf) {
27916659
DM
612 next if $k !~ m/^net(\d+)$/;
613 my $ind = $1;
1b4cf758 614 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
108c6cab
WB
615 $raw .= "lxc.net.$ind.type = veth\n";
616 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
617 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
618 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name});
619 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu});
a12a36e0
WL
620 }
621
0b6a2f0e
WB
622 if ($cgv1->{cpuset}) {
623 my $had_cpuset = 0;
624 if (my $lxcconf = $conf->{lxc}) {
625 foreach my $entry (@$lxcconf) {
626 my ($k, $v) = @$entry;
627 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
628 $raw .= "$k = $v\n";
629 }
e576f689 630 }
27916659 631
0b6a2f0e
WB
632 my $cores = $conf->{cores};
633 if (!$had_cpuset && $cores) {
634 my $cpuset = eval { PVE::CpuSet->new_from_cgroup('lxc', 'effective_cpus') };
635 $cpuset = PVE::CpuSet->new_from_cgroup('', 'effective_cpus') if !$cpuset;
636 my @members = $cpuset->members();
637 while (scalar(@members) > $cores) {
638 my $randidx = int(rand(scalar(@members)));
639 $cpuset->delete($members[$randidx]);
640 splice(@members, $randidx, 1); # keep track of the changes
641 }
642 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
92902047 643 }
92902047 644 }
0b6a2f0e 645
27916659
DM
646 File::Path::mkpath("$dir/rootfs");
647
648 PVE::Tools::file_set_contents("$dir/config", $raw);
b80dd50a
DM
649}
650
117636e5
DM
651# verify and cleanup nameserver list (replace \0 with ' ')
652sub verify_nameserver_list {
653 my ($nameserver_list) = @_;
654
655 my @list = ();
656 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
657 PVE::JSONSchema::pve_verify_ip($server);
658 push @list, $server;
659 }
660
661 return join(' ', @list);
662}
663
664sub verify_searchdomain_list {
665 my ($searchdomain_list) = @_;
666
667 my @list = ();
668 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
669 # todo: should we add checks for valid dns domains?
670 push @list, $server;
671 }
672
673 return join(' ', @list);
674}
675
aca816ad 676sub get_console_command {
65213b67 677 my ($vmid, $conf, $escapechar) = @_;
39413635 678
65213b67
TM
679 # '-1' as $escapechar disables keyboard escape sequence
680 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
aca816ad 681
1b4cf758 682 my $cmode = PVE::LXC::Config->get_cmode($conf);
aca816ad 683
4d494664 684 my $cmd = [];
aca816ad 685 if ($cmode eq 'console') {
4d494664 686 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
65213b67 687 push @$cmd, '-e', $escapechar if $escapechar;
aca816ad 688 } elsif ($cmode eq 'tty') {
4d494664 689 push @$cmd, 'lxc-console', '-n', $vmid;
65213b67 690 push @$cmd, '-e', $escapechar if $escapechar;
aca816ad 691 } elsif ($cmode eq 'shell') {
4d494664 692 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
aca816ad
DM
693 } else {
694 die "internal error";
695 }
4d494664
DC
696
697 return $cmd;
aca816ad
DM
698}
699
c325b32f
DM
700sub get_primary_ips {
701 my ($conf) = @_;
702
703 # return data from net0
cbb03fea 704
27916659 705 return undef if !defined($conf->{net0});
1b4cf758 706 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
c325b32f
DM
707
708 my $ipv4 = $net->{ip};
db78a181
WB
709 if ($ipv4) {
710 if ($ipv4 =~ /^(dhcp|manual)$/) {
711 $ipv4 = undef
712 } else {
713 $ipv4 =~ s!/\d+$!!;
714 }
715 }
65e5eaa3 716 my $ipv6 = $net->{ip6};
db78a181 717 if ($ipv6) {
5f291c7d 718 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
db78a181
WB
719 $ipv6 = undef;
720 } else {
721 $ipv6 =~ s!/\d+$!!;
722 }
723 }
cbb03fea 724
c325b32f
DM
725 return ($ipv4, $ipv6);
726}
148d1cb4 727
b407293b
WB
728sub delete_mountpoint_volume {
729 my ($storage_cfg, $vmid, $volume) = @_;
730
d250604f 731 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
b407293b
WB
732
733 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
6b81ef77
TL
734
735 if ($vmid == $owner) {
736 PVE::Storage::vdisk_free($storage_cfg, $volume);
737 } else {
738 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
739 }
b407293b 740}
ef241384 741
27916659 742sub destroy_lxc_container {
bccaa371 743 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
148d1cb4 744
d250604f 745 PVE::LXC::Config->foreach_mountpoint($conf, sub {
db8989e1 746 my ($ms, $mountpoint) = @_;
b407293b 747 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
db8989e1
WB
748 });
749
27916659
DM
750 rmdir "/var/lib/lxc/$vmid/rootfs";
751 unlink "/var/lib/lxc/$vmid/config";
752 rmdir "/var/lib/lxc/$vmid";
bccaa371
FG
753 if (defined $replacement_conf) {
754 PVE::LXC::Config->write_config($vmid, $replacement_conf);
755 } else {
4eeb9af1 756 PVE::LXC::Config->destroy_config($vmid);
bccaa371 757 }
148d1cb4 758}
68fba17b 759
ef241384 760sub vm_stop_cleanup {
5fa890f0 761 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
bf9d912c 762
38e7891a
TL
763 return if $keepActive;
764
765 eval {
766 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
767 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
ef241384
DM
768 };
769 warn $@ if $@; # avoid errors - just warn
770}
771
93cdbbfb
AD
772my $safe_num_ne = sub {
773 my ($a, $b) = @_;
774
775 return 0 if !defined($a) && !defined($b);
776 return 1 if !defined($a);
777 return 1 if !defined($b);
778
779 return $a != $b;
780};
781
782my $safe_string_ne = sub {
783 my ($a, $b) = @_;
784
785 return 0 if !defined($a) && !defined($b);
786 return 1 if !defined($a);
787 return 1 if !defined($b);
788
789 return $a ne $b;
790};
791
792sub update_net {
bedeaaf1 793 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
93cdbbfb 794
18862537
WB
795 if ($newnet->{type} ne 'veth') {
796 # for when there are physical interfaces
797 die "cannot update interface of type $newnet->{type}";
798 }
799
800 my $veth = "veth${vmid}i${netid}";
93cdbbfb
AD
801 my $eth = $newnet->{name};
802
18862537 803 if (my $oldnetcfg = $conf->{$opt}) {
1b4cf758 804 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
18862537
WB
805
806 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
807 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
93cdbbfb 808
18862537 809 PVE::Network::veth_delete($veth);
bedeaaf1 810 delete $conf->{$opt};
67afe46e 811 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb 812
18862537 813 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
bedeaaf1 814
380962c7
WB
815 } else {
816 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
817 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
818 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
bedeaaf1 819
18862537 820 if ($oldnet->{bridge}) {
bedeaaf1 821 PVE::Network::tap_unplug($veth);
18862537
WB
822 foreach (qw(bridge tag firewall)) {
823 delete $oldnet->{$_};
824 }
1b4cf758 825 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
67afe46e 826 PVE::LXC::Config->write_config($vmid, $conf);
bedeaaf1 827 }
93cdbbfb 828
380962c7
WB
829 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
830 # This includes the rate:
831 foreach (qw(bridge tag firewall rate)) {
18862537
WB
832 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
833 }
380962c7
WB
834 } elsif (&$safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
835 # Rate can be applied on its own but any change above needs to
836 # include the rate in tap_plug since OVS resets everything.
837 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
838 $oldnet->{rate} = $newnet->{rate}
839 }
840 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
841 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
842 }
843 } else {
18862537 844 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
93cdbbfb
AD
845 }
846
bedeaaf1 847 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
93cdbbfb
AD
848}
849
850sub hotplug_net {
18862537 851 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
93cdbbfb 852
18862537 853 my $veth = "veth${vmid}i${netid}";
cbb03fea 854 my $vethpeer = $veth . "p";
93cdbbfb
AD
855 my $eth = $newnet->{name};
856
857 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
380962c7 858 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
93cdbbfb 859
cbb03fea 860 # attach peer in container
93cdbbfb
AD
861 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
862 PVE::Tools::run_command($cmd);
863
cbb03fea 864 # link up peer in container
93cdbbfb
AD
865 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
866 PVE::Tools::run_command($cmd);
bedeaaf1 867
18862537
WB
868 my $done = { type => 'veth' };
869 foreach (qw(bridge tag firewall hwaddr name)) {
870 $done->{$_} = $newnet->{$_} if $newnet->{$_};
871 }
1b4cf758 872 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
bedeaaf1 873
67afe46e 874 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
875}
876
68a05bb3 877sub update_ipconfig {
bedeaaf1
AD
878 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
879
f2104b80 880 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
bedeaaf1 881
1b4cf758 882 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
84e0c123
WB
883 my $deleted = [];
884 my $added = [];
8d723477
WB
885 my $nscmd = sub {
886 my $cmdargs = shift;
887 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
84e0c123 888 };
8d723477 889 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
2bfd1615 890
84e0c123 891 my $change_ip_config = sub {
f39002a6
DM
892 my ($ipversion) = @_;
893
894 my $family_opt = "-$ipversion";
895 my $suffix = $ipversion == 4 ? '' : $ipversion;
84e0c123
WB
896 my $gw= "gw$suffix";
897 my $ip= "ip$suffix";
bedeaaf1 898
6178b0dd
WB
899 my $newip = $newnet->{$ip};
900 my $newgw = $newnet->{$gw};
901 my $oldip = $optdata->{$ip};
ded5d25a 902 my $oldgw = $optdata->{$gw};
6178b0dd
WB
903
904 my $change_ip = &$safe_string_ne($oldip, $newip);
ded5d25a 905 my $change_gw = &$safe_string_ne($oldgw, $newgw);
bedeaaf1 906
84e0c123 907 return if !$change_ip && !$change_gw;
68a05bb3 908
84e0c123 909 # step 1: add new IP, if this fails we cancel
292aff54
WB
910 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
911 if ($change_ip && $is_real_ip) {
8d723477 912 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
84e0c123
WB
913 if (my $err = $@) {
914 warn $err;
915 return;
916 }
bedeaaf1 917 }
bedeaaf1 918
84e0c123
WB
919 # step 2: replace gateway
920 # If this fails we delete the added IP and cancel.
921 # If it succeeds we save the config and delete the old IP, ignoring
922 # errors. The config is then saved.
923 # Note: 'ip route replace' can add
924 if ($change_gw) {
6178b0dd 925 if ($newgw) {
292aff54
WB
926 eval {
927 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
928 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
929 }
930 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
931 };
84e0c123
WB
932 if (my $err = $@) {
933 warn $err;
934 # the route was not replaced, the old IP is still available
935 # rollback (delete new IP) and cancel
936 if ($change_ip) {
8d723477 937 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
84e0c123
WB
938 warn $@ if $@; # no need to die here
939 }
940 return;
941 }
942 } else {
8d723477 943 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
84e0c123
WB
944 # if the route was not deleted, the guest might have deleted it manually
945 # warn and continue
946 warn $@ if $@;
947 }
ded5d25a
DL
948 if ($oldgw && $oldip && !PVE::Network::is_ip_in_cidr($oldgw, $oldip)) {
949 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
950 # warn if the route was deleted manually
951 warn $@ if $@;
952 }
2bfd1615 953 }
2bfd1615 954
6178b0dd 955 # from this point on we save the configuration
84e0c123 956 # step 3: delete old IP ignoring errors
6178b0dd 957 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
8d723477
WB
958 # We need to enable promote_secondaries, otherwise our newly added
959 # address will be removed along with the old one.
960 my $promote = 0;
961 eval {
962 if ($ipversion == 4) {
963 &$nscmd({ outfunc => sub { $promote = int(shift) } },
964 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
965 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
966 }
967 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
968 };
84e0c123 969 warn $@ if $@; # no need to die here
8d723477
WB
970
971 if ($ipversion == 4) {
972 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
973 }
bedeaaf1
AD
974 }
975
84e0c123
WB
976 foreach my $property ($ip, $gw) {
977 if ($newnet->{$property}) {
978 $optdata->{$property} = $newnet->{$property};
979 } else {
980 delete $optdata->{$property};
981 }
bedeaaf1 982 }
1b4cf758 983 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
67afe46e 984 PVE::LXC::Config->write_config($vmid, $conf);
84e0c123
WB
985 $lxc_setup->setup_network($conf);
986 };
bedeaaf1 987
f39002a6
DM
988 &$change_ip_config(4);
989 &$change_ip_config(6);
489e960d
WL
990
991}
992
34fdb3d7
WB
993my $enter_namespace = sub {
994 my ($vmid, $pid, $which, $type) = @_;
995 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
996 or die "failed to open $which namespace of container $vmid: $!\n";
997 PVE::Tools::setns(fileno($fd), $type)
998 or die "failed to enter $which namespace of container $vmid: $!\n";
999 close $fd;
1000};
1001
1002my $do_syncfs = sub {
1003 my ($vmid, $pid, $socket) = @_;
1004
1005 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
1006
1007 # Tell the parent process to start reading our /proc/mounts
1008 print {$socket} "go\n";
1009 $socket->flush();
1010
1011 # Receive /proc/self/mounts
1012 my $mountdata = do { local $/ = undef; <$socket> };
1013 close $socket;
1014
1015 # Now sync all mountpoints...
1016 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
1017 foreach my $mp (@$mounts) {
1018 my ($what, $dir, $fs) = @$mp;
1019 next if $fs eq 'fuse.lxcfs';
1020 eval { PVE::Tools::sync_mountpoint($dir); };
1021 warn $@ if $@;
1022 }
1023};
1024
1025sub sync_container_namespace {
1026 my ($vmid) = @_;
1027 my $pid = find_lxc_pid($vmid);
1028
1029 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1030 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
1031 or die "failed to create socketpair: $!\n";
1032
1033 my $child = fork();
1034 die "fork failed: $!\n" if !defined($child);
1035
1036 if (!$child) {
1037 eval {
1038 close $pfd;
1039 &$do_syncfs($vmid, $pid, $cfd);
1040 };
1041 if (my $err = $@) {
1042 warn $err;
1043 POSIX::_exit(1);
1044 }
1045 POSIX::_exit(0);
1046 }
1047 close $cfd;
1048 my $go = <$pfd>;
1049 die "failed to enter container namespace\n" if $go ne "go\n";
1050
1051 open my $mounts, '<', "/proc/$child/mounts"
1052 or die "failed to open container's /proc/mounts: $!\n";
1053 my $mountdata = do { local $/ = undef; <$mounts> };
1054 close $mounts;
1055 print {$pfd} $mountdata;
1056 close $pfd;
1057
1058 while (waitpid($child, 0) != $child) {}
1059 die "failed to sync container namespace\n" if $? != 0;
1060}
1061
bb1ac2de
DM
1062sub template_create {
1063 my ($vmid, $conf) = @_;
1064
1065 my $storecfg = PVE::Storage::config();
1066
9d1cb46b
WL
1067 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1068 my ($ms, $mountpoint) = @_;
bb1ac2de 1069
9d1cb46b 1070 my $volid = $mountpoint->{volume};
bb1ac2de 1071
9d1cb46b
WL
1072 die "Template feature is not available for '$volid'\n"
1073 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
1074 });
bb1ac2de 1075
9d1cb46b
WL
1076 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1077 my ($ms, $mountpoint) = @_;
1078
1079 my $volid = $mountpoint->{volume};
1080
1081 PVE::Storage::activate_volumes($storecfg, [$volid]);
1082
1083 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
1084 $mountpoint->{volume} = $template_volid;
1085 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1086 });
bb1ac2de 1087
67afe46e 1088 PVE::LXC::Config->write_config($vmid, $conf);
bb1ac2de
DM
1089}
1090
52389a07 1091sub check_ct_modify_config_perm {
f1ba1a4b 1092 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
52389a07 1093
c81f19d1 1094 return 1 if $authuser eq 'root@pam';
52389a07 1095
f1ba1a4b
WB
1096 my $check = sub {
1097 my ($opt, $delete) = @_;
f2357408 1098 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
52389a07 1099 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
e59a61ed 1100 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
52389a07 1101 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
f1ba1a4b 1102 return if $delete;
1b4cf758
FG
1103 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
1104 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
9d294016
FG
1105 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
1106 if $data->{type} ne 'volume';
52389a07
DM
1107 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1108 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1109 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1110 $opt eq 'searchdomain' || $opt eq 'hostname') {
1111 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
5a63f1c5
WB
1112 } elsif ($opt eq 'features') {
1113 # For now this is restricted to root@pam
1114 raise_perm_exc("changing feature flags is only allowed for root\@pam");
1a416433
DC
1115 } elsif ($opt eq 'hookscript') {
1116 # For now this is restricted to root@pam
1117 raise_perm_exc("changing the hookscript is only allowed for root\@pam");
52389a07
DM
1118 } else {
1119 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1120 }
f1ba1a4b
WB
1121 };
1122
1123 foreach my $opt (keys %$newconf) {
1124 &$check($opt, 0);
1125 }
1126 foreach my $opt (@$delete) {
1127 &$check($opt, 1);
52389a07
DM
1128 }
1129
1130 return 1;
1131}
1132
9622e848 1133sub umount_all {
da629848 1134 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
9622e848
DM
1135
1136 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
d250604f 1137 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848 1138
73058b84
TL
1139 my $res = 1;
1140
d250604f 1141 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
9622e848
DM
1142 my ($ms, $mountpoint) = @_;
1143
1144 my $volid = $mountpoint->{volume};
1145 my $mount = $mountpoint->{mp};
1146
1147 return if !$volid || !$mount;
1148
d18f96b4 1149 my $mount_path = "$rootdir/$mount";
f845a93d 1150 $mount_path =~ s!/+!/!g;
9622e848 1151
228a5a1d
WL
1152 return if !PVE::ProcFSTools::is_mounted($mount_path);
1153
9622e848 1154 eval {
d18f96b4 1155 PVE::Tools::run_command(['umount', '-d', $mount_path]);
9622e848
DM
1156 };
1157 if (my $err = $@) {
1158 if ($noerr) {
73058b84 1159 $res = 0;
9622e848
DM
1160 warn $err;
1161 } else {
1162 die $err;
1163 }
1164 }
1165 });
73058b84
TL
1166
1167 return $res; # tell caller if (some) umounts failed for the noerr case
9622e848
DM
1168}
1169
1170sub mount_all {
25321b68 1171 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
9622e848
DM
1172
1173 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1adc7e53 1174 File::Path::make_path($rootdir);
9622e848 1175
d250604f 1176 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848
DM
1177 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
1178
4c98d66c
FG
1179 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1180
9622e848 1181 eval {
d250604f 1182 PVE::LXC::Config->foreach_mountpoint($conf, sub {
9622e848
DM
1183 my ($ms, $mountpoint) = @_;
1184
25321b68
FG
1185 $mountpoint->{ro} = 0 if $ignore_ro;
1186
4c98d66c 1187 mountpoint_mount($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
9622e848
DM
1188 });
1189 };
1190 if (my $err = $@) {
e2007ac2 1191 warn "mounting container failed\n";
9622e848 1192 umount_all($vmid, $storage_cfg, $conf, 1);
e2007ac2 1193 die $err;
9622e848
DM
1194 }
1195
da629848 1196 return $rootdir;
9622e848
DM
1197}
1198
1199
b15c75fc 1200sub mountpoint_mount_path {
da629848 1201 my ($mountpoint, $storage_cfg, $snapname) = @_;
b15c75fc 1202
da629848 1203 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
b15c75fc 1204}
cc6b0307 1205
21f292ff
WB
1206sub query_loopdev {
1207 my ($path) = @_;
1208 my $found;
1209 my $parser = sub {
1210 my $line = shift;
1211 if ($line =~ m@^(/dev/loop\d+):@) {
1212 $found = $1;
1213 }
1214 };
1215 my $cmd = ['losetup', '--associated', $path];
1216 PVE::Tools::run_command($cmd, outfunc => $parser);
1217 return $found;
1218}
1219
50df544c
WB
1220# Run a function with a file attached to a loop device.
1221# The loop device is always detached afterwards (or set to autoclear).
1222# Returns the loop device.
1223sub run_with_loopdev {
fd8cab92 1224 my ($func, $file, $readonly) = @_;
54d11e5c
WB
1225 my $device = query_loopdev($file);
1226 # Try to reuse an existing device
1227 if ($device) {
1228 # We assume that whoever setup the loop device is responsible for
1229 # detaching it.
1230 &$func($device);
1231 return $device;
1232 }
1233
50df544c
WB
1234 my $parser = sub {
1235 my $line = shift;
1236 if ($line =~ m@^(/dev/loop\d+)$@) {
1237 $device = $1;
1238 }
1239 };
fd8cab92
DL
1240 my $losetup_cmd = [
1241 'losetup',
1242 '--show',
1243 '-f',
1244 $file,
1245 ];
1246 push @$losetup_cmd, '-r' if $readonly;
1247 PVE::Tools::run_command($losetup_cmd, outfunc => $parser);
50df544c
WB
1248 die "failed to setup loop device for $file\n" if !$device;
1249 eval { &$func($device); };
1250 my $err = $@;
1251 PVE::Tools::run_command(['losetup', '-d', $device]);
1252 die $err if $err;
1253 return $device;
1254}
1255
ab3722b3
WB
1256# In scalar mode: returns a file handle to the deepest directory node.
1257# In list context: returns a list of:
1258# * the deepest directory node
1259# * the 2nd deepest directory (parent of the above)
1260# * directory name of the last directory
1261# So that the path $2/$3 should lead to $1 afterwards.
4c98d66c
FG
1262sub walk_tree_nofollow($$$;$$) {
1263 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
ab3722b3 1264
ab3722b3
WB
1265 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1266 or die "failed to open start directory $start: $!\n";
1267
2c6830d5
WB
1268 return walk_tree_nofollow_fd($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1269}
1270
1271
1272sub walk_tree_nofollow_fd($$$$;$$) {
1273 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1274
1275 # splitdir() returns '' for empty components including the leading /
1276 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1277
1278 my $fd = $start_fd;
1279 my $dir = $start_dirname;
ab3722b3
WB
1280 my $last_component = undef;
1281 my $second = $fd;
1282 foreach my $component (@comps) {
1283 $dir .= "/$component";
1284 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1285
1286 if (!$next) {
1287 # failed, check for symlinks and try to create the path
3eb5f47b 1288 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
ab3722b3
WB
1289 die "cannot open directory $dir: $!\n" if !$mkdir;
1290
1291 # We don't check for errors on mkdirat() here and just try to
1292 # openat() again, since at least one error (EEXIST) is an
1293 # expected possibility if multiple containers start
1294 # simultaneously. If someone else injects a symlink now then
1295 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1296 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1297
1298 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1299 die "failed to create path: $dir: $!\n" if !$next;
4c98d66c
FG
1300
1301 PVE::Tools::fchownat(fileno($next), '', $rootuid, $rootgid, PVE::Tools::AT_EMPTY_PATH)
1302 if defined($rootuid) && defined($rootgid);
ab3722b3
WB
1303 }
1304
2c6830d5 1305 close $second if defined($last_component) && $second != $start_fd;
ab3722b3
WB
1306 $last_component = $component;
1307 $second = $fd;
1308 $fd = $next;
1309 }
1310
1311 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
2c6830d5 1312 close $second if defined($last_component) && $second != $start_fd;
ab3722b3
WB
1313 return $fd;
1314}
1315
619f27b4
WB
1316# To guard against symlink attack races against other currently running
1317# containers with shared recursive bind mount hierarchies we prepare a
1318# directory handle for the directory we're mounting over to verify the
1319# mountpoint afterwards.
1320sub __bindmount_prepare {
1321 my ($hostroot, $dir) = @_;
1322 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1323 return $srcdh;
1324}
ab3722b3 1325
619f27b4
WB
1326# Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1327# ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1328# we intended to bind mount.
1329sub __bindmount_verify {
1330 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
ab3722b3
WB
1331 my $destdh;
1332 if ($parentfd) {
1333 # Open the mount point path coming from the parent directory since the
1334 # filehandle we would have gotten as first result of walk_tree_nofollow
1335 # earlier is still a handle to the underlying directory instead of the
1336 # mounted path.
619f27b4
WB
1337 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1338 die "failed to open mount point: $!\n" if !$destdh;
1339 if ($ro) {
1340 my $dot = '.';
619f27b4 1341 # no separate function because 99% of the time it's the wrong thing to use.
0389da0d 1342 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
619f27b4
WB
1343 die "failed to mark bind mount read only\n";
1344 }
1345 die "read-only check failed: $!\n" if $! != EROFS;
1346 }
ab3722b3
WB
1347 } else {
1348 # For the rootfs we don't have a parentfd so we open the path directly.
1349 # Note that this means bindmounting any prefix of the host's
1350 # /var/lib/lxc/$vmid path into another container is considered a grave
1351 # security error.
1352 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
619f27b4 1353 die "failed to open mount point: $!\n" if !$destdh;
ab3722b3 1354 }
ab3722b3
WB
1355
1356 my ($srcdev, $srcinode) = stat($srcdh);
1357 my ($dstdev, $dstinode) = stat($destdh);
1358 close $srcdh;
1359 close $destdh;
1360
619f27b4
WB
1361 return ($srcdev == $dstdev && $srcinode == $dstinode);
1362}
1363
1364# Perform the actual bind mounting:
1365sub __bindmount_do {
1366 my ($dir, $dest, $ro, @extra_opts) = @_;
1367 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1368 if ($ro) {
1369 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1370 if (my $err = $@) {
1371 warn "bindmount error\n";
1372 # don't leave writable bind-mounts behind...
1373 PVE::Tools::run_command(['umount', $dest]);
1374 die $err;
1375 }
1376 }
1377}
1378
1379sub bindmount {
1380 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1381
1382 my $srcdh = __bindmount_prepare('/', $dir);
1383
1384 __bindmount_do($dir, $dest, $ro, @extra_opts);
1385
1386 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
ab3722b3
WB
1387 PVE::Tools::run_command(['umount', $dest]);
1388 die "detected mount path change at: $dir\n";
1389 }
c2744c97
WB
1390}
1391
619f27b4
WB
1392# Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1393# from $rootdir and $mount and walk the path from $rootdir to the final
1394# directory to check for symlinks.
1395sub __mount_prepare_rootdir {
4c98d66c 1396 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
619f27b4
WB
1397 $rootdir =~ s!/+!/!g;
1398 $rootdir =~ s!/+$!!;
1399 my $mount_path = "$rootdir/$mount";
4c98d66c 1400 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1, $rootuid, $rootgid);
619f27b4
WB
1401 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1402}
1403
b15c75fc 1404# use $rootdir = undef to just return the corresponding mount path
cc6b0307 1405sub mountpoint_mount {
4c98d66c 1406 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
cc6b0307
AD
1407
1408 my $volid = $mountpoint->{volume};
1409 my $mount = $mountpoint->{mp};
7c921c80 1410 my $type = $mountpoint->{type};
50df544c
WB
1411 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1412 my $mounted_dev;
b15c75fc 1413
cc6b0307
AD
1414 return if !$volid || !$mount;
1415
ab3722b3
WB
1416 $mount =~ s!/+!/!g;
1417
b15c75fc 1418 my $mount_path;
ab3722b3 1419 my ($mpfd, $parentfd, $last_dir);
b15c75fc
DM
1420
1421 if (defined($rootdir)) {
619f27b4 1422 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
4c98d66c 1423 __mount_prepare_rootdir($rootdir, $mount, $rootuid, $rootgid);
116ce06f 1424 }
b15c75fc
DM
1425
1426 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
cc6b0307 1427
b15c75fc 1428 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
cc6b0307 1429
2bf24eb3 1430 my $optlist = [];
e80cb0cd
TL
1431
1432 if (my $mountopts = $mountpoint->{mountoptions}) {
1433 my @opts = split(/;/, $mountpoint->{mountoptions});
1434 push @$optlist, grep { PVE::LXC::Config::is_valid_mount_option($_) } @opts;
2bf24eb3
OB
1435 }
1436
719129ea
WB
1437 my $acl = $mountpoint->{acl};
1438 if (defined($acl)) {
2bf24eb3 1439 push @$optlist, ($acl ? 'acl' : 'noacl');
471dd315 1440 }
2bf24eb3
OB
1441
1442 my $optstring = join(',', @$optlist);
c2744c97 1443 my $readonly = $mountpoint->{ro};
471dd315 1444
9de0505c
WL
1445 my @extra_opts;
1446 @extra_opts = ('-o', $optstring) if $optstring;
471dd315 1447
b15c75fc
DM
1448 if ($storage) {
1449
1450 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
7c138f58 1451
841fba68 1452 my $path = PVE::Storage::map_volume($storage_cfg, $volid, $snapname);
7c138f58 1453
841fba68 1454 $path = PVE::Storage::path($storage_cfg, $volid, $snapname) if !defined($path);
b15c75fc
DM
1455
1456 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1457 PVE::Storage::parse_volname($storage_cfg, $volid);
1458
c87b9dd8
DM
1459 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1460
b15c75fc 1461 if ($format eq 'subvol') {
30de33be
DM
1462 if ($mount_path) {
1463 if ($snapname) {
e84f7f5d
DM
1464 if ($scfg->{type} eq 'zfspool') {
1465 my $path_arg = $path;
1466 $path_arg =~ s!^/+!!;
471dd315 1467 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
e84f7f5d 1468 } else {
30de33be
DM
1469 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1470 }
e84f7f5d 1471 } else {
719129ea
WB
1472 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1473 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1474 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1475 $name .= "\@$snapname" if defined($snapname);
1476 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1477 }
ab3722b3 1478 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
50df544c 1479 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
30de33be 1480 }
b15c75fc 1481 }
5f6280cf 1482 return wantarray ? ($path, 0, undef) : $path;
c87b9dd8 1483 } elsif ($format eq 'raw' || $format eq 'iso') {
ada088e6
WB
1484 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1485 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1486 # Our autodev hook expects the /dev/dm-* device currently
1487 # and will create the /dev/mapper symlink accordingly
e439a713
WB
1488 $path = Cwd::realpath($path);
1489 die "failed to get device path\n" if !$path;
1490 ($path) = ($path =~ /^(.*)$/s); #untaint
50df544c
WB
1491 my $domount = sub {
1492 my ($path) = @_;
1493 if ($mount_path) {
1494 if ($format eq 'iso') {
1495 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1496 } elsif ($isBase || defined($snapname)) {
1497 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1498 } else {
1499 if ($quota) {
1500 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1501 }
c2744c97 1502 push @extra_opts, '-o', 'ro' if $readonly;
50df544c
WB
1503 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1504 }
1505 }
1506 };
30de33be 1507 my $use_loopdev = 0;
b15c75fc 1508 if ($scfg->{path}) {
fd8cab92 1509 $mounted_dev = run_with_loopdev($domount, $path, $readonly);
30de33be 1510 $use_loopdev = 1;
2e879877
DM
1511 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1512 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
50df544c
WB
1513 $mounted_dev = $path;
1514 &$domount($path);
b15c75fc
DM
1515 } else {
1516 die "unsupported storage type '$scfg->{type}'\n";
1517 }
50df544c 1518 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
b15c75fc
DM
1519 } else {
1520 die "unsupported image format '$format'\n";
1521 }
7c921c80 1522 } elsif ($type eq 'device') {
c9bc95a1 1523 push @extra_opts, '-o', 'ro' if $readonly;
0d449e38
WB
1524 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1525 # See the NOTE above about devicemapper canonicalization
1526 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
471dd315 1527 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
0d449e38 1528 return wantarray ? ($volid, 0, $devpath) : $volid;
e2007ac2
DM
1529 } elsif ($type eq 'bind') {
1530 die "directory '$volid' does not exist\n" if ! -d $volid;
ab3722b3 1531 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
50df544c
WB
1532 warn "cannot enable quota control for bind mounts\n" if $quota;
1533 return wantarray ? ($volid, 0, undef) : $volid;
b15c75fc
DM
1534 }
1535
1536 die "unsupported storage";
cc6b0307
AD
1537}
1538
6c871c36 1539sub mkfs {
d216e891 1540 my ($dev, $rootuid, $rootgid) = @_;
6c871c36 1541
d216e891
WB
1542 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1543 '-E', "root_owner=$rootuid:$rootgid",
1544 $dev]);
6c871c36
DM
1545}
1546
1547sub format_disk {
d216e891 1548 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
6c871c36
DM
1549
1550 if ($volid =~ m!^/dev/.+!) {
1551 mkfs($volid);
1552 return;
1553 }
1554
1555 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1556
1557 die "cannot format volume '$volid' with no storage\n" if !$storage;
1558
08ca136d
DM
1559 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1560
841fba68
DM
1561 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
1562
1563 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
6c871c36
DM
1564
1565 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1566 PVE::Storage::parse_volname($storage_cfg, $volid);
1567
1568 die "cannot format volume '$volid' (format == $format)\n"
1569 if $format ne 'raw';
1570
d216e891 1571 mkfs($path, $rootuid, $rootgid);
6c871c36
DM
1572}
1573
1574sub destroy_disks {
1575 my ($storecfg, $vollist) = @_;
1576
1577 foreach my $volid (@$vollist) {
1578 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1579 warn $@ if $@;
1580 }
1581}
1582
c9cf8008
WB
1583sub alloc_disk {
1584 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1585
1586 my $needs_chown = 0;
1587 my $volid;
1588
1589 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1590 # fixme: use better naming ct-$vmid-disk-X.raw?
1591
1592 eval {
1593 my $do_format = 0;
be6c3dfa 1594 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs' || $scfg->{type} eq 'cifs' ) {
c9cf8008
WB
1595 if ($size_kb > 0) {
1596 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1597 undef, $size_kb);
1598 $do_format = 1;
1599 } else {
1600 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1601 undef, 0);
1602 $needs_chown = 1;
1603 }
1604 } elsif ($scfg->{type} eq 'zfspool') {
1605
1606 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1607 undef, $size_kb);
1608 $needs_chown = 1;
1609 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1610
1611 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1612 $do_format = 1;
1613
1614 } elsif ($scfg->{type} eq 'rbd') {
1615
c9cf8008
WB
1616 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1617 $do_format = 1;
1618 } else {
1619 die "unable to create containers on storage type '$scfg->{type}'\n";
1620 }
1621 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1622 };
1623 if (my $err = $@) {
1624 # in case formatting got interrupted:
1625 if (defined($volid)) {
1626 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1627 warn $@ if $@;
1628 }
1629 die $err;
1630 }
1631
1632 return ($volid, $needs_chown);
1633}
1634
2aee38e5 1635our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
6c871c36 1636sub create_disks {
32e15a2b 1637 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
6c871c36
DM
1638
1639 my $vollist = [];
1640
1641 eval {
d216e891
WB
1642 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1643 my $chown_vollist = [];
1644
d250604f 1645 PVE::LXC::Config->foreach_mountpoint($settings, sub {
6c871c36
DM
1646 my ($ms, $mountpoint) = @_;
1647
1648 my $volid = $mountpoint->{volume};
1649 my $mp = $mountpoint->{mp};
1650
1651 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1652
2aee38e5 1653 if ($storage && ($volid =~ $NEW_DISK_RE)) {
8ed5ff9d 1654 my ($storeid, $size_gb) = ($1, $2);
6c871c36 1655
8ed5ff9d 1656 my $size_kb = int(${size_gb}*1024) * 1024;
6c871c36 1657
c9cf8008
WB
1658 my $needs_chown = 0;
1659 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1660 push @$chown_vollist, $volid if $needs_chown;
6c871c36 1661 push @$vollist, $volid;
71c780b9
WB
1662 $mountpoint->{volume} = $volid;
1663 $mountpoint->{size} = $size_kb * 1024;
32e15a2b
OB
1664 if ($pending) {
1665 $conf->{pending}->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1666 } else {
1667 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1668 }
6c871c36 1669 } else {
32e15a2b
OB
1670 # use specified/existing volid/dir/device
1671 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36
DM
1672 }
1673 });
d216e891
WB
1674
1675 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1676 foreach my $volid (@$chown_vollist) {
1677 my $path = PVE::Storage::path($storecfg, $volid, undef);
1678 chown($rootuid, $rootgid, $path);
1679 }
1680 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
6c871c36
DM
1681 };
1682 # free allocated images on error
1683 if (my $err = $@) {
1684 destroy_disks($storecfg, $vollist);
32e15a2b 1685 die $err;
6c871c36
DM
1686 }
1687 return $vollist;
1688}
1689
6827e44d
AA
1690sub update_disksize {
1691 my ($vmid, $conf, $all_volumes) = @_;
1692
1693 my $changes;
1694 my $prefix = "CT $vmid:";
1695
1696 my $update_mp = sub {
1697 my ($key, $mp, @param) = @_;
1698 my $size = $all_volumes->{$mp->{volume}}->{size} // 0;
1699
1700 if (!defined($mp->{size}) || $size != $mp->{size}) {
1701 $changes = 1;
1702 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1703 $mp->{size} = $size;
1704 my $nomp = 1 if ($key eq 'rootfs');
1705 $conf->{$key} = PVE::LXC::Config->print_ct_mountpoint($mp, $nomp);
1706 }
1707 };
1708
1709 PVE::LXC::Config->foreach_mountpoint($conf, $update_mp);
1710
1711 return $changes;
1712}
1713
1714sub update_unused {
1715 my ($vmid, $conf, $all_volumes) = @_;
1716
1717 my $changes;
1718 my $prefix = "CT $vmid:";
1719
1720 # Note: it is allowed to define multiple storage entries with the same path
1721 # (alias), so we need to check both 'volid' and real 'path' (two different
1722 # volid can point to the same path).
1723
1724 # used and unused disks
1725 my $refpath = {};
1726 my $orphans = {};
1727
1728 foreach my $opt (keys %$conf) {
1729 next if ($opt !~ m/^unused\d+$/);
1730 my $vol = $all_volumes->{$conf->{$opt}};
1731 $refpath->{$vol->{path}} = $vol->{volid};
1732 }
1733
1734 foreach my $key (keys %$all_volumes) {
1735 my $vol = $all_volumes->{$key};
1736 my $in_use = PVE::LXC::Config->is_volume_in_use($conf, $vol->{volid});
1737 my $path = $vol->{path};
1738
1739 if ($in_use) {
1740 $refpath->{$path} = $key;
1741 delete $orphans->{$path};
1742 } else {
1743 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
1744 $orphans->{$path} = $key;
1745 }
1746 }
1747 }
1748
1749 for my $key (keys %$orphans) {
1750 my $disk = $orphans->{$key};
1751 my $unused = PVE::LXC::Config->add_unused_volume($conf, $disk);
1752
1753 if ($unused) {
1754 $changes = 1;
1755 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
1756 }
1757 }
1758
1759 return $changes;
1760}
1761
1762sub scan_volids {
1763 my ($cfg, $vmid) = @_;
1764
1765 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid);
1766
1767 my $all_volumes = {};
1768 foreach my $storeid (keys %$info) {
1769 foreach my $item (@{$info->{$storeid}}) {
1770 my $volid = $item->{volid};
1771 next if !($volid && $item->{size});
1772 $item->{path} = PVE::Storage::path($cfg, $volid);
1773 $all_volumes->{$volid} = $item;
1774 }
1775 }
1776
1777 return $all_volumes;
1778}
1779
1780sub rescan {
1781 my ($vmid, $nolock, $dryrun) = @_;
1782
1783 my $cfg = PVE::Storage::config();
1784
1785 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
1786 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
1787 foreach my $stor (keys %{$cfg->{ids}}) {
1788 delete($cfg->{ids}->{$stor}) if !$cfg->{ids}->{$stor}->{content}->{rootdir};
1789 }
1790
1791 print "rescan volumes...\n";
1792 my $all_volumes = scan_volids($cfg, $vmid);
1793
1794 my $updatefn = sub {
1795 my ($vmid) = @_;
1796
1797 my $changes;
1798 my $conf = PVE::LXC::Config->load_config($vmid);
1799
1800 PVE::LXC::Config->check_lock($conf);
1801
1802 my $vm_volids = {};
1803 foreach my $volid (keys %$all_volumes) {
1804 my $info = $all_volumes->{$volid};
1805 $vm_volids->{$volid} = $info if $info->{vmid} == $vmid;
1806 }
1807
1808 my $upu = update_unused($vmid, $conf, $vm_volids);
1809 my $upd = update_disksize($vmid, $conf, $vm_volids);
1810 $changes = $upu || $upd;
1811
1812 PVE::LXC::Config->write_config($vmid, $conf) if $changes && !$dryrun;
1813 };
1814
1815 if (defined($vmid)) {
1816 if ($nolock) {
1817 &$updatefn($vmid);
1818 } else {
1819 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
1820 }
1821 } else {
1822 my $vmlist = config_list();
1823 foreach my $vmid (keys %$vmlist) {
1824 if ($nolock) {
1825 &$updatefn($vmid);
1826 } else {
1827 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
1828 }
1829 }
1830 }
1831}
1832
1833
68e8f3c5
DM
1834# bash completion helper
1835
1836sub complete_os_templates {
1837 my ($cmdname, $pname, $cvalue) = @_;
1838
1839 my $cfg = PVE::Storage::config();
1840
9e9bc3a6 1841 my $storeid;
68e8f3c5
DM
1842
1843 if ($cvalue =~ m/^([^:]+):/) {
1844 $storeid = $1;
1845 }
1846
1847 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1848 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1849
1850 my $res = [];
1851 foreach my $id (keys %$data) {
1852 foreach my $item (@{$data->{$id}}) {
1853 push @$res, $item->{volid} if defined($item->{volid});
1854 }
1855 }
1856
1857 return $res;
1858}
1859
68e8f3c5
DM
1860my $complete_ctid_full = sub {
1861 my ($running) = @_;
1862
1863 my $idlist = vmstatus();
1864
1865 my $active_hash = list_active_containers();
1866
1867 my $res = [];
1868
1869 foreach my $id (keys %$idlist) {
1870 my $d = $idlist->{$id};
1871 if (defined($running)) {
1872 next if $d->{template};
1873 next if $running && !$active_hash->{$id};
1874 next if !$running && $active_hash->{$id};
1875 }
1876 push @$res, $id;
1877
1878 }
1879 return $res;
1880};
1881
1882sub complete_ctid {
1883 return &$complete_ctid_full();
1884}
1885
1886sub complete_ctid_stopped {
1887 return &$complete_ctid_full(0);
1888}
1889
1890sub complete_ctid_running {
1891 return &$complete_ctid_full(1);
1892}
1893
c6a605f9
WB
1894sub parse_id_maps {
1895 my ($conf) = @_;
1896
1897 my $id_map = [];
1898 my $rootuid = 0;
1899 my $rootgid = 0;
1900
1901 my $lxc = $conf->{lxc};
1902 foreach my $entry (@$lxc) {
1903 my ($key, $value) = @$entry;
108c6cab
WB
1904 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1905 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
c6a605f9
WB
1906 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1907 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1908 push @$id_map, [$type, $ct, $host, $length];
1909 if ($ct == 0) {
1910 $rootuid = $host if $type eq 'u';
1911 $rootgid = $host if $type eq 'g';
1912 }
1913 } else {
108c6cab 1914 die "failed to parse idmap: $value\n";
c6a605f9
WB
1915 }
1916 }
1917
1918 if (!@$id_map && $conf->{unprivileged}) {
1919 # Should we read them from /etc/subuid?
1920 $id_map = [ ['u', '0', '100000', '65536'],
1921 ['g', '0', '100000', '65536'] ];
1922 $rootuid = $rootgid = 100000;
1923 }
1924
1925 return ($id_map, $rootuid, $rootgid);
1926}
1927
01dce99b
WB
1928sub userns_command {
1929 my ($id_map) = @_;
1930 if (@$id_map) {
1931 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1932 }
1933 return [];
1934}
1935
6725e93c
AA
1936sub vm_start {
1937 my ($vmid, $conf, $skiplock) = @_;
1938
60b3c5e4
OB
1939 # apply pending changes while starting
1940 if (scalar(keys %{$conf->{pending}})) {
1941 my $storecfg = PVE::Storage::config();
1942 PVE::LXC::Config->vmconfig_apply_pending($vmid, $conf, $storecfg);
1943 $conf = PVE::LXC::Config->load_config($vmid); # update/reload
1944 }
1945
6725e93c
AA
1946 update_lxc_config($vmid, $conf);
1947
2e64f057
AA
1948 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1949
1950 if ($skiplock) {
1951 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1952 close($fh);
1953 }
6725e93c
AA
1954
1955 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1956
1a416433 1957 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
2e64f057
AA
1958 eval { PVE::Tools::run_command($cmd); };
1959 if (my $err = $@) {
1960 unlink $skiplock_flag_fn;
1322f50d 1961 die $err;
2e64f057 1962 }
1a416433 1963 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
6725e93c
AA
1964
1965 return;
1966}
1967
b1bad293
WB
1968# Helper to stop a container completely and make sure it has stopped completely.
1969# This is necessary because we want the post-stop hook to have completed its
1970# unmount-all step, but post-stop happens after lxc puts the container into the
1971# STOPPED state.
e0e29818
TL
1972# $kill - if true it will always do an immediate hard-stop
1973# $shutdown_timeout - the timeout to wait for a gracefull shutdown
1974# $kill_after_timeout - if true, send a hardstop if shutdown timed out
b1bad293 1975sub vm_stop {
e0e29818 1976 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
b1bad293
WB
1977
1978 # Open the container's command socket.
1979 my $path = "\0/var/lib/lxc/$vmid/command";
1980 my $sock = IO::Socket::UNIX->new(
1981 Type => SOCK_STREAM(),
1982 Peer => $path,
1983 );
1984 if (!$sock) {
1985 return if $! == ECONNREFUSED; # The container is not running
1986 die "failed to open container ${vmid}'s command socket: $!\n";
1987 }
1988
1a416433
DC
1989 my $conf = PVE::LXC::Config->load_config($vmid);
1990 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
1991
b1bad293
WB
1992 # Stop the container:
1993
1994 my $cmd = ['lxc-stop', '-n', $vmid];
1995
1996 if ($kill) {
1997 push @$cmd, '--kill'; # doesn't allow timeouts
e0e29818
TL
1998 } else {
1999 # lxc-stop uses a default timeout
2000 push @$cmd, '--nokill' if !$kill_after_timeout;
2001
2002 if (defined($shutdown_timeout)) {
2003 push @$cmd, '--timeout', $shutdown_timeout;
2004 # Give run_command 5 extra seconds
2005 $shutdown_timeout += 5;
2006 }
b1bad293
WB
2007 }
2008
2009 eval { PVE::Tools::run_command($cmd, timeout => $shutdown_timeout) };
2010 if (my $err = $@) {
2011 warn $@ if $@;
2012 }
2013
8d41edef 2014 my $result = <$sock>;
b1bad293
WB
2015
2016 return if !defined $result; # monitor is gone and the ct has stopped.
2017 die "container did not stop\n";
2018}
846a66b0 2019
00501642
WB
2020sub run_unshared {
2021 my ($code) = @_;
2022
2023 return PVE::Tools::run_fork(sub {
2024 # Unshare the mount namespace
2025 die "failed to unshare mount namespace: $!\n"
2026 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
2027 PVE::Tools::run_command(['mount', '--make-rslave', '/']);
2028 return $code->();
2029 });
2030}
2031
2032my $copy_volume = sub {
4c98d66c 2033 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
00501642 2034
fd8cab92 2035 my $src_mp = { volume => $src_volid, mp => '/', ro => 1 };
00501642
WB
2036 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
2037
fd8cab92 2038 my $dst_mp = { volume => $dst_volid, mp => '/', ro => 0 };
00501642
WB
2039 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
2040
2041 my @mounted;
2042 eval {
2043 # mount and copy
2044 mkdir $src;
4c98d66c 2045 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
00501642
WB
2046 push @mounted, $src;
2047 mkdir $dest;
4c98d66c 2048 mountpoint_mount($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
00501642
WB
2049 push @mounted, $dest;
2050
08540353
SI
2051 $bwlimit //= 0;
2052
00501642
WB
2053 PVE::Tools::run_command(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2054 '-aH', '--whole-file', '--sparse', '--one-file-system',
08540353 2055 "--bwlimit=$bwlimit", "$src/", $dest]);
00501642
WB
2056 };
2057 my $err = $@;
75c2677f
DJ
2058
2059 # Wait for rsync's children to release dest so that
2060 # consequent file operations (umount, remove) are possible
2061 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2062
00501642 2063 foreach my $mount (reverse @mounted) {
75c2677f 2064 eval { PVE::Tools::run_command(['/bin/umount', $mount], errfunc => sub{})};
00501642
WB
2065 warn "Can't umount $mount\n" if $@;
2066 }
2067
2068 # If this fails they're used as mount points in a concurrent operation
2069 # (which should not happen but there's also no real need to get rid of them).
2070 rmdir $dest;
2071 rmdir $src;
2072
2073 die $err if $err;
2074};
2075
2076# Should not be called after unsharing the mount namespace!
2077sub copy_volume {
08540353 2078 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
00501642
WB
2079
2080 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
2081 File::Path::make_path("/var/lib/lxc/$vmid");
2082 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2083 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2084
2085 # get id's for unprivileged container
2086 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
2087
2088 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2089 # are visible in this namespace, otherwise the host only sees the empty
2090 # (not-mounted) directory.
2091 my $new_volid;
2092 eval {
5154e3e9
WB
2093 # Make sure $mp contains a correct size.
2094 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
00501642
WB
2095 my $needs_chown;
2096 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
2097 if ($needs_chown) {
2098 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
2099 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
2100 chown($rootuid, $rootgid, $path);
2101 }
2102
2103 run_unshared(sub {
4c98d66c 2104 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
00501642
WB
2105 });
2106 };
2107 if (my $err = $@) {
2108 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
2109 if defined($new_volid);
2110 die $err;
2111 }
2112
2113 return $new_volid;
2114}
2115
f76a2828 21161;