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