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