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