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