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