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