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