7 use Errno
qw(ELOOP ENOTDIR EROFS ECONNREFUSED EEXIST);
8 use Fcntl
qw(O_RDONLY O_WRONLY O_NOFOLLOW O_DIRECTORY);
11 use IO
::Poll
qw(POLLIN POLLHUP);
15 use Time
::HiRes qw
(gettimeofday
);
17 use PVE
::AccessControl
;
20 use PVE
::Exception
qw(raise_perm_exc);
21 use PVE
::GuestHelpers
qw(check_vnet_access safe_string_ne safe_num_ne safe_boolean_ne);
23 use PVE
::JSONSchema
qw(get_standard_option);
26 use PVE
::RESTEnvironment
;
39 use PVE
::Syscall
qw(:fsmount);
43 use PVE
::LXC
::Monitor
;
48 require PVE
::Network
::SDN
::Zones
;
52 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
54 my $nodename = PVE
::INotify
::nodename
();
56 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
58 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
61 my $vmlist = PVE
::Cluster
::get_vmlist
();
63 return $res if !$vmlist || !$vmlist->{ids
};
64 my $ids = $vmlist->{ids
};
66 foreach my $vmid (keys %$ids) {
67 next if !$vmid; # skip CT0
68 my $d = $ids->{$vmid};
69 next if !$d->{node
} || $d->{node
} ne $nodename;
70 next if !$d->{type
} || $d->{type
} ne 'lxc';
71 $res->{$vmid} = { type
=> 'lxc', vmid
=> $vmid };
76 # container status helpers
78 sub list_active_containers
{
80 my $filename = "/proc/net/unix";
82 # similar test is used by lcxcontainers.c: list_active_containers
85 my $fh = IO
::File-
>new ($filename, "r");
88 while (defined(my $line = <$fh>)) {
89 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
91 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
102 # warning: this is slow
106 my $active_hash = list_active_containers
();
108 return 1 if defined($active_hash->{$vmid});
113 sub get_container_disk_usage
{
114 my ($vmid, $pid) = @_;
116 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
119 my $last_proc_vmid_stat;
121 our $vmstatus_return_properties = {
122 vmid
=> get_standard_option
('pve-vmid'),
124 description
=> "LXC Container status.",
126 enum
=> ['stopped', 'running'],
129 description
=> "Maximum memory in bytes.",
135 description
=> "Maximum SWAP memory in bytes.",
141 description
=> "Root disk size in bytes.",
147 description
=> "Container name.",
152 description
=> "Uptime.",
155 renderer
=> 'duration',
158 description
=> "Maximum usable CPUs.",
163 description
=> "The current config lock, if any.",
168 description
=> "The current configured tags, if any.",
177 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc', vmid
=> int($opt_vmid) }} : config_list
();
179 my $active_hash = list_active_containers
();
181 my $cpucount = $cpuinfo->{cpus
} || 1;
183 my $cdtime = gettimeofday
;
185 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
186 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
188 my $unprivileged = {};
190 foreach my $vmid (keys %$list) {
191 my $d = $list->{$vmid};
193 eval { $d->{pid
} = int(find_lxc_pid
($vmid)) if defined($active_hash->{$vmid}); };
194 warn $@ if $@; # ignore errors (consider them stopped)
196 $d->{status
} = $active_hash->{$vmid} ?
'running' : 'stopped';
198 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
199 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
201 $unprivileged->{$vmid} = $conf->{unprivileged
};
203 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
204 $d->{name
} =~ s/[\s]//g;
206 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
207 $d->{cpus
} = $cpucount if !$d->{cpus
};
209 $d->{tags
} = $conf->{tags
} if defined($conf->{tags
});
212 my $res = get_container_disk_usage
($vmid, $d->{pid
});
213 $d->{disk
} = int($res->{used
});
214 $d->{maxdisk
} = int($res->{total
});
217 # use 4GB by default ??
218 if (my $rootfs = $conf->{rootfs
}) {
219 my $rootinfo = PVE
::LXC
::Config-
>parse_volume('rootfs', $rootfs);
220 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
222 $d->{maxdisk
} = 4*1024*1024*1024;
228 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
229 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
240 $d->{template
} = 1 if PVE
::LXC
::Config-
>is_template($conf);
241 $d->{lock} = $conf->{lock} if $conf->{lock};
244 foreach my $vmid (keys %$list) {
245 my $d = $list->{$vmid};
248 next if !$pid; # skip stopped CTs
250 my $proc_pid_stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
251 $d->{uptime
} = int(($uptime - $proc_pid_stat->{starttime
}) / $clock_ticks); # the method lxcfs uses
253 my $unpriv = $unprivileged->{$vmid};
255 my $cgroups = PVE
::LXC
::CGroup-
>new($vmid);
257 if (defined(my $mem = $cgroups->get_memory_stat())) {
258 $d->{mem
} = int($mem->{mem
});
259 $d->{swap
} = int($mem->{swap
});
265 if (defined(my $blkio = $cgroups->get_io_stats())) {
266 $d->{diskread
} = int($blkio->{diskread
});
267 $d->{diskwrite
} = int($blkio->{diskwrite
});
273 if (defined(my $cpu = $cgroups->get_cpu_stat())) {
274 # Total time (in milliseconds) used up by the cpu.
275 my $used_ms = $cpu->{utime} + $cpu->{stime
};
277 my $old = $last_proc_vmid_stat->{$vmid};
279 $last_proc_vmid_stat->{$vmid} = {
287 my $delta_ms = ($cdtime - $old->{time}) * $cpucount * 1000.0;
288 if ($delta_ms > 1000.0) {
289 my $delta_used_ms = $used_ms - $old->{used
};
290 $d->{cpu
} = (($delta_used_ms / $delta_ms) * $cpucount) / $d->{cpus
};
291 $last_proc_vmid_stat->{$vmid} = {
297 $d->{cpu
} = $old->{cpu
};
304 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
306 foreach my $dev (keys %$netdev) {
307 next if $dev !~ m/^veth([1-9]\d*)i/;
309 my $d = $list->{$vmid};
313 $d->{netout
} += $netdev->{$dev}->{receive
};
314 $d->{netin
} += $netdev->{$dev}->{transmit
};
321 sub find_lxc_console_pids
{
325 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
328 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
331 my @args = split(/\0/, $cmdline);
333 # search for lxc-console -n <vmid>
334 return if scalar(@args) != 3;
335 return if $args[1] ne '-n';
336 return if $args[2] !~ m/^\d+$/;
337 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
341 push @{$res->{$vmid}}, $pid;
353 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
355 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
357 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
364 sysopen(my $fd, "/proc/$pid", O_RDONLY
| O_DIRECTORY
)
365 or die "failed to open /proc/$pid pid fd\n";
372 # Find the pid and open:
373 my $pid = find_lxc_pid
($vmid);
374 my $fd = open_pid_fd
($pid);
377 my $pid2 = find_lxc_pid
($vmid);
379 return () if $pid != $pid2;
386 # Find the parent pid via proc and open it:
387 my $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
388 my $ppid = $stat->{ppid
} // die "failed to get parent pid\n";
390 my $fd = open_pid_fd
($ppid);
393 $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
394 my $ppid2 = $stat->{ppid
} // die "failed to get parent pid for verification\n";
396 return () if $ppid != $ppid2;
400 # Note: we cannot use Net:IP, because that only allows strict
402 sub parse_ipv4_cidr
{
403 my ($cidr, $noerr) = @_;
405 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
406 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
409 return undef if $noerr;
411 die "unable to parse ipv4 address/mask\n";
414 # With seccomp trap to userspace we now have the ability to optionally forward
415 # certain syscalls to the "host" to handle (via our pve-lxc-syscalld daemon).
417 # This means that there are cases where we need to create an extra seccomp
418 # profile for the container to load.
420 # This returns a configuration snippet added to the raw lxc config.
421 sub make_seccomp_config
{
422 my ($conf, $vmid, $conf_dir, $unprivileged, $features) = @_;
423 # User-configured profile has precedence, note that the user's entry would
424 # be written 'after' this line anyway...
425 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.seccomp.profile')) {
426 # Warn the user if this conflicts with a feature:
427 my $warn = join(', ', grep { $features->{$_} } qw(keyctl mknod));
428 warn "explicitly configured lxc.seccomp.profile overrides the following settings: $warn\n"
429 if length($warn) > 0;
433 # Privileged containers keep using the default (which is already part of
434 # the files included via lxc.include, so we don't need to write it out,
435 # that way it stays admin-configurable via /usr/share/lxc/config/... as
437 return '' if !$unprivileged;
440 keyctl
=> ['errno 38'],
442 # Disable btrfs ioctrls since they don't work particularly well in user namespaces.
443 # Particularly, without the mount option to enable rmdir removing snapshots, user
444 # namespaces can create snapshots but neither `show` or `delete` them, which is quite
445 # horrible, so for now, just disable this entirely:
447 # BTRFS_IOCTL_MAGIC 0x94, _IOC type shift is 8,
448 # so `(req & 0xFF00) == 0x9400` is a btrfs ioctl and gets an EPERM
449 ioctl => ['errno 1 [1,0x9400,SCMP_CMP_MASKED_EQ,0xff00]'],
454 # Unprivileged containers will get keyctl() disabled by default as a
455 # workaround for systemd-networkd behavior. But we have an option to
456 # explicitly enable it:
457 if ($features->{keyctl
}) {
458 delete $rules->{keyctl
};
461 # By default, unprivileged containers cannot use `mknod` at all.
462 # Since lxc 3.2, we can use seccomp's trap to userspace feature for this,
463 # but for now this is experimental, so it has to be enabled via a feature
465 # Note that we only handle block and char devices (like lxd), the rest we
466 # leave up to the kernel. We may in the future remove this if seccomp gets
467 # a way to tell the kernel to "continue" a syscall.
468 if ($features->{mknod
}) {
469 my ($ok, $kernel) = PVE
::ProcFSTools
::check_kernel_release
(5, 3);
471 die "'mknod' feature requested, but kernel too old (found $kernel, required >= 5.3)\n";
474 $raw_conf .= "lxc.seccomp.notify.proxy = unix:/run/pve/lxc-syscalld.sock\n";
475 $raw_conf .= "lxc.seccomp.notify.cookie = $vmid\n";
478 # condition: (mode & S_IFMT) == S_IFCHR
479 'notify [1,8192,SCMP_CMP_MASKED_EQ,61440]',
480 # condition: (mode & S_IFMT) == S_IFBLK
481 'notify [1,24576,SCMP_CMP_MASKED_EQ,61440]',
483 $rules->{mknodat
} = [
484 # condition: (mode & S_IFMT) == S_IFCHR
485 'notify [2,8192,SCMP_CMP_MASKED_EQ,61440]',
486 # condition: (mode & S_IFMT) == S_IFBLK
487 'notify [2,24576,SCMP_CMP_MASKED_EQ,61440]',
491 # Now build the custom seccomp rule text...
492 my $extra_rules = join("\n", map {
494 map { "$syscall $_" } $rules->{$syscall}->@*
495 } sort keys %$rules) . "\n";
497 return $raw_conf if $extra_rules eq "\n";
499 # We still have the "most common" config readily available, so don't write
501 if ($raw_conf eq '' && $extra_rules eq "keyctl errno 38\n") {
502 # we have no extra $raw_conf and use the same we had in pve 6.1:
503 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
506 # Write the rule file to the container's config path:
507 my $rule_file = "$conf_dir/rules.seccomp";
508 my $rule_data = file_get_contents
("$LXC_CONFIG_PATH/common.seccomp")
510 file_set_contents
($rule_file, $rule_data);
511 $raw_conf .= "lxc.seccomp.profile = $rule_file\n";
516 # Since lxc-3.0.2 we can have lxc generate a profile for the container
517 # automatically. The default should be equivalent to the old
518 # `lxc-container-default-cgns` profile.
520 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
521 # additional lines into the profile. We can use that to allow mounting specific
523 sub make_apparmor_config
{
524 my ($conf, $unprivileged, $features) = @_;
526 # user-configured profile has precedence, but first we go through our own
527 # code to figure out whether we should warn the user:
529 my $raw = "lxc.apparmor.profile = generated\n";
532 if ($features->{fuse
}) {
533 # For the informational warning:
534 push @profile_uses, 'features:fuse';
537 # There's lxc.apparmor.allow_nesting now, which will add the necessary
538 # apparmor lines, create an apparmor namespace for the container, but also
539 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
540 # lxcfs mounted over them, because that would prevent the container from
541 # mounting new instances of them for nested containers.
542 if ($features->{nesting
}) {
543 push @profile_uses, 'features:nesting';
544 $raw .= "lxc.apparmor.allow_nesting = 1\n"
546 # In the default profile in /etc/apparmor.d we patch this in because
547 # otherwise a container can for example run `chown` on /sys, breaking
548 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
549 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
550 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
551 # Preferably we could use the 'remount' flag but this does not sit well
552 # with apparmor_parser currently:
553 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
556 if (my $mount = $features->{mount
}) {
557 push @profile_uses, 'features:mount';
558 foreach my $fs (PVE
::Tools
::split_list
($mount)) {
559 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
565 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.apparmor.profile')) {
566 if (length(my $used = join(', ', @profile_uses))) {
567 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
575 sub update_lxc_config
{
576 my ($vmid, $conf) = @_;
578 my $dir = "/var/lib/lxc/$vmid";
580 if ($conf->{template
}) {
582 unlink "$dir/config";
587 my ($lxc_major, $lxc_minor) = get_lxc_version
();
591 if ($lxc_major >= 4) {
592 # Explicitly don't use relative directories, which is the default, but
593 # note that we do this mostly because they are only applied for *some*
594 # cgroups. Our pve-container@.service now starts lxc-start with `-F`,
595 # so we also don't need to worry about the new monitor cgroup to
597 $raw .= "lxc.cgroup.relative = 0\n";
599 # To make things easier, let's keep our previous cgroup layout and
600 # simply move the monitor outside:
601 $raw .= "lxc.cgroup.dir.monitor = lxc.monitor/$vmid\n";
602 # cgroup namespace separation for stronger limits:
603 $raw .= "lxc.cgroup.dir.container = lxc/$vmid\n";
604 $raw .= "lxc.cgroup.dir.container.inner = ns\n";
607 die "missing 'arch' - internal error" if !$conf->{arch
};
608 $raw .= "lxc.arch = $conf->{arch}\n";
610 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
611 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
613 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
615 File
::Path
::mkpath
($dir);
617 my $cfgpath = '/usr/share/lxc/config';
618 my $inc = "$cfgpath/$ostype.common.conf";
619 $inc ="$cfgpath/common.conf" if !-f
$inc;
620 $raw .= "lxc.include = $inc\n";
622 $inc = "$cfgpath/$ostype.userns.conf";
623 $inc = "$cfgpath/userns.conf" if !-f
$inc;
624 $raw .= "lxc.include = $inc\n";
627 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
629 $raw .= make_seccomp_config
($conf, $vmid, $dir, $unprivileged, $features);
630 $raw .= make_apparmor_config
($conf, $unprivileged, $features);
631 if ($features->{fuse
}) {
632 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
633 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
636 if ($unprivileged && !$features->{force_rw_sys
}) {
637 # unpriv. CT default to sys:rw, but that doesn't always plays well with
638 # systemd, e.g., systemd-networkd https://systemd.io/CONTAINER_INTERFACE/
639 $raw .= "lxc.mount.auto = sys:mixed\n";
642 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
643 # cannot be exposed to the container with r/w access (cgroup perms).
644 # When this is enabled mounts will still remain in the monitor's namespace
645 # after the container unmounted them and thus will not detach from their
646 # files while the container is running!
647 $raw .= "lxc.monitor.unshare = 1\n";
649 my ($cgv1, $cgv2) = PVE
::CGroup
::get_cgroup_controllers
();
651 # Should we read them from /etc/subuid?
652 if ($unprivileged && !$custom_idmap) {
653 $raw .= "lxc.idmap = u 0 100000 65536\n";
654 $raw .= "lxc.idmap = g 0 100000 65536\n";
657 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
658 $raw .= "lxc.console.path = none\n";
659 if ($cgv1->{devices
}) {
660 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
661 } elsif (defined($cgv2)) {
662 $raw .= "lxc.cgroup2.devices.deny = c 5:1 rwm\n";
666 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
667 $raw .= "lxc.tty.max = $ttycount\n";
669 # some init scripts expect a linux terminal (turnkey).
670 $raw .= "lxc.environment = TERM=linux\n";
672 my $utsname = $conf->{hostname
} || "CT$vmid";
673 $raw .= "lxc.uts.name = $utsname\n";
675 if ($cgv1->{memory
}) {
676 my $memory = $conf->{memory
} || 512;
677 my $swap = $conf->{swap
} // 0;
679 my $lxcmem = int($memory*1024*1024);
680 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
682 my $lxcswap = int(($memory + $swap)*1024*1024);
683 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
684 } elsif ($cgv2->{memory
}) {
685 my $memory = $conf->{memory
} || 512;
686 my $swap = $conf->{swap
} // 0;
688 # cgroup memory usage is limited by the hard 'max' limit (OOM-killer enforced) and the soft
689 # 'high' limit (cgroup processes get throttled and put under heavy reclaim pressure).
690 my ($lxc_mem_max, $lxc_mem_high) = PVE
::LXC
::Config
::calculate_memory_constraints
($memory);
691 $raw .= "lxc.cgroup2.memory.max = $lxc_mem_max\n";
692 $raw .= "lxc.cgroup2.memory.high = $lxc_mem_high\n";
694 my $lxcswap = int($swap*1024*1024);
695 $raw .= "lxc.cgroup2.memory.swap.max = $lxcswap\n";
699 if (my $cpulimit = $conf->{cpulimit
}) {
700 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
701 my $value = int(100000*$cpulimit);
702 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
705 my $shares = PVE
::CGroup
::clamp_cpu_shares
($conf->{cpuunits
});
706 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
707 } elsif ($cgv2->{cpu
}) {
709 if (my $cpulimit = $conf->{cpulimit
}) {
710 my $value = int(100000*$cpulimit);
711 $raw .= "lxc.cgroup2.cpu.max = $value 100000\n";
714 if (defined(my $shares = $conf->{cpuunits
})) {
715 $shares = PVE
::CGroup
::clamp_cpu_shares
($shares);
716 $raw .= "lxc.cgroup2.cpu.weight = $shares\n";
720 die "missing 'rootfs' configuration\n"
721 if !defined($conf->{rootfs
});
723 my $mountpoint = PVE
::LXC
::Config-
>parse_volume('rootfs', $conf->{rootfs
});
725 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
727 foreach my $k (sort keys %$conf) {
728 next if $k !~ m/^net(\d+)$/;
730 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
731 $raw .= "lxc.net.$ind.type = veth\n";
732 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
733 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
734 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
736 my $bridge_mtu = PVE
::Network
::read_bridge_mtu
($d->{bridge
});
737 my $mtu = $d->{mtu
} || $bridge_mtu;
739 # Keep container from starting with invalid mtu configuration
740 die "$k: MTU size '$mtu' is bigger than bridge MTU '$bridge_mtu'\n"
741 if ($mtu > $bridge_mtu);
743 $raw .= "lxc.net.$ind.mtu = $mtu\n";
745 # Starting with lxc 4.0, we do not patch lxc to execute our up-scripts.
746 if ($lxc_major >= 4) {
747 $raw .= "lxc.net.$ind.script.up = /usr/share/lxc/lxcnetaddbr\n";
752 if (my $lxcconf = $conf->{lxc
}) {
753 foreach my $entry (@$lxcconf) {
754 my ($k, $v) = @$entry;
755 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus' || $k eq 'lxc.cgroup2.cpuset.cpus';
761 my ($cpuset_cgroup, $cpuset_version) = eval { PVE
::CGroup
::cpuset_controller_path
() };
762 if (defined($cpuset_cgroup)) {
763 $cpuset = eval { PVE
::CpuSet-
>new_from_path("$cpuset_cgroup/lxc", 1) }
764 || PVE
::CpuSet-
>new_from_path($cpuset_cgroup, 1);
766 my $cores = $conf->{cores
};
767 if (!$had_cpuset && $cores && $cpuset) {
768 my @members = $cpuset->members();
769 while (scalar(@members) > $cores) {
770 my $randidx = int(rand(scalar(@members)));
771 $cpuset->delete($members[$randidx]);
772 splice(@members, $randidx, 1); # keep track of the changes
774 my $ver = $cpuset_version == 1 ?
'' : '2';
775 $raw .= "lxc.cgroup$ver.cpuset.cpus = ".$cpuset->short_string()."\n";
778 File
::Path
::mkpath
("$dir/rootfs");
780 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
783 # verify and cleanup nameserver list (replace \0 with ' ')
784 sub verify_nameserver_list
{
785 my ($nameserver_list) = @_;
788 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
789 PVE
::LXC
::Config
::verify_ip_with_ll_iface
($server);
793 return join(' ', @list);
796 sub verify_searchdomain_list
{
797 my ($searchdomain_list) = @_;
800 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
801 # todo: should we add checks for valid dns domains?
805 return join(' ', @list);
808 sub get_console_command
{
809 my ($vmid, $conf, $escapechar) = @_;
811 # '-1' as $escapechar disables keyboard escape sequence
812 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
814 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
817 if ($cmode eq 'console') {
818 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
819 push @$cmd, '-e', $escapechar if $escapechar;
820 } elsif ($cmode eq 'tty') {
821 push @$cmd, 'lxc-console', '-n', $vmid;
822 push @$cmd, '-e', $escapechar if $escapechar;
823 } elsif ($cmode eq 'shell') {
824 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
826 die "internal error";
832 sub get_primary_ips
{
835 # return data from net0
837 return undef if !defined($conf->{net0
});
838 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
840 my $ipv4 = $net->{ip
};
842 if ($ipv4 =~ /^(dhcp|manual)$/) {
848 my $ipv6 = $net->{ip6
};
850 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
857 return ($ipv4, $ipv6);
860 sub delete_mountpoint_volume
{
861 my ($storage_cfg, $vmid, $volume) = @_;
863 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
865 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
867 if ($vmid == $owner) {
868 PVE
::Storage
::vdisk_free
($storage_cfg, $volume);
870 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
874 sub destroy_lxc_container
{
875 my ($storage_cfg, $vmid, $conf, $replacement_conf, $purge_unreferenced) = @_;
878 my $remove_volume = sub {
879 my ($ms, $mountpoint) = @_;
881 my $volume = $mountpoint->{volume
};
883 return if $volids->{$volume};
884 $volids->{$volume} = 1;
886 delete_mountpoint_volume
($storage_cfg, $vmid, $volume);
888 PVE
::LXC
::Config-
>foreach_volume_full($conf, {include_unused
=> 1}, $remove_volume);
890 PVE
::LXC
::Config-
>foreach_volume_full($conf->{pending
}, {include_unused
=> 1}, $remove_volume);
892 if ($purge_unreferenced) { # also remove unreferenced disk
893 my $vmdisks = PVE
::Storage
::vdisk_list
($storage_cfg, undef, $vmid, undef, 'rootdir');
894 PVE
::Storage
::foreach_volid
($vmdisks, sub {
895 my ($volid, $sid, $volname, $d) = @_;
896 eval { PVE
::Storage
::vdisk_free
($storage_cfg, $volid) };
901 rmdir "/var/lib/lxc/$vmid/rootfs";
902 unlink "/var/lib/lxc/$vmid/config";
903 rmdir "/var/lib/lxc/$vmid";
904 if (defined $replacement_conf) {
905 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
907 PVE
::LXC
::Config-
>destroy_config($vmid);
911 sub vm_stop_cleanup
{
912 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
914 return if $keepActive;
917 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
918 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
920 warn $@ if $@; # avoid errors - just warn
923 sub net_tap_plug
: prototype($$) {
924 my ($iface, $net) = @_;
926 if (defined($net->{link_down
})) {
927 PVE
::Tools
::run_command
(['/sbin/ip', 'link', 'set', 'dev', $iface, 'down']);
928 # Don't add disconnected interfaces to the bridge, otherwise e.g. applying any network
929 # change (e.g. `ifreload -a`) could (re-)activate it unintentionally.
933 my ($bridge, $tag, $firewall, $trunks, $rate, $hwaddr) =
934 $net->@{'bridge', 'tag', 'firewall', 'trunks', 'rate', 'hwaddr'};
937 PVE
::Network
::SDN
::Zones
::tap_plug
($iface, $bridge, $tag, $firewall, $trunks, $rate);
938 PVE
::Network
::SDN
::Zones
::add_bridge_fdb
($iface, $hwaddr, $bridge);
940 PVE
::Network
::tap_plug
($iface, $bridge, $tag, $firewall, $trunks, $rate, { mac
=> $hwaddr });
943 PVE
::Tools
::run_command
(['/sbin/ip', 'link', 'set', 'dev', $iface, 'up']);
947 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
949 if ($newnet->{type
} ne 'veth') {
950 # for when there are physical interfaces
951 die "cannot update interface of type $newnet->{type}";
954 my $veth = "veth${vmid}i${netid}";
955 my $eth = $newnet->{name
};
957 if (my $oldnetcfg = $conf->{$opt}) {
958 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
960 if (safe_string_ne
($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
961 safe_string_ne
($oldnet->{name
}, $newnet->{name
})) {
963 PVE
::Network
::veth_delete
($veth);
966 eval { PVE
::Network
::SDN
::Vnets
::del_ips_from_mac
($oldnet->{bridge
}, $oldnet->{hwaddr
}, $conf->{hostname
}) };
970 delete $conf->{$opt};
971 PVE
::LXC
::Config-
>write_config($vmid, $conf);
973 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
976 if (safe_string_ne
($oldnet->{bridge
}, $newnet->{bridge
}) ||
977 safe_num_ne
($oldnet->{tag
}, $newnet->{tag
}) ||
978 safe_num_ne
($oldnet->{firewall
}, $newnet->{firewall
}) ||
979 safe_boolean_ne
($oldnet->{link_down
}, $newnet->{link_down
})
982 if ($oldnet->{bridge
}) {
984 PVE
::Network
::tap_unplug
($veth);
985 foreach (qw(bridge tag firewall)) {
986 delete $oldnet->{$_};
988 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
989 PVE
::LXC
::Config-
>write_config($vmid, $conf);
992 eval { PVE
::Network
::SDN
::Vnets
::del_ips_from_mac
($oldnet->{bridge
}, $oldnet->{hwaddr
}, $conf->{hostname
}) };
998 PVE
::Network
::SDN
::Vnets
::add_next_free_cidr
($newnet->{bridge
}, $conf->{hostname
}, $newnet->{hwaddr
}, $vmid, undef, 1);
1000 PVE
::LXC
::net_tap_plug
($veth, $newnet);
1002 # This includes the rate:
1003 foreach (qw(bridge tag firewall rate link_down)) {
1004 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
1006 } elsif (safe_string_ne
($oldnet->{rate
}, $newnet->{rate
})) {
1007 # Rate can be applied on its own but any change above needs to
1008 # include the rate in tap_plug since OVS resets everything.
1009 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
1010 $oldnet->{rate
} = $newnet->{rate
}
1012 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
1013 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1016 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
1019 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
1023 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
1025 my $veth = "veth${vmid}i${netid}";
1026 my $vethpeer = $veth . "p";
1027 my $eth = $newnet->{name
};
1030 PVE
::Network
::SDN
::Vnets
::add_next_free_cidr
($newnet->{bridge
}, $conf->{hostname
}, $newnet->{hwaddr
}, $vmid, undef, 1);
1031 PVE
::Network
::SDN
::Vnets
::add_dhcp_mapping
($newnet->{bridge
}, $newnet->{hwaddr
});
1032 PVE
::Network
::SDN
::Zones
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
1034 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
1037 PVE
::LXC
::net_tap_plug
($veth, $newnet);
1039 # attach peer in container
1040 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
1041 PVE
::Tools
::run_command
($cmd);
1043 # link up peer in container
1044 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
1045 PVE
::Tools
::run_command
($cmd);
1047 my $done = { type
=> 'veth' };
1048 foreach (qw(bridge tag firewall hwaddr name link_down)) {
1049 $done->{$_} = $newnet->{$_} if $newnet->{$_};
1051 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
1053 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1056 sub get_interfaces
{
1059 my $pid = eval { find_lxc_pid
($vmid); };
1063 # enters the network namespace of the container and executes 'ip a'
1064 run_command
(['nsenter', '-t', $pid, '--net', '--', 'ip', '--json', 'a'],
1065 outfunc
=> sub { $output .= shift; });
1067 my $config = JSON
::decode_json
($output);
1070 for my $interface ($config->@*) {
1071 my $obj = { name
=> $interface->{ifname
} };
1072 for my $ip ($interface->{addr_info
}->@*) {
1073 $obj->{$ip->{family
}} = $ip->{local} . "/" . $ip->{prefixlen
};
1075 $obj->{hwaddr
} = $interface->{address
};
1082 sub update_ipconfig
{
1083 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
1085 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
1087 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
1091 my $cmdargs = shift;
1092 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
1094 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
1096 my $change_ip_config = sub {
1097 my ($ipversion) = @_;
1099 my $family_opt = "-$ipversion";
1100 my $suffix = $ipversion == 4 ?
'' : $ipversion;
1101 my $gw= "gw$suffix";
1102 my $ip= "ip$suffix";
1104 my $newip = $newnet->{$ip};
1105 my $newgw = $newnet->{$gw};
1106 my $oldip = $optdata->{$ip};
1107 my $oldgw = $optdata->{$gw};
1109 my $change_ip = safe_string_ne
($oldip, $newip);
1110 my $change_gw = safe_string_ne
($oldgw, $newgw);
1112 return if !$change_ip && !$change_gw;
1114 # step 1: add new IP, if this fails we cancel
1115 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
1116 if ($change_ip && $is_real_ip) {
1117 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
1124 # step 2: replace gateway
1125 # If this fails we delete the added IP and cancel.
1126 # If it succeeds we save the config and delete the old IP, ignoring
1127 # errors. The config is then saved.
1128 # Note: 'ip route replace' can add
1132 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
1133 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1135 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1139 # the route was not replaced, the old IP is still available
1140 # rollback (delete new IP) and cancel
1142 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
1143 warn $@ if $@; # no need to die here
1148 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
1149 # if the route was not deleted, the guest might have deleted it manually
1153 if ($oldgw && $oldip && !PVE
::Network
::is_ip_in_cidr
($oldgw, $oldip)) {
1154 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
1155 # warn if the route was deleted manually
1160 # from this point on we save the configuration
1161 # step 3: delete old IP ignoring errors
1162 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
1163 # We need to enable promote_secondaries, otherwise our newly added
1164 # address will be removed along with the old one.
1167 if ($ipversion == 4) {
1168 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
1169 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1170 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1172 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1174 warn $@ if $@; # no need to die here
1176 if ($ipversion == 4) {
1177 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1181 foreach my $property ($ip, $gw) {
1182 if ($newnet->{$property}) {
1183 $optdata->{$property} = $newnet->{$property};
1185 delete $optdata->{$property};
1188 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
1189 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1190 $lxc_setup->setup_network($conf);
1193 &$change_ip_config(4);
1194 &$change_ip_config(6);
1198 my $open_namespace = sub {
1199 my ($vmid, $pid, $kind) = @_;
1200 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1201 or die "failed to open $kind namespace of container $vmid: $!\n";
1205 my $enter_namespace = sub {
1206 my ($vmid, $pid, $kind, $type) = @_;
1207 my $fd = $open_namespace->($vmid, $pid, $kind);
1208 PVE
::Tools
::setns
(fileno($fd), $type)
1209 or die "failed to enter $kind namespace of container $vmid: $!\n";
1213 my $get_container_namespace = sub {
1214 my ($vmid, $pid, $kind) = @_;
1217 if (!defined($pid)) {
1218 # Pin the pid while we're grabbing its stuff from /proc
1219 ($pid, $pidfd) = open_lxc_pid
($vmid)
1220 or die "failed to open pidfd of container $vmid\'s init process\n";
1223 return $open_namespace->($vmid, $pid, $kind);
1226 my $do_syncfs = sub {
1227 my ($vmid, $pid, $socket) = @_;
1229 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
1231 # Tell the parent process to start reading our /proc/mounts
1232 print {$socket} "go\n";
1235 # Receive /proc/self/mounts
1236 my $mountdata = do { local $/ = undef; <$socket> };
1252 # Now sync all mountpoints...
1253 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
1254 foreach my $mp (@$mounts) {
1255 my ($what, $dir, $fs) = @$mp;
1256 next if $nosyncfs{$fs};
1257 eval { PVE
::Tools
::sync_mountpoint
($dir); };
1262 sub sync_container_namespace
{
1264 my $pid = find_lxc_pid
($vmid);
1266 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1267 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
1268 or die "failed to create socketpair: $!\n";
1271 die "fork failed: $!\n" if !defined($child);
1276 &$do_syncfs($vmid, $pid, $cfd);
1286 die "failed to enter container namespace\n" if $go ne "go\n";
1288 open my $mounts, '<', "/proc/$child/mounts"
1289 or die "failed to open container's /proc/mounts: $!\n";
1290 my $mountdata = do { local $/ = undef; <$mounts> };
1292 print {$pfd} $mountdata;
1295 while (waitpid($child, 0) != $child) {}
1296 die "failed to sync container namespace\n" if $? != 0;
1299 sub template_create
{
1300 my ($vmid, $conf) = @_;
1302 my $storecfg = PVE
::Storage
::config
();
1304 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1305 my ($ms, $mountpoint) = @_;
1307 my $volid = $mountpoint->{volume
};
1309 die "Template feature is not available for '$volid'\n"
1310 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1313 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1314 my ($ms, $mountpoint) = @_;
1316 my $volid = $mountpoint->{volume
};
1318 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
1320 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
1321 $mountpoint->{volume
} = $template_volid;
1322 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1325 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1328 sub check_ct_modify_config_perm
{
1329 my ($rpcenv, $authuser, $vmid, $pool, $oldconf, $newconf, $delete, $unprivileged) = @_;
1331 return 1 if $authuser eq 'root@pam';
1332 my $storage_cfg = PVE
::Storage
::config
();
1335 my ($opt, $delete) = @_;
1336 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1337 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1338 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1339 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1341 my $data = PVE
::LXC
::Config-
>parse_volume($opt, $newconf->{$opt});
1342 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
1343 if $data->{type
} ne 'volume';
1344 my $volid = $data->{volume
};
1345 if ($volid =~ $NEW_DISK_RE) {
1347 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
1349 PVE
::Storage
::check_volume_access
(
1358 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1359 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1360 } elsif ($opt =~ m/^net\d+$/) {
1361 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1362 check_bridge_access
($rpcenv, $authuser, $oldconf->{$opt}) if $oldconf->{$opt};
1363 check_bridge_access
($rpcenv, $authuser, $newconf->{$opt}) if $newconf->{$opt};
1364 } elsif ($opt eq 'nameserver' || $opt eq 'searchdomain' || $opt eq 'hostname') {
1365 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1366 } elsif ($opt eq 'features') {
1367 raise_perm_exc
("changing feature flags for privileged container is only allowed for root\@pam")
1370 my $nesting_changed = 0;
1371 my $other_changed = 0;
1373 my $features = PVE
::LXC
::Config-
>parse_features($newconf->{$opt});
1374 if (defined($oldconf) && $oldconf->{$opt}) {
1375 # existing container with features
1376 my $old_features = PVE
::LXC
::Config-
>parse_features($oldconf->{$opt});
1377 for my $feature ((keys %$old_features, keys %$features)) {
1378 my $old = $old_features->{$feature} // '';
1379 my $new = $features->{$feature} // '';
1381 if ($feature eq 'nesting') {
1382 $nesting_changed = 1;
1391 # new container or no features defined
1392 if (scalar(keys %$features) == 1 && $features->{nesting
}) {
1393 $nesting_changed = 1;
1394 } elsif (scalar(keys %$features) > 0) {
1399 my $features = PVE
::LXC
::Config-
>parse_features($oldconf->{$opt});
1400 if (scalar(keys %$features) == 1 && $features->{nesting
}) {
1401 $nesting_changed = 1;
1402 } elsif (scalar(keys %$features) > 0) {
1406 raise_perm_exc
("changing feature flags (except nesting) is only allowed for root\@pam")
1408 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Allocate'])
1409 if $nesting_changed;
1410 } elsif ($opt eq 'hookscript') {
1411 # For now this is restricted to root@pam
1412 raise_perm_exc
("changing the hookscript is only allowed for root\@pam");
1413 } elsif ($opt eq 'tags') {
1414 my $old = $oldconf->{$opt};
1415 my $new = $delete ?
'' : $newconf->{$opt};
1416 PVE
::GuestHelpers
::assert_tag_permissions
($vmid, $old, $new, $rpcenv, $authuser);
1418 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1422 foreach my $opt (keys %$newconf) {
1425 foreach my $opt (@$delete) {
1432 sub check_bridge_access
{
1433 my ($rpcenv, $authuser, $raw) = @_;
1435 return 1 if $authuser eq 'root@pam';
1437 my $net = PVE
::LXC
::Config-
>parse_lxc_network($raw);
1438 my ($bridge, $tag, $trunks) = $net->@{'bridge', 'tag', 'trunks'};
1439 check_vnet_access
($rpcenv, $authuser, $bridge, $tag, $trunks);
1445 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1447 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1448 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1452 PVE
::LXC
::Config-
>foreach_volume_full($conf, {'reverse' => 1}, sub {
1453 my ($ms, $mountpoint) = @_;
1455 my $volid = $mountpoint->{volume
};
1456 my $mount = $mountpoint->{mp
};
1458 return if !$volid || !$mount;
1460 my $mount_path = "$rootdir/$mount";
1461 $mount_path =~ s!/+!/!g;
1463 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1466 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
1478 return $res; # tell caller if (some) umounts failed for the noerr case
1482 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1484 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1485 File
::Path
::make_path
($rootdir);
1487 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1488 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
1490 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1493 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1494 my ($ms, $mountpoint) = @_;
1496 $mountpoint->{ro
} = 0 if $ignore_ro;
1498 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1502 warn "mounting container failed\n";
1503 umount_all
($vmid, $storage_cfg, $conf, 1);
1511 sub mountpoint_mount_path
{
1512 my ($mountpoint, $storage_cfg, $snapname) = @_;
1514 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1522 if ($line =~ m
@^(/dev/loop\d
+):@) {
1526 my $cmd = ['losetup', '--associated', $path];
1527 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1531 # Run a function with a file attached to a loop device.
1532 # The loop device is always detached afterwards (or set to autoclear).
1533 # Returns the loop device.
1534 sub run_with_loopdev
{
1535 my ($func, $file, $readonly) = @_;
1536 my $device = query_loopdev
($file);
1537 # Try to reuse an existing device
1539 # We assume that whoever setup the loop device is responsible for
1547 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1557 push @$losetup_cmd, '-r' if $readonly;
1558 PVE
::Tools
::run_command
($losetup_cmd, outfunc
=> $parser);
1559 die "failed to setup loop device for $file\n" if !$device;
1560 eval { &$func($device); };
1562 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1567 # In scalar mode: returns a file handle to the deepest directory node.
1568 # In list context: returns a list of:
1569 # * the deepest directory node
1570 # * the 2nd deepest directory (parent of the above)
1571 # * directory name of the last directory
1572 # So that the path $2/$3 should lead to $1 afterwards.
1573 sub walk_tree_nofollow
($$$;$$) {
1574 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1576 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1577 or die "failed to open start directory $start: $!\n";
1579 return walk_tree_nofollow_fd
($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1583 sub walk_tree_nofollow_fd
($$$$;$$) {
1584 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1586 # splitdir() returns '' for empty components including the leading /
1587 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1590 my $dir = $start_dirname;
1591 my $last_component = undef;
1593 foreach my $component (@comps) {
1594 $dir .= "/$component";
1595 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1598 # failed, check for symlinks and try to create the path
1599 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1600 die "cannot open directory $dir: $!\n" if !$mkdir;
1602 # We don't check for errors on mkdirat() here and just try to
1603 # openat() again, since at least one error (EEXIST) is an
1604 # expected possibility if multiple containers start
1605 # simultaneously. If someone else injects a symlink now then
1606 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1607 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1609 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1610 die "failed to create path: $dir: $!\n" if !$next;
1612 PVE
::Tools
::fchownat
(fileno($next), '', $rootuid, $rootgid, PVE
::Tools
::AT_EMPTY_PATH
)
1613 if defined($rootuid) && defined($rootgid);
1616 close $second if defined($last_component) && $second != $start_fd;
1617 $last_component = $component;
1622 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1623 close $second if defined($last_component) && $second != $start_fd;
1627 # To guard against symlink attack races against other currently running
1628 # containers with shared recursive bind mount hierarchies we prepare a
1629 # directory handle for the directory we're mounting over to verify the
1630 # mountpoint afterwards.
1631 sub __bindmount_prepare
{
1632 my ($hostroot, $dir) = @_;
1633 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1637 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1638 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1639 # we intended to bind mount.
1640 sub __bindmount_verify
{
1641 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1644 # Open the mount point path coming from the parent directory since the
1645 # filehandle we would have gotten as first result of walk_tree_nofollow
1646 # earlier is still a handle to the underlying directory instead of the
1648 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1649 die "failed to open mount point: $!\n" if !$destdh;
1652 # no separate function because 99% of the time it's the wrong thing to use.
1653 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1654 die "failed to mark bind mount read only\n";
1656 die "read-only check failed: $!\n" if $! != EROFS
;
1659 # For the rootfs we don't have a parentfd so we open the path directly.
1660 # Note that this means bindmounting any prefix of the host's
1661 # /var/lib/lxc/$vmid path into another container is considered a grave
1663 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1664 die "failed to open mount point: $!\n" if !$destdh;
1667 my ($srcdev, $srcinode) = stat($srcdh);
1668 my ($dstdev, $dstinode) = stat($destdh);
1672 return ($srcdev == $dstdev && $srcinode == $dstinode);
1675 # Perform the actual bind mounting:
1676 sub __bindmount_do
{
1677 my ($dir, $dest, $ro, @extra_opts) = @_;
1678 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1680 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1682 warn "bindmount error\n";
1683 # don't leave writable bind-mounts behind...
1684 PVE
::Tools
::run_command
(['umount', $dest]);
1691 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1693 my $srcdh = __bindmount_prepare
('/', $dir);
1695 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1697 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1698 PVE
::Tools
::run_command
(['umount', $dest]);
1699 die "detected mount path change at: $dir\n";
1703 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1704 # from $rootdir and $mount and walk the path from $rootdir to the final
1705 # directory to check for symlinks.
1706 sub __mount_prepare_rootdir
{
1707 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1708 $rootdir =~ s!/+!/!g;
1709 $rootdir =~ s!/+$!!;
1710 my $mount_path = "$rootdir/$mount";
1711 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1, $rootuid, $rootgid);
1712 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1715 # use $rootdir = undef to just return the corresponding mount path
1716 sub mountpoint_mount
{
1717 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1718 return __mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1721 sub mountpoint_stage
{
1722 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1723 my ($path, $loop, $dev) =
1724 __mountpoint_mount
($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1726 if (!defined($path)) {
1727 die "failed to mount subvolume: $!\n";
1730 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1731 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1734 my $fd = PVE
::Tools
::open_tree
(&AT_FDCWD
, $stage_dir, &OPEN_TREE_CLOEXEC
| &OPEN_TREE_CLONE
)
1735 or die "open_tree() on mount point failed: $!\n";
1737 return wantarray ?
($path, $loop, $dev, $fd) : $fd;
1740 sub mountpoint_insert_staged
{
1741 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1743 if (!defined($rootdir_fd)) {
1744 sysopen($rootdir_fd, '.', O_PATH
| O_DIRECTORY
)
1745 or die "failed to open '.': $!\n";
1748 my $dest_fd = walk_tree_nofollow_fd
('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1750 PVE
::Tools
::move_mount
(
1755 &MOVE_MOUNT_F_EMPTY_PATH
| &MOVE_MOUNT_T_EMPTY_PATH
,
1756 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1759 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1760 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1761 sub __mountpoint_mount
{
1762 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1764 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1765 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1766 # which we use in __bindmount_verify()!
1767 my $mount = $stage_mount ?
'/': $mountpoint->{mp
};
1769 my $volid = $mountpoint->{volume
};
1770 my $type = $mountpoint->{type
};
1771 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1774 return if !$volid || !$mount;
1779 my ($mpfd, $parentfd, $last_dir);
1781 if (defined($rootdir)) {
1782 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1783 __mount_prepare_rootdir
($rootdir, $mount, $rootuid, $rootgid);
1786 if (defined($stage_mount)) {
1787 $mount_path = $rootdir;
1790 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1792 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1796 if (my $mountopts = $mountpoint->{mountoptions
}) {
1797 my @opts = split(/;/, $mountpoint->{mountoptions
});
1798 push @$optlist, grep { PVE
::LXC
::Config
::is_valid_mount_option
($_) } @opts;
1801 my $acl = $mountpoint->{acl
};
1802 if (defined($acl)) {
1803 push @$optlist, ($acl ?
'acl' : 'noacl');
1806 my $optstring = join(',', @$optlist);
1807 my $readonly = $mountpoint->{ro
};
1810 @extra_opts = ('-o', $optstring) if $optstring;
1814 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1816 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid, $snapname);
1818 $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname) if !defined($path);
1820 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1821 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1823 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1825 if ($format eq 'subvol') {
1827 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1828 if (defined($snapname)) {
1829 $name .= "\@$snapname";
1830 if ($scfg->{type
} eq 'zfspool') {
1831 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', "$scfg->{pool}/$name", $mount_path]);
1833 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1836 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1837 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1838 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1840 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1841 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1844 return wantarray ?
($path, 0, undef) : $path;
1845 } elsif ($format eq 'raw' || $format eq 'iso') {
1846 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1847 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1848 # Our autodev hook expects the /dev/dm-* device currently
1849 # and will create the /dev/mapper symlink accordingly
1850 $path = Cwd
::realpath
($path);
1851 die "failed to get device path\n" if !$path;
1852 ($path) = ($path =~ /^(.*)$/s); #untaint
1856 if ($format eq 'iso') {
1857 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1858 } elsif ($isBase || defined($snapname)) {
1859 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1862 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1864 push @extra_opts, '-o', 'ro' if $readonly;
1865 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1869 my $use_loopdev = 0;
1870 if ($scfg->{content
}->{rootdir
}) {
1871 if ($scfg->{path
}) {
1872 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1875 $mounted_dev = $path;
1879 die "storage '$storage' does not support containers\n";
1881 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1883 die "unsupported image format '$format'\n";
1885 } elsif ($type eq 'device') {
1886 push @extra_opts, '-o', 'ro' if $readonly;
1887 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1888 # See the NOTE above about devicemapper canonicalization
1889 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1890 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1891 return wantarray ?
($volid, 0, $devpath) : $volid;
1892 } elsif ($type eq 'bind') {
1893 die "directory '$volid' does not exist\n" if ! -d
$volid;
1894 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1895 warn "cannot enable quota control for bind mounts\n" if $quota;
1896 return wantarray ?
($volid, 0, undef) : $volid;
1899 die "unsupported storage";
1902 sub mountpoint_hotplug
:prototype($$$$$) {
1903 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1905 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1907 # We do the rest in a fork with an unshared mount namespace, because:
1908 # -) change our papparmor profile to that of /usr/bin/lxc-start
1909 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1910 # container's namespace, then mount it.
1912 PVE
::Tools
::run_fork
(sub {
1913 # Pin the container pid longer, we also need to get its monitor/parent:
1914 my ($ct_pid, $ct_pidfd) = open_lxc_pid
($vmid)
1915 or die "failed to open pidfd of container $vmid\'s init process\n";
1917 my ($monitor_pid, $monitor_pidfd) = open_ppid
($ct_pid)
1918 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1920 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1921 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1923 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1924 # profile to lower our privileges to the same level we have in the start hook:
1925 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY
)
1926 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1927 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1930 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1931 # namespace for it to remain active there since the container will be able to unmount
1932 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1934 PVE
::Tools
::setns
(fileno($monitor_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1936 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1938 my $dir = get_staging_mount_path
($opt);
1940 # Now switch our apparmor profile before mounting:
1941 my $data = 'changeprofile /usr/bin/lxc-start';
1942 if (syswrite($aa_fd, $data, length($data)) != length($data)) {
1943 die "failed to change apparmor profile: $!\n";
1945 # Check errors on close as well:
1947 or die "failed to change apparmor profile (close() failed): $!\n";
1949 my $mount_fd = mountpoint_stage
($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1951 PVE
::Tools
::setns
(fileno($ct_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1953 or die "failed to change root directory within the container's mount namespace: $!\n";
1955 mountpoint_insert_staged
($mount_fd, undef, $mp->{mp
}, $opt, $rootuid, $rootgid);
1959 # Create a directory in the mountpoint staging tempfs.
1960 sub get_staging_mount_path
($) {
1963 my $target = get_staging_tempfs
() . "/$opt";
1964 if (!mkdir($target) && $! != EEXIST
) {
1965 die "failed to create directory $target: $!\n";
1971 # Mount tmpfs for mount point staging and return the path.
1972 sub get_staging_tempfs
() {
1973 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
1975 my $target = '/var/lib/lxc/.pve-staged-mounts';
1976 if (!mkdir($target)) {
1977 return $target if $! == EEXIST
;
1978 die "failed to create directory $target: $!\n";
1981 PVE
::Tools
::mount
("none", $target, 'tmpfs', 0, "size=8k,mode=755")
1982 or die "failed to mount $target as tmpfs: $!\n";
1988 my ($dev, $rootuid, $rootgid) = @_;
1996 "root_owner=$rootuid:$rootgid",
2001 # a hack to print only the relevant stuff, i.e., the one which could help on repair
2002 if ($line =~ /^(Creating filesystem|Filesystem UUID|Superblock backups|\s+\d+, \d)/) {
2008 print STDERR
"$line\n" if $line && $line !~ /^mke2fs \d\.\d/;
2014 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
2016 if ($volid =~ m!^/dev/.+!) {
2021 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2023 die "cannot format volume '$volid' with no storage\n" if !$storage;
2025 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
2027 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid);
2029 $path = PVE
::Storage
::path
($storage_cfg, $volid) if !defined($path);
2031 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
2032 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
2034 die "cannot format volume '$volid' (format == $format)\n"
2035 if $format ne 'raw';
2037 mkfs
($path, $rootuid, $rootgid);
2041 my ($storecfg, $vollist) = @_;
2043 foreach my $volid (@$vollist) {
2044 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
2050 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
2052 my $needs_chown = 0;
2055 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
2056 # fixme: use better naming ct-$vmid-disk-X.raw?
2060 if ($scfg->{content
}->{rootdir
} && $scfg->{path
}) {
2061 if ($size_kb > 0 && !($scfg->{type
} eq 'btrfs' && $scfg->{quotas
})) {
2062 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2065 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2068 } elsif ($scfg->{type
} eq 'zfspool') {
2069 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2071 } elsif ($scfg->{content
}->{rootdir
}) {
2072 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2075 die "content type 'rootdir' is not available or configured on storage '$storage'\n";
2077 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
2080 # in case formatting got interrupted:
2081 if (defined($volid)) {
2082 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
2088 return ($volid, $needs_chown);
2092 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
2097 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
2098 my $chown_vollist = [];
2100 PVE
::LXC
::Config-
>foreach_volume($settings, sub {
2101 my ($ms, $mountpoint) = @_;
2103 my $volid = $mountpoint->{volume
};
2104 my $mp = $mountpoint->{mp
};
2106 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2108 if ($storage && ($volid =~ $NEW_DISK_RE)) {
2109 my ($storeid, $size_gb) = ($1, $2);
2111 my $size_kb = int(${size_gb
}*1024) * 1024;
2113 my $needs_chown = 0;
2114 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
2115 push @$chown_vollist, $volid if $needs_chown;
2116 push @$vollist, $volid;
2117 $mountpoint->{volume
} = $volid;
2118 $mountpoint->{size
} = $size_kb * 1024;
2120 $conf->{pending
}->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2122 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2125 # use specified/existing volid/dir/device
2126 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2130 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
2131 foreach my $volid (@$chown_vollist) {
2132 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
2133 chown($rootuid, $rootgid, $path);
2135 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
2137 # free allocated images on error
2139 destroy_disks
($storecfg, $vollist);
2145 sub update_disksize
{
2146 my ($vmid, $conf, $all_volumes) = @_;
2149 my $prefix = "CT $vmid:";
2151 my $update_mp = sub {
2152 my ($key, $mp, @param) = @_;
2153 my $size = $all_volumes->{$mp->{volume
}}->{size
} // 0;
2155 if (!defined($mp->{size
}) || $size != $mp->{size
}) {
2157 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
2158 $mp->{size
} = $size;
2159 my $no_mp = $key eq 'rootfs'; # rootfs is handled different from other mount points
2160 $conf->{$key} = PVE
::LXC
::Config-
>print_ct_mountpoint($mp, $no_mp);
2164 PVE
::LXC
::Config-
>foreach_volume($conf, $update_mp);
2170 my ($vmid, $conf, $all_volumes) = @_;
2173 my $prefix = "CT $vmid:";
2175 # Note: it is allowed to define multiple storage entries with the same path
2176 # (alias), so we need to check both 'volid' and real 'path' (two different
2177 # volid can point to the same path).
2179 # used and unused disks
2183 foreach my $opt (keys %$conf) {
2184 next if ($opt !~ m/^unused\d+$/);
2185 my $vol = $all_volumes->{$conf->{$opt}};
2186 $refpath->{$vol->{path
}} = $vol->{volid
};
2189 foreach my $key (keys %$all_volumes) {
2190 my $vol = $all_volumes->{$key};
2191 my $in_use = PVE
::LXC
::Config-
>is_volume_in_use($conf, $vol->{volid
});
2192 my $path = $vol->{path
};
2195 $refpath->{$path} = $key;
2196 delete $orphans->{$path};
2198 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
2199 $orphans->{$path} = $key;
2204 for my $key (keys %$orphans) {
2205 my $disk = $orphans->{$key};
2206 my $unused = PVE
::LXC
::Config-
>add_unused_volume($conf, $disk);
2210 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
2218 my ($cfg, $vmid) = @_;
2220 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid, undef, 'rootdir');
2222 my $all_volumes = {};
2223 foreach my $storeid (keys %$info) {
2224 foreach my $item (@{$info->{$storeid}}) {
2225 my $volid = $item->{volid
};
2226 next if !($volid && $item->{size
});
2227 $item->{path
} = PVE
::Storage
::path
($cfg, $volid);
2228 $all_volumes->{$volid} = $item;
2232 return $all_volumes;
2236 my ($vmid, $nolock, $dryrun) = @_;
2238 my $cfg = PVE
::Storage
::config
();
2240 print "rescan volumes...\n";
2241 my $all_volumes = scan_volids
($cfg, $vmid);
2243 my $updatefn = sub {
2247 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2249 PVE
::LXC
::Config-
>check_lock($conf);
2252 foreach my $volid (keys %$all_volumes) {
2253 my $info = $all_volumes->{$volid};
2254 $vm_volids->{$volid} = $info if $info->{vmid
} == $vmid;
2257 my $upu = update_unused
($vmid, $conf, $vm_volids);
2258 my $upd = update_disksize
($vmid, $conf, $vm_volids);
2259 $changes = $upu || $upd;
2261 PVE
::LXC
::Config-
>write_config($vmid, $conf) if $changes && !$dryrun;
2264 if (defined($vmid)) {
2268 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2271 my $vmlist = config_list
();
2272 foreach my $vmid (keys %$vmlist) {
2276 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2283 # bash completion helper
2285 sub complete_os_templates
{
2286 my ($cmdname, $pname, $cvalue) = @_;
2288 my $cfg = PVE
::Storage
::config
();
2292 if ($cvalue =~ m/^([^:]+):/) {
2296 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
2297 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
2300 foreach my $id (keys %$data) {
2301 foreach my $item (@{$data->{$id}}) {
2302 push @$res, $item->{volid
} if defined($item->{volid
});
2309 my $complete_ctid_full = sub {
2312 my $idlist = vmstatus
();
2314 my $active_hash = list_active_containers
();
2318 foreach my $id (keys %$idlist) {
2319 my $d = $idlist->{$id};
2320 if (defined($running)) {
2321 next if $d->{template
};
2322 next if $running && !$active_hash->{$id};
2323 next if !$running && $active_hash->{$id};
2332 return &$complete_ctid_full();
2335 sub complete_ctid_stopped
{
2336 return &$complete_ctid_full(0);
2339 sub complete_ctid_running
{
2340 return &$complete_ctid_full(1);
2350 my $lxc = $conf->{lxc
};
2351 foreach my $entry (@$lxc) {
2352 my ($key, $value) = @$entry;
2354 next if $key ne 'lxc.idmap';
2356 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2357 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2358 push @$id_map, [$type, $ct, $host, $length];
2360 $rootuid = $host if $type eq 'u';
2361 $rootgid = $host if $type eq 'g';
2364 die "failed to parse idmap: $value\n";
2368 if (!@$id_map && $conf->{unprivileged
}) {
2369 # Should we read them from /etc/subuid?
2370 $id_map = [ ['u', '0', '100000', '65536'],
2371 ['g', '0', '100000', '65536'] ];
2372 $rootuid = $rootgid = 100000;
2375 return ($id_map, $rootuid, $rootgid);
2378 sub validate_id_maps
{
2381 # $mappings->{$type}->{$side} = [ { line => $line, start => $start, count => $count }, ... ]
2382 # $type: either "u" or "g"
2383 # $side: either "container" or "host"
2384 # $line: index of this mapping in @$id_map
2385 # $start, $count: interval of this mapping
2386 my $mappings = { u
=> {}, g
=> {} };
2387 for (my $i = 0; $i < scalar(@$id_map); $i++) {
2388 my ($type, $ct_start, $host_start, $count) = $id_map->[$i]->@*;
2389 my $sides = $mappings->{$type};
2390 push $sides->{host
}->@*, { line
=> $i, start
=> $host_start, count
=> $count };
2391 push $sides->{container
}->@*, { line
=> $i, start
=> $ct_start, count
=> $count };
2394 # find the first conflict between two consecutive mappings when sorted by their start id
2395 for my $type (qw(u g)) {
2396 for my $side (qw(container host)) {
2397 my @entries = sort { $a->{start
} <=> $b->{start
} } $mappings->{$type}->{$side}->@*;
2398 for my $idx (1..scalar(@entries) - 1) {
2399 my $previous = $entries[$idx - 1];
2400 my $current = $entries[$idx];
2401 if ($previous->{start
} + $previous->{count
} > $current->{start
}) {
2402 my $conflict = $current->{start
};
2403 my @previous_line = $id_map->[$previous->{line
}]->@*;
2404 my @current_line = $id_map->[$current->{line
}]->@*;
2405 die "invalid map entry '@current_line': $side ${type}id $conflict "
2406 ."is also mapped by entry '@previous_line'\n";
2413 sub userns_command
{
2416 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2421 my sub print_ct_stderr_log
{
2423 my $log = eval { file_get_contents
("/run/pve/ct-$vmid.stderr") };
2426 while ($log =~ /^\h*(lxc-start:?\s+$vmid:?\s*\S+\s*)?(.*?)\h*$/gm) {
2428 print STDERR
"$line\n";
2431 my sub print_ct_warn_log
{
2433 my $log_fn = "/run/pve/ct-$vmid.warnings";
2434 my $log = eval { file_get_contents
($log_fn) };
2437 while ($log =~ /^\h*\s*(.*?)\h*$/gm) {
2438 PVE
::RESTEnvironment
::log_warn
($1);
2440 unlink $log_fn or warn "could not unlink '$log_fn' - $!\n";
2443 my sub monitor_state_change
($$) {
2444 my ($monitor_socket, $vmid) = @_;
2445 die "no monitor socket\n" if !defined($monitor_socket);
2448 my ($type, $name, $value) = PVE
::LXC
::Monitor
::read_lxc_message
($monitor_socket);
2450 die "monitor socket: got EOF\n" if !defined($type);
2452 next if $name ne "$vmid" || $type ne 'STATE';
2454 if ($value eq PVE
::LXC
::Monitor
::STATE_STARTING
) {
2455 alarm(0); # don't timeout after seeing the starting state
2456 } elsif ($value eq PVE
::LXC
::Monitor
::STATE_ABORTING
||
2457 $value eq PVE
::LXC
::Monitor
::STATE_STOPPING
||
2458 $value eq PVE
::LXC
::Monitor
::STATE_STOPPED
) {
2460 } elsif ($value eq PVE
::LXC
::Monitor
::STATE_RUNNING
) {
2463 warn "unexpected message from monitor socket - " .
2464 "type: '$type' - value: '$value'\n";
2468 my sub monitor_start
($$) {
2469 my ($monitor_socket, $vmid) = @_;
2471 my $success = eval {
2472 PVE
::Tools
::run_with_timeout
(10, \
&monitor_state_change
, $monitor_socket, $vmid)
2475 warn "problem with monitor socket, but continuing anyway: $err\n";
2476 } elsif (!$success) {
2477 print_ct_stderr_log
($vmid);
2478 die "startup for container '$vmid' failed\n";
2483 my ($vmid, $conf, $skiplock, $debug) = @_;
2485 # apply pending changes while starting
2486 if (scalar(keys %{$conf->{pending
}})) {
2487 my $storecfg = PVE
::Storage
::config
();
2488 PVE
::LXC
::Config-
>vmconfig_apply_pending($vmid, $conf, $storecfg);
2489 PVE
::LXC
::Config-
>write_config($vmid, $conf);
2490 $conf = PVE
::LXC
::Config-
>load_config($vmid); # update/reload
2493 update_lxc_config
($vmid, $conf);
2496 my ($id_map, undef, undef) = PVE
::LXC
::parse_id_maps
($conf);
2497 PVE
::LXC
::validate_id_maps
($id_map);
2499 warn "lxc.idmap: $@" if $@;
2501 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2504 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2508 my $storage_cfg = PVE
::Storage
::config
();
2509 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
2511 PVE
::Storage
::activate_volumes
($storage_cfg, $vollist);
2513 my $monitor_socket = eval { PVE
::LXC
::Monitor
::get_monitor_socket
() };
2516 unlink "/run/pve/ct-$vmid.stderr"; # systemd does not truncate log files
2518 my $is_debug = $debug || (!defined($debug) && $conf->{debug
});
2519 my $base_unit = $is_debug ?
'pve-container-debug' : 'pve-container';
2521 my $cmd = ['systemctl', 'start', "$base_unit\@$vmid"];
2523 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-start', 1);
2527 monitor_start
($monitor_socket, $vmid) if defined($monitor_socket);
2529 # if debug is requested, print the log it also when the start succeeded
2530 print_ct_stderr_log
($vmid) if $is_debug;
2532 print_ct_warn_log
($vmid); # always print warn log, if any
2535 unlink $skiplock_flag_fn;
2538 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'post-start');
2543 # Helper to stop a container completely and make sure it has stopped completely.
2544 # This is necessary because we want the post-stop hook to have completed its
2545 # unmount-all step, but post-stop happens after lxc puts the container into the
2547 # $kill - if true it will always do an immediate hard-stop
2548 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2549 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2551 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2553 # Open the container's command socket.
2554 my $path = "\0/var/lib/lxc/$vmid/command";
2555 my $sock = IO
::Socket
::UNIX-
>new(
2556 Type
=> SOCK_STREAM
(),
2560 return if $! == ECONNREFUSED
; # The container is not running
2561 die "failed to open container ${vmid}'s command socket: $!\n";
2564 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2565 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-stop');
2567 # Stop the container:
2569 my $cmd = ['lxc-stop', '-n', $vmid];
2572 push @$cmd, '--kill'; # doesn't allow timeouts
2574 # lxc-stop uses a default timeout
2575 push @$cmd, '--nokill' if !$kill_after_timeout;
2577 if (defined($shutdown_timeout)) {
2578 push @$cmd, '--timeout', $shutdown_timeout;
2579 # Give run_command 5 extra seconds
2580 $shutdown_timeout += 5;
2584 eval { run_command
($cmd, timeout
=> $shutdown_timeout) };
2586 # Wait until the command socket is closed.
2587 # In case the lxc-stop call failed, reading from the command socket may block forever,
2588 # so poll with another timeout to avoid freezing the shutdown task.
2592 my $poll = IO
::Poll-
>new();
2593 $poll->mask($sock => POLLIN
| POLLHUP
); # watch for input and EOF events
2594 $poll->poll($shutdown_timeout); # IO::Poll timeout is in seconds
2595 return if ($poll->events($sock) & POLLHUP
);
2597 my $result = <$sock>;
2598 return if !defined $result; # monitor is gone and the ct has stopped.
2601 die "container did not stop\n";
2605 my ($vmid, $timeout, $skiplock) = @_;
2607 PVE
::LXC
::Config-
>lock_config($vmid, sub {
2608 return if !check_running
($vmid);
2610 vm_stop
($vmid, 0, $timeout, 1); # kill if timeout exceeds
2612 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2613 vm_start
($vmid, $conf);
2620 return PVE
::Tools
::run_fork
(sub {
2621 # Unshare the mount namespace
2622 die "failed to unshare mount namespace: $!\n"
2623 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
2624 run_command
(['mount', '--make-rslave', '/']);
2629 my $copy_volume = sub {
2630 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2632 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
2633 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
2635 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
2636 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
2642 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2643 push @mounted, $src;
2645 mountpoint_mount
($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2646 push @mounted, $dest;
2659 '--one-file-system',
2660 "--bwlimit=$bwlimit",
2667 # Wait for rsync's children to release dest so that
2668 # consequent file operations (umount, remove) are possible
2669 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2671 foreach my $mount (reverse @mounted) {
2672 eval { run_command
(['/bin/umount', $mount], errfunc
=> sub{})};
2673 warn "Can't umount $mount\n" if $@;
2676 # If this fails they're used as mount points in a concurrent operation
2677 # (which should not happen but there's also no real need to get rid of them).
2684 # Should not be called after unsharing the mount namespace!
2686 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2688 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
2689 File
::Path
::make_path
("/var/lib/lxc/$vmid");
2690 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2691 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2693 # get id's for unprivileged container
2694 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
2696 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2697 # are visible in this namespace, otherwise the host only sees the empty
2698 # (not-mounted) directory.
2701 # Make sure $mp contains a correct size.
2702 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
2704 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
2706 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
2707 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
2708 chown($rootuid, $rootgid, $path);
2712 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2716 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
2717 if defined($new_volid);
2724 sub get_lxc_version
() {
2726 run_command
([qw(lxc-start --version)], outfunc
=> sub {
2728 # We only parse out major & minor version numbers.
2729 if ($line =~ /^(\d+)\.(\d+)(?:\D.*)?$/) {
2730 $version = [$1, $2];
2734 die "failed to get lxc version\n" if !defined($version);
2737 return $version->@*;
2742 if (PVE
::CGroup
::cgroup_mode
() == 2) {
2743 PVE
::LXC
::Command
::freeze
($vmid, 30);
2745 PVE
::LXC
::CGroup-
>new($vmid)->freeze_thaw(1);
2751 if (PVE
::CGroup
::cgroup_mode
() == 2) {
2752 PVE
::LXC
::Command
::unfreeze
($vmid, 30);
2754 PVE
::LXC
::CGroup-
>new($vmid)->freeze_thaw(0);