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