13 use Fcntl
qw(O_RDONLY O_WRONLY O_NOFOLLOW O_DIRECTORY);
14 use Errno
qw(ELOOP ENOTDIR EROFS ECONNREFUSED ENOSYS EEXIST);
17 use PVE
::Exception
qw(raise_perm_exc);
21 use PVE
::JSONSchema
qw(get_standard_option);
23 dir_glob_foreach file_get_contents file_set_contents
24 AT_FDCWD O_PATH $IPV4RE $IPV6RE
28 use PVE
::AccessControl
;
30 use PVE
::Syscall
qw(:fsmount);
32 use PVE
::GuestHelpers
qw(safe_string_ne safe_num_ne safe_boolean_ne);
35 use PVE
::LXC
::Monitor
;
37 use Time
::HiRes qw
(gettimeofday
);
40 require PVE
::Network
::SDN
::Zones
;
44 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
46 my $nodename = PVE
::INotify
::nodename
();
48 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
51 my $vmlist = PVE
::Cluster
::get_vmlist
();
53 return $res if !$vmlist || !$vmlist->{ids
};
54 my $ids = $vmlist->{ids
};
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 };
66 # container status helpers
68 sub list_active_containers
{
70 my $filename = "/proc/net/unix";
72 # similar test is used by lcxcontainers.c: list_active_containers
75 my $fh = IO
::File-
>new ($filename, "r");
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+)$/) {
81 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
92 # warning: this is slow
96 my $active_hash = list_active_containers
();
98 return 1 if defined($active_hash->{$vmid});
103 sub get_container_disk_usage
{
104 my ($vmid, $pid) = @_;
106 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
109 my $last_proc_vmid_stat;
111 our $vmstatus_return_properties = {
112 vmid
=> get_standard_option
('pve-vmid'),
114 description
=> "LXC Container status.",
116 enum
=> ['stopped', 'running'],
119 description
=> "Maximum memory in bytes.",
125 description
=> "Maximum SWAP memory in bytes.",
131 description
=> "Root disk size in bytes.",
137 description
=> "Container name.",
142 description
=> "Uptime.",
145 renderer
=> 'duration',
148 description
=> "Maximum usable CPUs.",
153 description
=> "The current config lock, if any.",
158 description
=> "The current configured tags, if any.",
167 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc', vmid
=> $opt_vmid }} : config_list
();
169 my $active_hash = list_active_containers
();
171 my $cpucount = $cpuinfo->{cpus
} || 1;
173 my $cdtime = gettimeofday
;
175 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
176 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
178 my $unprivileged = {};
180 foreach my $vmid (keys %$list) {
181 my $d = $list->{$vmid};
183 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
184 warn $@ if $@; # ignore errors (consider them stopped)
186 $d->{status
} = $active_hash->{$vmid} ?
'running' : 'stopped';
188 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
189 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
191 $unprivileged->{$vmid} = $conf->{unprivileged
};
193 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
194 $d->{name
} =~ s/[\s]//g;
196 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
197 $d->{cpus
} = $cpucount if !$d->{cpus
};
199 $d->{lock} = $conf->{lock} || '';
200 $d->{tags
} = $conf->{tags
} if defined($conf->{tags
});
203 my $res = get_container_disk_usage
($vmid, $d->{pid
});
204 $d->{disk
} = $res->{used
};
205 $d->{maxdisk
} = $res->{total
};
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);
213 $d->{maxdisk
} = 4*1024*1024*1024;
219 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
220 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
231 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
232 $d->{lock} = $conf->{lock} if $conf->{lock};
235 foreach my $vmid (keys %$list) {
236 my $d = $list->{$vmid};
239 next if !$pid; # skip stopped CTs
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
244 my $unpriv = $unprivileged->{$vmid};
246 my $cgroups = PVE
::LXC
::CGroup-
>new($vmid);
248 if (defined(my $mem = $cgroups->get_memory_stat())) {
249 $d->{mem
} = $mem->{mem
};
250 $d->{swap
} = $mem->{swap
};
256 if (defined(my $blkio = $cgroups->get_io_stats())) {
257 $d->{diskread
} = $blkio->{diskread
};
258 $d->{diskwrite
} = $blkio->{diskwrite
};
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
};
268 my $old = $last_proc_vmid_stat->{$vmid};
270 $last_proc_vmid_stat->{$vmid} = {
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} = {
288 $d->{cpu
} = $old->{cpu
};
295 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
297 foreach my $dev (keys %$netdev) {
298 next if $dev !~ m/^veth([1-9]\d*)i/;
300 my $d = $list->{$vmid};
304 $d->{netout
} += $netdev->{$dev}->{receive
};
305 $d->{netin
} += $netdev->{$dev}->{transmit
};
312 sub find_lxc_console_pids
{
316 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
319 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
322 my @args = split(/\0/, $cmdline);
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
$|;
332 push @{$res->{$vmid}}, $pid;
344 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
346 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
348 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
355 sysopen(my $fd, "/proc/$pid", O_RDONLY
| O_DIRECTORY
)
356 or die "failed to open /proc/$pid pid fd\n";
363 # Find the pid and open:
364 my $pid = find_lxc_pid
($vmid);
365 my $fd = open_pid_fd
($pid);
368 my $pid2 = find_lxc_pid
($vmid);
370 return () if $pid != $pid2;
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";
381 my $fd = open_pid_fd
($ppid);
384 $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
385 my $ppid2 = $stat->{ppid
} // die "failed to get parent pid for verification\n";
387 return () if $ppid != $ppid2;
391 # Note: we cannot use Net:IP, because that only allows strict
393 sub parse_ipv4_cidr
{
394 my ($cidr, $noerr) = @_;
396 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
397 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
400 return undef if $noerr;
402 die "unable to parse ipv4 address/mask\n";
405 # Deprecated. Use `PVE::LXC::CGroup::get_cgroup_controllers()` instead.
406 sub get_cgroup_subsystems
{
407 PVE
::LXC
::CGroup
::get_v1_controllers
();
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).
413 # This means that there are cases where we need to create an extra seccomp
414 # profile for the container to load.
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;
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
433 return '' if !$unprivileged;
436 keyctl
=> ['errno 38'],
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
};
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
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);
458 die "'mknod' feature requested, but kernel too old (found $kernel, required >= 5.3)\n";
461 $raw_conf .= "lxc.seccomp.notify.proxy = unix:/run/pve/lxc-syscalld.sock\n";
462 $raw_conf .= "lxc.seccomp.notify.cookie = $vmid\n";
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]',
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]',
478 # Now build the custom seccomp rule text...
479 my $extra_rules = join("\n", map {
481 map { "$syscall $_" } $rules->{$syscall}->@*
482 } sort keys %$rules) . "\n";
484 return $raw_conf if $extra_rules eq "\n";
486 # We still have the "most common" config readily available, so don't write
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";
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")
497 file_set_contents
($rule_file, $rule_data);
498 $raw_conf .= "lxc.seccomp.profile = $rule_file\n";
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.
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
510 sub make_apparmor_config
{
511 my ($conf, $unprivileged, $features) = @_;
513 # user-configured profile has precedence, but first we go through our own
514 # code to figure out whether we should warn the user:
516 my $raw = "lxc.apparmor.profile = generated\n";
519 if ($features->{fuse
}) {
520 # For the informational warning:
521 push @profile_uses, 'features:fuse';
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"
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/,
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";
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";
562 sub update_lxc_config
{
563 my ($vmid, $conf) = @_;
565 my $dir = "/var/lib/lxc/$vmid";
567 if ($conf->{template
}) {
569 unlink "$dir/config";
574 my ($lxc_major, $lxc_minor) = get_lxc_version
();
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
584 $raw .= "lxc.cgroup.relative = 0\n";
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";
594 die "missing 'arch' - internal error" if !$conf->{arch
};
595 $raw .= "lxc.arch = $conf->{arch}\n";
597 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
598 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
600 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
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";
607 $inc = "$cfgpath/$ostype.userns.conf";
608 $inc = "$cfgpath/userns.conf" if !-f
$inc;
609 $raw .= "lxc.include = $inc\n";
612 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
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";
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";
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";
634 my $cgv1 = get_cgroup_subsystems
();
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";
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
};
647 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
648 $raw .= "lxc.tty.max = $ttycount\n";
650 # some init scripts expect a linux terminal (turnkey).
651 $raw .= "lxc.environment = TERM=linux\n";
653 my $utsname = $conf->{hostname
} || "CT$vmid";
654 $raw .= "lxc.uts.name = $utsname\n";
656 if ($cgv1->{memory
}) {
657 my $memory = $conf->{memory
} || 512;
658 my $swap = $conf->{swap
} // 0;
660 my $lxcmem = int($memory*1024*1024);
661 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
663 my $lxcswap = int(($memory + $swap)*1024*1024);
664 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
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";
674 my $shares = $conf->{cpuunits
} || 1024;
675 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
678 die "missing 'rootfs' configuration\n"
679 if !defined($conf->{rootfs
});
681 my $mountpoint = PVE
::LXC
::Config-
>parse_volume('rootfs', $conf->{rootfs
});
683 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
685 foreach my $k (sort keys %$conf) {
686 next if $k !~ m/^net(\d+)$/;
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
});
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";
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';
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);
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
724 my $ver = $cpuset_version == 1 ?
'' : '2';
725 $raw .= "lxc.cgroup$ver.cpuset.cpus = ".$cpuset->short_string()."\n";
728 File
::Path
::mkpath
("$dir/rootfs");
730 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
733 # verify and cleanup nameserver list (replace \0 with ' ')
734 sub verify_nameserver_list
{
735 my ($nameserver_list) = @_;
738 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
739 PVE
::JSONSchema
::pve_verify_ip
($server);
743 return join(' ', @list);
746 sub verify_searchdomain_list
{
747 my ($searchdomain_list) = @_;
750 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
751 # todo: should we add checks for valid dns domains?
755 return join(' ', @list);
758 sub get_console_command
{
759 my ($vmid, $conf, $escapechar) = @_;
761 # '-1' as $escapechar disables keyboard escape sequence
762 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
764 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
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;
776 die "internal error";
782 sub get_primary_ips
{
785 # return data from net0
787 return undef if !defined($conf->{net0
});
788 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
790 my $ipv4 = $net->{ip
};
792 if ($ipv4 =~ /^(dhcp|manual)$/) {
798 my $ipv6 = $net->{ip6
};
800 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
807 return ($ipv4, $ipv6);
810 sub delete_mountpoint_volume
{
811 my ($storage_cfg, $vmid, $volume) = @_;
813 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
815 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
817 if ($vmid == $owner) {
818 PVE
::Storage
::vdisk_free
($storage_cfg, $volume);
820 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
824 sub destroy_lxc_container
{
825 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
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
});
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);
838 PVE
::LXC
::Config-
>destroy_config($vmid);
842 sub vm_stop_cleanup
{
843 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
845 return if $keepActive;
848 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
849 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
851 warn $@ if $@; # avoid errors - just warn
855 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
857 if ($newnet->{type
} ne 'veth') {
858 # for when there are physical interfaces
859 die "cannot update interface of type $newnet->{type}";
862 my $veth = "veth${vmid}i${netid}";
863 my $eth = $newnet->{name
};
865 if (my $oldnetcfg = $conf->{$opt}) {
866 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
868 if (safe_string_ne
($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
869 safe_string_ne
($oldnet->{name
}, $newnet->{name
})) {
871 PVE
::Network
::veth_delete
($veth);
872 delete $conf->{$opt};
873 PVE
::LXC
::Config-
>write_config($vmid, $conf);
875 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
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
})) {
882 if ($oldnet->{bridge
}) {
883 PVE
::Network
::tap_unplug
($veth);
884 foreach (qw(bridge tag firewall)) {
885 delete $oldnet->{$_};
887 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
888 PVE
::LXC
::Config-
>write_config($vmid, $conf);
892 PVE
::Network
::SDN
::Zones
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
894 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
897 # This includes the rate:
898 foreach (qw(bridge tag firewall rate)) {
899 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
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
}
907 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
908 PVE
::LXC
::Config-
>write_config($vmid, $conf);
911 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
914 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
918 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
920 my $veth = "veth${vmid}i${netid}";
921 my $vethpeer = $veth . "p";
922 my $eth = $newnet->{name
};
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
});
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
});
932 # attach peer in container
933 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
934 PVE
::Tools
::run_command
($cmd);
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);
940 my $done = { type
=> 'veth' };
941 foreach (qw(bridge tag firewall hwaddr name)) {
942 $done->{$_} = $newnet->{$_} if $newnet->{$_};
944 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
946 PVE
::LXC
::Config-
>write_config($vmid, $conf);
949 sub update_ipconfig
{
950 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
952 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
954 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
959 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
961 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
963 my $change_ip_config = sub {
964 my ($ipversion) = @_;
966 my $family_opt = "-$ipversion";
967 my $suffix = $ipversion == 4 ?
'' : $ipversion;
971 my $newip = $newnet->{$ip};
972 my $newgw = $newnet->{$gw};
973 my $oldip = $optdata->{$ip};
974 my $oldgw = $optdata->{$gw};
976 my $change_ip = safe_string_ne
($oldip, $newip);
977 my $change_gw = safe_string_ne
($oldgw, $newgw);
979 return if !$change_ip && !$change_gw;
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); };
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
999 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
1000 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1002 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1006 # the route was not replaced, the old IP is still available
1007 # rollback (delete new IP) and cancel
1009 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
1010 warn $@ if $@; # no need to die here
1015 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
1016 # if the route was not deleted, the guest might have deleted it manually
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
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.
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");
1039 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1041 warn $@ if $@; # no need to die here
1043 if ($ipversion == 4) {
1044 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1048 foreach my $property ($ip, $gw) {
1049 if ($newnet->{$property}) {
1050 $optdata->{$property} = $newnet->{$property};
1052 delete $optdata->{$property};
1055 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
1056 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1057 $lxc_setup->setup_network($conf);
1060 &$change_ip_config(4);
1061 &$change_ip_config(6);
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";
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";
1080 my $get_container_namespace = sub {
1081 my ($vmid, $pid, $kind) = @_;
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";
1090 return $open_namespace->($vmid, $pid, $kind);
1093 my $do_syncfs = sub {
1094 my ($vmid, $pid, $socket) = @_;
1096 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
1098 # Tell the parent process to start reading our /proc/mounts
1099 print {$socket} "go\n";
1102 # Receive /proc/self/mounts
1103 my $mountdata = do { local $/ = undef; <$socket> };
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); };
1116 sub sync_container_namespace
{
1118 my $pid = find_lxc_pid
($vmid);
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";
1125 die "fork failed: $!\n" if !defined($child);
1130 &$do_syncfs($vmid, $pid, $cfd);
1140 die "failed to enter container namespace\n" if $go ne "go\n";
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> };
1146 print {$pfd} $mountdata;
1149 while (waitpid($child, 0) != $child) {}
1150 die "failed to sync container namespace\n" if $? != 0;
1153 sub template_create
{
1154 my ($vmid, $conf) = @_;
1156 my $storecfg = PVE
::Storage
::config
();
1158 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1159 my ($ms, $mountpoint) = @_;
1161 my $volid = $mountpoint->{volume
};
1163 die "Template feature is not available for '$volid'\n"
1164 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1167 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1168 my ($ms, $mountpoint) = @_;
1170 my $volid = $mountpoint->{volume
};
1172 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
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");
1179 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1182 sub check_ct_modify_config_perm
{
1183 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
1185 return 1 if $authuser eq 'root@pam';
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']);
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");
1209 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1213 foreach my $opt (keys %$newconf) {
1216 foreach my $opt (@$delete) {
1224 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1226 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1227 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1231 PVE
::LXC
::Config-
>foreach_volume_full($conf, {'reverse' => 1}, sub {
1232 my ($ms, $mountpoint) = @_;
1234 my $volid = $mountpoint->{volume
};
1235 my $mount = $mountpoint->{mp
};
1237 return if !$volid || !$mount;
1239 my $mount_path = "$rootdir/$mount";
1240 $mount_path =~ s!/+!/!g;
1242 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1245 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
1257 return $res; # tell caller if (some) umounts failed for the noerr case
1261 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1263 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1264 File
::Path
::make_path
($rootdir);
1266 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1267 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
1269 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1272 PVE
::LXC
::Config-
>foreach_volume($conf, sub {
1273 my ($ms, $mountpoint) = @_;
1275 $mountpoint->{ro
} = 0 if $ignore_ro;
1277 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1281 warn "mounting container failed\n";
1282 umount_all
($vmid, $storage_cfg, $conf, 1);
1290 sub mountpoint_mount_path
{
1291 my ($mountpoint, $storage_cfg, $snapname) = @_;
1293 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1301 if ($line =~ m
@^(/dev/loop\d
+):@) {
1305 my $cmd = ['losetup', '--associated', $path];
1306 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
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
1318 # We assume that whoever setup the loop device is responsible for
1326 if ($line =~ m
@^(/dev/loop\d
+)$@) {
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); };
1341 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
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) = @_;
1355 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1356 or die "failed to open start directory $start: $!\n";
1358 return walk_tree_nofollow_fd
($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1362 sub walk_tree_nofollow_fd
($$$$;$$) {
1363 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1365 # splitdir() returns '' for empty components including the leading /
1366 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1369 my $dir = $start_dirname;
1370 my $last_component = undef;
1372 foreach my $component (@comps) {
1373 $dir .= "/$component";
1374 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
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;
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);
1388 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1389 die "failed to create path: $dir: $!\n" if !$next;
1391 PVE
::Tools
::fchownat
(fileno($next), '', $rootuid, $rootgid, PVE
::Tools
::AT_EMPTY_PATH
)
1392 if defined($rootuid) && defined($rootgid);
1395 close $second if defined($last_component) && $second != $start_fd;
1396 $last_component = $component;
1401 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1402 close $second if defined($last_component) && $second != $start_fd;
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);
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) = @_;
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
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;
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";
1435 die "read-only check failed: $!\n" if $! != EROFS
;
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
1442 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1443 die "failed to open mount point: $!\n" if !$destdh;
1446 my ($srcdev, $srcinode) = stat($srcdh);
1447 my ($dstdev, $dstinode) = stat($destdh);
1451 return ($srcdev == $dstdev && $srcinode == $dstinode);
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]);
1459 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1461 warn "bindmount error\n";
1462 # don't leave writable bind-mounts behind...
1463 PVE
::Tools
::run_command
(['umount', $dest]);
1470 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1472 my $srcdh = __bindmount_prepare
('/', $dir);
1474 __bindmount_do
($dir, $dest, $ro, @extra_opts);
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";
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);
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);
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);
1505 if (!defined($path)) {
1506 return undef if $! == ENOSYS
;
1507 die "failed to mount subvolume: $!\n";
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
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";
1517 return wantarray ?
($path, $loop, $dev, $fd) : $fd;
1520 sub mountpoint_insert_staged
{
1521 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1523 if (!defined($rootdir_fd)) {
1524 sysopen($rootdir_fd, '.', O_PATH
| O_DIRECTORY
)
1525 or die "failed to open '.': $!\n";
1528 my $dest_fd = walk_tree_nofollow_fd
('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1530 PVE
::Tools
::move_mount
(
1535 &MOVE_MOUNT_F_EMPTY_PATH
| &MOVE_MOUNT_T_EMPTY_PATH
,
1536 ) or die "failed to move '$opt' into container hierarchy: $!\n";
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) = @_;
1546 if (defined($stage_mount) && !PVE
::LXC
::Tools
::can_use_new_mount_api
()) {
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
};
1556 my $volid = $mountpoint->{volume
};
1557 my $type = $mountpoint->{type
};
1558 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1561 return if !$volid || !$mount;
1566 my ($mpfd, $parentfd, $last_dir);
1568 if (defined($rootdir)) {
1569 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1570 __mount_prepare_rootdir
($rootdir, $mount, $rootuid, $rootgid);
1573 if (defined($stage_mount)) {
1574 $mount_path = $rootdir;
1577 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1579 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1583 if (my $mountopts = $mountpoint->{mountoptions
}) {
1584 my @opts = split(/;/, $mountpoint->{mountoptions
});
1585 push @$optlist, grep { PVE
::LXC
::Config
::is_valid_mount_option
($_) } @opts;
1588 my $acl = $mountpoint->{acl
};
1589 if (defined($acl)) {
1590 push @$optlist, ($acl ?
'acl' : 'noacl');
1593 my $optstring = join(',', @$optlist);
1594 my $readonly = $mountpoint->{ro
};
1597 @extra_opts = ('-o', $optstring) if $optstring;
1601 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1603 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid, $snapname);
1605 $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname) if !defined($path);
1607 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1608 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1610 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1612 if ($format eq 'subvol') {
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]);
1620 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
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"]);
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;
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
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]);
1649 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1651 push @extra_opts, '-o', 'ro' if $readonly;
1652 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1656 my $use_loopdev = 0;
1657 if ($scfg->{path
}) {
1658 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1660 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1661 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1662 $mounted_dev = $path;
1665 die "unsupported storage type '$scfg->{type}'\n";
1667 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1669 die "unsupported image format '$format'\n";
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;
1685 die "unsupported storage";
1688 sub mountpoint_hotplug
($$$) {
1689 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1691 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
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.
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";
1703 my ($monitor_pid, $monitor_pidfd) = open_ppid
($ct_pid)
1704 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1706 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1707 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
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
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
1720 PVE
::Tools
::setns
(fileno($monitor_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1722 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1724 my $dir = get_staging_mount_path
($opt);
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";
1731 # Check errors on close as well:
1733 or die "failed to change apparmor profile (close() failed): $!\n";
1735 my $mount_fd = mountpoint_stage
($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1737 PVE
::Tools
::setns
(fileno($ct_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1739 or die "failed to change root directory within the container's mount namespace: $!\n";
1741 mountpoint_insert_staged
($mount_fd, undef, $mp->{mp
}, $opt, $rootuid, $rootgid);
1745 # Create a directory in the mountpoint staging tempfs.
1746 sub get_staging_mount_path
($) {
1749 my $target = get_staging_tempfs
() . "/$opt";
1750 if (!mkdir($target) && $! != EEXIST
) {
1751 die "failed to create directory $target: $!\n";
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
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";
1767 PVE
::Tools
::mount
("none", $target, 'tmpfs', 0, "size=8k,mode=755")
1768 or die "failed to mount $target as tmpfs: $!\n";
1774 my ($dev, $rootuid, $rootgid) = @_;
1776 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1777 '-E', "root_owner=$rootuid:$rootgid",
1782 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1784 if ($volid =~ m!^/dev/.+!) {
1789 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1791 die "cannot format volume '$volid' with no storage\n" if !$storage;
1793 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1795 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid);
1797 $path = PVE
::Storage
::path
($storage_cfg, $volid) if !defined($path);
1799 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1800 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1802 die "cannot format volume '$volid' (format == $format)\n"
1803 if $format ne 'raw';
1805 mkfs
($path, $rootuid, $rootgid);
1809 my ($storecfg, $vollist) = @_;
1811 foreach my $volid (@$vollist) {
1812 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1818 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1820 my $needs_chown = 0;
1823 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1824 # fixme: use better naming ct-$vmid-disk-X.raw?
1828 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs' || $scfg->{type
} eq 'cifs' ) {
1830 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1834 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1838 } elsif ($scfg->{type
} eq 'zfspool') {
1840 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1843 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1845 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1848 } elsif ($scfg->{type
} eq 'rbd') {
1850 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1853 die "unable to create containers on storage type '$scfg->{type}'\n";
1855 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1858 # in case formatting got interrupted:
1859 if (defined($volid)) {
1860 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1866 return ($volid, $needs_chown);
1869 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1871 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
1876 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1877 my $chown_vollist = [];
1879 PVE
::LXC
::Config-
>foreach_volume($settings, sub {
1880 my ($ms, $mountpoint) = @_;
1882 my $volid = $mountpoint->{volume
};
1883 my $mp = $mountpoint->{mp
};
1885 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1887 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1888 my ($storeid, $size_gb) = ($1, $2);
1890 my $size_kb = int(${size_gb
}*1024) * 1024;
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;
1899 $conf->{pending
}->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1901 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1904 # use specified/existing volid/dir/device
1905 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
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);
1914 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1916 # free allocated images on error
1918 destroy_disks
($storecfg, $vollist);
1924 sub update_disksize
{
1925 my ($vmid, $conf, $all_volumes) = @_;
1928 my $prefix = "CT $vmid:";
1930 my $update_mp = sub {
1931 my ($key, $mp, @param) = @_;
1932 my $size = $all_volumes->{$mp->{volume
}}->{size
} // 0;
1934 if (!defined($mp->{size
}) || $size != $mp->{size
}) {
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);
1943 PVE
::LXC
::Config-
>foreach_volume($conf, $update_mp);
1949 my ($vmid, $conf, $all_volumes) = @_;
1952 my $prefix = "CT $vmid:";
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).
1958 # used and unused disks
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
};
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
};
1974 $refpath->{$path} = $key;
1975 delete $orphans->{$path};
1977 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
1978 $orphans->{$path} = $key;
1983 for my $key (keys %$orphans) {
1984 my $disk = $orphans->{$key};
1985 my $unused = PVE
::LXC
::Config-
>add_unused_volume($conf, $disk);
1989 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
1997 my ($cfg, $vmid) = @_;
1999 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid);
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;
2011 return $all_volumes;
2015 my ($vmid, $nolock, $dryrun) = @_;
2017 my $cfg = PVE
::Storage
::config
();
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
};
2025 print "rescan volumes...\n";
2026 my $all_volumes = scan_volids
($cfg, $vmid);
2028 my $updatefn = sub {
2032 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2034 PVE
::LXC
::Config-
>check_lock($conf);
2037 foreach my $volid (keys %$all_volumes) {
2038 my $info = $all_volumes->{$volid};
2039 $vm_volids->{$volid} = $info if $info->{vmid
} == $vmid;
2042 my $upu = update_unused
($vmid, $conf, $vm_volids);
2043 my $upd = update_disksize
($vmid, $conf, $vm_volids);
2044 $changes = $upu || $upd;
2046 PVE
::LXC
::Config-
>write_config($vmid, $conf) if $changes && !$dryrun;
2049 if (defined($vmid)) {
2053 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2056 my $vmlist = config_list
();
2057 foreach my $vmid (keys %$vmlist) {
2061 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2068 # bash completion helper
2070 sub complete_os_templates
{
2071 my ($cmdname, $pname, $cvalue) = @_;
2073 my $cfg = PVE
::Storage
::config
();
2077 if ($cvalue =~ m/^([^:]+):/) {
2081 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
2082 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
2085 foreach my $id (keys %$data) {
2086 foreach my $item (@{$data->{$id}}) {
2087 push @$res, $item->{volid
} if defined($item->{volid
});
2094 my $complete_ctid_full = sub {
2097 my $idlist = vmstatus
();
2099 my $active_hash = list_active_containers
();
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};
2117 return &$complete_ctid_full();
2120 sub complete_ctid_stopped
{
2121 return &$complete_ctid_full(0);
2124 sub complete_ctid_running
{
2125 return &$complete_ctid_full(1);
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];
2144 $rootuid = $host if $type eq 'u';
2145 $rootgid = $host if $type eq 'g';
2148 die "failed to parse idmap: $value\n";
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;
2159 return ($id_map, $rootuid, $rootgid);
2162 sub userns_command
{
2165 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2170 my sub print_ct_stderr_log
{
2172 my $log = eval { file_get_contents
("/run/pve/ct-$vmid.stderr") };
2175 while ($log =~ /^\h*(lxc-start:?\s+$vmid:?\s*\S+\s*)?(.*?)\h*$/gm) {
2177 print STDERR
"$line\n";
2181 my sub monitor_state_change
($$) {
2182 my ($monitor_socket, $vmid) = @_;
2183 die "no monitor socket\n" if !defined($monitor_socket);
2186 my ($type, $name, $value) = PVE
::LXC
::Monitor
::read_lxc_message
($monitor_socket);
2188 die "monitor socket: got EOF\n" if !defined($type);
2190 next if $name ne "$vmid" || $type ne 'STATE';
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
) {
2198 } elsif ($value eq PVE
::LXC
::Monitor
::STATE_RUNNING
) {
2201 warn "unexpected message from monitor socket - " .
2202 "type: '$type' - value: '$value'\n";
2206 my sub monitor_start
($$) {
2207 my ($monitor_socket, $vmid) = @_;
2209 my $success = eval {
2210 PVE
::Tools
::run_with_timeout
(10, \
&monitor_state_change
, $monitor_socket, $vmid)
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";
2221 my ($vmid, $conf, $skiplock) = @_;
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
2231 update_lxc_config
($vmid, $conf);
2233 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2236 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2240 my $storage_cfg = PVE
::Storage
::config
();
2241 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
2243 PVE
::Storage
::activate_volumes
($storage_cfg, $vollist);
2245 my $monitor_socket = eval { PVE
::LXC
::Monitor
::get_monitor_socket
() };
2248 unlink "/run/pve/ct-$vmid.stderr"; # systemd does not truncate log files
2250 my $base_unit = $conf->{debug
} ?
'pve-container-debug' : 'pve-container';
2252 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
2254 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-start', 1);
2256 PVE
::Tools
::run_command
($cmd);
2258 monitor_start
($monitor_socket, $vmid) if defined($monitor_socket);
2261 unlink $skiplock_flag_fn;
2264 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'post-start');
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
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
2277 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
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
(),
2286 return if $! == ECONNREFUSED
; # The container is not running
2287 die "failed to open container ${vmid}'s command socket: $!\n";
2290 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2291 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-stop');
2293 # Stop the container:
2295 my $cmd = ['lxc-stop', '-n', $vmid];
2298 push @$cmd, '--kill'; # doesn't allow timeouts
2300 # lxc-stop uses a default timeout
2301 push @$cmd, '--nokill' if !$kill_after_timeout;
2303 if (defined($shutdown_timeout)) {
2304 push @$cmd, '--timeout', $shutdown_timeout;
2305 # Give run_command 5 extra seconds
2306 $shutdown_timeout += 5;
2310 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
2315 my $result = <$sock>;
2317 return if !defined $result; # monitor is gone and the ct has stopped.
2318 die "container did not stop\n";
2322 my ($vmid, $timeout, $skiplock) = @_;
2324 PVE
::LXC
::Config-
>lock_config($vmid, sub {
2325 return if !check_running
($vmid);
2327 vm_stop
($vmid, 0, $timeout, 1); # kill if timeout exceeds
2329 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2330 vm_start
($vmid, $conf);
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', '/']);
2346 my $copy_volume = sub {
2347 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2349 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
2350 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
2352 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
2353 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
2359 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2360 push @mounted, $src;
2362 mountpoint_mount
($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2363 push @mounted, $dest;
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]);
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};
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 $@;
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).
2390 # Should not be called after unsharing the mount namespace!
2392 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
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";
2399 # get id's for unprivileged container
2400 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
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.
2407 # Make sure $mp contains a correct size.
2408 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
2410 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
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);
2418 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2422 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
2423 if defined($new_volid);
2430 sub get_lxc_version
() {
2432 PVE
::Tools
::run_command
([qw(lxc-start --version)], outfunc
=> sub {
2434 # We only parse out major & minor version numbers.
2435 if ($line =~ /^(\d+)\.(\d+)(?:\D.*)?$/) {
2436 $version = [$1, $2];
2440 die "failed to get lxc version\n" if !defined($version);
2443 return $version->@*;
2448 PVE
::LXC
::CGroup-
>new($vmid)->freeze_thaw(1);
2453 PVE
::LXC
::CGroup-
>new($vmid)->freeze_thaw(0);