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