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