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