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