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