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 lock_file
24 lock_file_full AT_FDCWD O_PATH $IPV4RE $IPV6RE
28 use PVE
::AccessControl
;
30 use PVE
::Syscall
qw(:fsmount);
32 use PVE
::GuestHelpers
;
35 use Time
::HiRes qw
(gettimeofday
);
37 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
39 my $nodename = PVE
::INotify
::nodename
();
41 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
44 my $vmlist = PVE
::Cluster
::get_vmlist
();
46 return $res if !$vmlist || !$vmlist->{ids
};
47 my $ids = $vmlist->{ids
};
49 foreach my $vmid (keys %$ids) {
50 next if !$vmid; # skip CT0
51 my $d = $ids->{$vmid};
52 next if !$d->{node
} || $d->{node
} ne $nodename;
53 next if !$d->{type
} || $d->{type
} ne 'lxc';
54 $res->{$vmid} = { type
=> 'lxc', vmid
=> $vmid };
59 # container status helpers
61 sub list_active_containers
{
63 my $filename = "/proc/net/unix";
65 # similar test is used by lcxcontainers.c: list_active_containers
68 my $fh = IO
::File-
>new ($filename, "r");
71 while (defined(my $line = <$fh>)) {
72 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
74 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
85 # warning: this is slow
89 my $active_hash = list_active_containers
();
91 return 1 if defined($active_hash->{$vmid});
96 sub get_container_disk_usage
{
97 my ($vmid, $pid) = @_;
99 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
102 my $last_proc_vmid_stat;
104 my $parse_cpuacct_stat = sub {
105 my ($vmid, $unprivileged) = @_;
107 my $raw = read_cgroup_value
('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
111 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
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
=> $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
} = 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->{lock} = $conf->{lock} || '';
210 $d->{tags
} = $conf->{tags
} if defined($conf->{tags
});
213 my $res = get_container_disk_usage
($vmid, $d->{pid
});
214 $d->{disk
} = $res->{used
};
215 $d->{maxdisk
} = $res->{total
};
218 # use 4GB by default ??
219 if (my $rootfs = $conf->{rootfs
}) {
220 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($rootfs);
221 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
223 $d->{maxdisk
} = 4*1024*1024*1024;
229 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
230 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
241 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
242 $d->{lock} = $conf->{lock} if $conf->{lock};
245 foreach my $vmid (keys %$list) {
246 my $d = $list->{$vmid};
249 next if !$pid; # skip stopped CTs
251 my $proc_pid_stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
252 $d->{uptime
} = int(($uptime - $proc_pid_stat->{starttime
}) / $clock_ticks); # the method lxcfs uses
254 my $unpriv = $unprivileged->{$vmid};
256 if (-d
'/sys/fs/cgroup/memory') {
257 my $memory_stat = read_cgroup_list
('memory', $vmid, $unpriv, 'memory.stat');
258 my $mem_usage_in_bytes = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
260 $d->{mem
} = $mem_usage_in_bytes - $memory_stat->{total_cache
};
261 $d->{swap
} = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
267 if (-d
'/sys/fs/cgroup/blkio') {
268 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, 0, 'blkio.throttle.io_service_bytes', 1); # don't check if unpriv
269 my @bytes = split(/\n/, $blkio_bytes);
270 foreach my $byte (@bytes) {
271 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
272 $d->{diskread
} += $2 if $key eq 'Read';
273 $d->{diskwrite
} += $2 if $key eq 'Write';
281 if (-d
'/sys/fs/cgroup/cpuacct') {
282 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
284 my $used = $pstat->{utime} + $pstat->{stime
};
286 my $old = $last_proc_vmid_stat->{$vmid};
288 $last_proc_vmid_stat->{$vmid} = {
296 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
299 my $dutime = $used - $old->{used
};
301 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
302 $last_proc_vmid_stat->{$vmid} = {
308 $d->{cpu
} = $old->{cpu
};
315 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
317 foreach my $dev (keys %$netdev) {
318 next if $dev !~ m/^veth([1-9]\d*)i/;
320 my $d = $list->{$vmid};
324 $d->{netout
} += $netdev->{$dev}->{receive
};
325 $d->{netin
} += $netdev->{$dev}->{transmit
};
332 sub read_cgroup_list
($$$$) {
333 my ($group, $vmid, $unprivileged, $name) = @_;
335 my $content = read_cgroup_value
($group, $vmid, $unprivileged, $name, 1);
337 return { split(/\s+/, $content) };
340 sub read_cgroup_value
($$$$$) {
341 my ($group, $vmid, $unprivileged, $name, $full) = @_;
343 my $nsdir = $unprivileged ?
'' : 'ns/';
344 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
346 return PVE
::Tools
::file_get_contents
($path) if $full;
348 return PVE
::Tools
::file_read_firstline
($path);
351 sub write_cgroup_value
{
352 my ($group, $vmid, $name, $value) = @_;
354 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
355 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
359 sub find_lxc_console_pids
{
363 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
366 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
369 my @args = split(/\0/, $cmdline);
371 # search for lxc-console -n <vmid>
372 return if scalar(@args) != 3;
373 return if $args[1] ne '-n';
374 return if $args[2] !~ m/^\d+$/;
375 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
379 push @{$res->{$vmid}}, $pid;
391 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
393 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
395 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
402 sysopen(my $fd, "/proc/$pid", O_RDONLY
| O_DIRECTORY
)
403 or die "failed to open /proc/$pid pid fd\n";
410 # Find the pid and open:
411 my $pid = find_lxc_pid
($vmid);
412 my $fd = open_pid_fd
($pid);
415 my $pid2 = find_lxc_pid
($vmid);
417 return () if $pid != $pid2;
424 # Find the parent pid via proc and open it:
425 my $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
426 my $ppid = $stat->{ppid
} // die "failed to get parent pid\n";
428 my $fd = open_pid_fd
($ppid);
431 $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
432 my $ppid2 = $stat->{ppid
} // die "failed to get parent pid for verification\n";
434 return () if $ppid != $ppid2;
438 # Note: we cannot use Net:IP, because that only allows strict
440 sub parse_ipv4_cidr
{
441 my ($cidr, $noerr) = @_;
443 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
444 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
447 return undef if $noerr;
449 die "unable to parse ipv4 address/mask\n";
452 sub get_cgroup_subsystems
{
455 my $data = PVE
::Tools
::file_get_contents
('/proc/self/cgroup');
456 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
459 $v1->{$_} = 1 foreach split(/,/, $type);
464 return wantarray ?
($v1, $v2) : $v1;
467 # With seccomp trap to userspace we now have the ability to optionally forward
468 # certain syscalls to the "host" to handle (via our pve-lxc-syscalld daemon).
470 # This means that there are cases where we need to create an extra seccomp
471 # profile for the container to load.
473 # This returns a configuration snippet added to the raw lxc config.
474 sub make_seccomp_config
{
475 my ($conf, $vmid, $conf_dir, $unprivileged, $features) = @_;
476 # User-configured profile has precedence, note that the user's entry would
477 # be written 'after' this line anyway...
478 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.seccomp.profile')) {
479 # Warn the user if this conflicts with a feature:
480 my $warn = join(', ', grep { $features->{$_} } qw(keyctl mknod));
481 warn "explicitly configured lxc.seccomp.profile overrides the following settings: $warn\n"
482 if length($warn) > 0;
486 # Privileged containers keep using the default (which is already part of
487 # the files included via lxc.include, so we don't need to write it out,
488 # that way it stays admin-configurable via /usr/share/lxc/config/... as
490 return '' if !$unprivileged;
493 keyctl
=> ['errno 38'],
498 # Unprivileged containers will get keyctl() disabled by default as a
499 # workaround for systemd-networkd behavior. But we have an option to
500 # explicitly enable it:
501 if ($features->{keyctl
}) {
502 delete $rules->{keyctl
};
505 # By default, unprivileged containers cannot use `mknod` at all.
506 # Since lxc 3.2, we can use seccomp's trap to userspace feature for this,
507 # but for now this is experimental, so it has to be enabled via a feature
509 # Note that we only handle block and char devices (like lxd), the rest we
510 # leave up to the kernel. We may in the future remove this if seccomp gets
511 # a way to tell the kernel to "continue" a syscall.
512 if ($features->{mknod
}) {
513 my ($ok, $kernel) = PVE
::ProcFSTools
::check_kernel_release
(5, 3);
515 die "'mknod' feature requested, but kernel too old (found $kernel, required >= 5.3)\n";
518 $raw_conf .= "lxc.seccomp.notify.proxy = unix:/run/pve/lxc-syscalld.sock\n";
519 $raw_conf .= "lxc.seccomp.notify.cookie = $vmid\n";
522 # condition: (mode & S_IFMT) == S_IFCHR
523 'notify [1,8192,SCMP_CMP_MASKED_EQ,61440]',
524 # condition: (mode & S_IFMT) == S_IFBLK
525 'notify [1,24576,SCMP_CMP_MASKED_EQ,61440]',
527 $rules->{mknodat
} = [
528 # condition: (mode & S_IFMT) == S_IFCHR
529 'notify [2,8192,SCMP_CMP_MASKED_EQ,61440]',
530 # condition: (mode & S_IFMT) == S_IFBLK
531 'notify [2,24576,SCMP_CMP_MASKED_EQ,61440]',
535 # Now build the custom seccomp rule text...
536 my $extra_rules = join("\n", map {
538 map { "$syscall $_" } $rules->{$syscall}->@*
539 } sort keys %$rules) . "\n";
541 return $raw_conf if $extra_rules eq "\n";
543 # We still have the "most common" config readily available, so don't write
545 if ($raw_conf eq '' && $extra_rules eq "keyctl errno 38\n") {
546 # we have no extra $raw_conf and use the same we had in pve 6.1:
547 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
550 # Write the rule file to the container's config path:
551 my $rule_file = "$conf_dir/rules.seccomp";
552 my $rule_data = file_get_contents
("$LXC_CONFIG_PATH/common.seccomp")
554 file_set_contents
($rule_file, $rule_data);
555 $raw_conf .= "lxc.seccomp.profile = $rule_file\n";
560 # Since lxc-3.0.2 we can have lxc generate a profile for the container
561 # automatically. The default should be equivalent to the old
562 # `lxc-container-default-cgns` profile.
564 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
565 # additional lines into the profile. We can use that to allow mounting specific
567 sub make_apparmor_config
{
568 my ($conf, $unprivileged, $features) = @_;
570 # user-configured profile has precedence, but first we go through our own
571 # code to figure out whether we should warn the user:
573 my $raw = "lxc.apparmor.profile = generated\n";
576 if ($features->{fuse
}) {
577 # For the informational warning:
578 push @profile_uses, 'features:fuse';
581 # There's lxc.apparmor.allow_nesting now, which will add the necessary
582 # apparmor lines, create an apparmor namespace for the container, but also
583 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
584 # lxcfs mounted over them, because that would prevent the container from
585 # mounting new instances of them for nested containers.
586 if ($features->{nesting
}) {
587 push @profile_uses, 'features:nesting';
588 $raw .= "lxc.apparmor.allow_nesting = 1\n"
590 # In the default profile in /etc/apparmor.d we patch this in because
591 # otherwise a container can for example run `chown` on /sys, breaking
592 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
593 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
594 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
595 # Preferably we could use the 'remount' flag but this does not sit well
596 # with apparmor_parser currently:
597 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
600 if (my $mount = $features->{mount
}) {
601 push @profile_uses, 'features:mount';
602 foreach my $fs (PVE
::Tools
::split_list
($mount)) {
603 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
609 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.apparmor.profile')) {
610 if (length(my $used = join(', ', @profile_uses))) {
611 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
619 sub update_lxc_config
{
620 my ($vmid, $conf) = @_;
622 my $dir = "/var/lib/lxc/$vmid";
624 if ($conf->{template
}) {
626 unlink "$dir/config";
633 die "missing 'arch' - internal error" if !$conf->{arch
};
634 $raw .= "lxc.arch = $conf->{arch}\n";
636 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
637 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
639 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
641 my $cfgpath = '/usr/share/lxc/config';
642 my $inc = "$cfgpath/$ostype.common.conf";
643 $inc ="$cfgpath/common.conf" if !-f
$inc;
644 $raw .= "lxc.include = $inc\n";
646 $inc = "$cfgpath/$ostype.userns.conf";
647 $inc = "$cfgpath/userns.conf" if !-f
$inc;
648 $raw .= "lxc.include = $inc\n";
651 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
653 $raw .= make_seccomp_config
($conf, $vmid, $dir, $unprivileged, $features);
654 $raw .= make_apparmor_config
($conf, $unprivileged, $features);
655 if ($features->{fuse
}) {
656 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
657 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
660 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
661 # cannot be exposed to the container with r/w access (cgroup perms).
662 # When this is enabled mounts will still remain in the monitor's namespace
663 # after the container unmounted them and thus will not detach from their
664 # files while the container is running!
665 $raw .= "lxc.monitor.unshare = 1\n";
667 my $cgv1 = get_cgroup_subsystems
();
669 # Should we read them from /etc/subuid?
670 if ($unprivileged && !$custom_idmap) {
671 $raw .= "lxc.idmap = u 0 100000 65536\n";
672 $raw .= "lxc.idmap = g 0 100000 65536\n";
675 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
676 $raw .= "lxc.console.path = none\n";
677 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices
};
680 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
681 $raw .= "lxc.tty.max = $ttycount\n";
683 # some init scripts expect a linux terminal (turnkey).
684 $raw .= "lxc.environment = TERM=linux\n";
686 my $utsname = $conf->{hostname
} || "CT$vmid";
687 $raw .= "lxc.uts.name = $utsname\n";
689 if ($cgv1->{memory
}) {
690 my $memory = $conf->{memory
} || 512;
691 my $swap = $conf->{swap
} // 0;
693 my $lxcmem = int($memory*1024*1024);
694 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
696 my $lxcswap = int(($memory + $swap)*1024*1024);
697 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
701 if (my $cpulimit = $conf->{cpulimit
}) {
702 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
703 my $value = int(100000*$cpulimit);
704 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
707 my $shares = $conf->{cpuunits
} || 1024;
708 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
711 die "missing 'rootfs' configuration\n"
712 if !defined($conf->{rootfs
});
714 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
716 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
718 foreach my $k (sort keys %$conf) {
719 next if $k !~ m/^net(\d+)$/;
721 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
722 $raw .= "lxc.net.$ind.type = veth\n";
723 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
724 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
725 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
726 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu
});
729 if ($cgv1->{cpuset
}) {
731 if (my $lxcconf = $conf->{lxc
}) {
732 foreach my $entry (@$lxcconf) {
733 my ($k, $v) = @$entry;
734 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
739 my $cores = $conf->{cores
};
740 if (!$had_cpuset && $cores) {
741 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup('lxc', 'effective_cpus') };
742 $cpuset = PVE
::CpuSet-
>new_from_cgroup('', 'effective_cpus') if !$cpuset;
743 my @members = $cpuset->members();
744 while (scalar(@members) > $cores) {
745 my $randidx = int(rand(scalar(@members)));
746 $cpuset->delete($members[$randidx]);
747 splice(@members, $randidx, 1); # keep track of the changes
749 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
753 File
::Path
::mkpath
("$dir/rootfs");
755 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
758 # verify and cleanup nameserver list (replace \0 with ' ')
759 sub verify_nameserver_list
{
760 my ($nameserver_list) = @_;
763 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
764 PVE
::JSONSchema
::pve_verify_ip
($server);
768 return join(' ', @list);
771 sub verify_searchdomain_list
{
772 my ($searchdomain_list) = @_;
775 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
776 # todo: should we add checks for valid dns domains?
780 return join(' ', @list);
783 sub get_console_command
{
784 my ($vmid, $conf, $escapechar) = @_;
786 # '-1' as $escapechar disables keyboard escape sequence
787 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
789 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
792 if ($cmode eq 'console') {
793 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
794 push @$cmd, '-e', $escapechar if $escapechar;
795 } elsif ($cmode eq 'tty') {
796 push @$cmd, 'lxc-console', '-n', $vmid;
797 push @$cmd, '-e', $escapechar if $escapechar;
798 } elsif ($cmode eq 'shell') {
799 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
801 die "internal error";
807 sub get_primary_ips
{
810 # return data from net0
812 return undef if !defined($conf->{net0
});
813 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
815 my $ipv4 = $net->{ip
};
817 if ($ipv4 =~ /^(dhcp|manual)$/) {
823 my $ipv6 = $net->{ip6
};
825 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
832 return ($ipv4, $ipv6);
835 sub delete_mountpoint_volume
{
836 my ($storage_cfg, $vmid, $volume) = @_;
838 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
840 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
842 if ($vmid == $owner) {
843 PVE
::Storage
::vdisk_free
($storage_cfg, $volume);
845 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
849 sub destroy_lxc_container
{
850 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
852 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
853 my ($ms, $mountpoint) = @_;
854 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
857 rmdir "/var/lib/lxc/$vmid/rootfs";
858 unlink "/var/lib/lxc/$vmid/config";
859 rmdir "/var/lib/lxc/$vmid";
860 if (defined $replacement_conf) {
861 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
863 PVE
::LXC
::Config-
>destroy_config($vmid);
867 sub vm_stop_cleanup
{
868 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
870 return if $keepActive;
873 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
874 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
876 warn $@ if $@; # avoid errors - just warn
879 my $safe_num_ne = sub {
882 return 0 if !defined($a) && !defined($b);
883 return 1 if !defined($a);
884 return 1 if !defined($b);
889 my $safe_string_ne = sub {
892 return 0 if !defined($a) && !defined($b);
893 return 1 if !defined($a);
894 return 1 if !defined($b);
900 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
902 if ($newnet->{type
} ne 'veth') {
903 # for when there are physical interfaces
904 die "cannot update interface of type $newnet->{type}";
907 my $veth = "veth${vmid}i${netid}";
908 my $eth = $newnet->{name
};
910 if (my $oldnetcfg = $conf->{$opt}) {
911 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
913 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
914 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
916 PVE
::Network
::veth_delete
($veth);
917 delete $conf->{$opt};
918 PVE
::LXC
::Config-
>write_config($vmid, $conf);
920 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
923 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
924 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
925 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
927 if ($oldnet->{bridge
}) {
928 PVE
::Network
::tap_unplug
($veth);
929 foreach (qw(bridge tag firewall)) {
930 delete $oldnet->{$_};
932 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
933 PVE
::LXC
::Config-
>write_config($vmid, $conf);
936 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
937 # This includes the rate:
938 foreach (qw(bridge tag firewall rate)) {
939 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
941 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
942 # Rate can be applied on its own but any change above needs to
943 # include the rate in tap_plug since OVS resets everything.
944 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
945 $oldnet->{rate
} = $newnet->{rate
}
947 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
948 PVE
::LXC
::Config-
>write_config($vmid, $conf);
951 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
954 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
958 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
960 my $veth = "veth${vmid}i${netid}";
961 my $vethpeer = $veth . "p";
962 my $eth = $newnet->{name
};
964 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
965 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
967 # attach peer in container
968 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
969 PVE
::Tools
::run_command
($cmd);
971 # link up peer in container
972 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
973 PVE
::Tools
::run_command
($cmd);
975 my $done = { type
=> 'veth' };
976 foreach (qw(bridge tag firewall hwaddr name)) {
977 $done->{$_} = $newnet->{$_} if $newnet->{$_};
979 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
981 PVE
::LXC
::Config-
>write_config($vmid, $conf);
984 sub update_ipconfig
{
985 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
987 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
989 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
994 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
996 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
998 my $change_ip_config = sub {
999 my ($ipversion) = @_;
1001 my $family_opt = "-$ipversion";
1002 my $suffix = $ipversion == 4 ?
'' : $ipversion;
1003 my $gw= "gw$suffix";
1004 my $ip= "ip$suffix";
1006 my $newip = $newnet->{$ip};
1007 my $newgw = $newnet->{$gw};
1008 my $oldip = $optdata->{$ip};
1009 my $oldgw = $optdata->{$gw};
1011 my $change_ip = &$safe_string_ne($oldip, $newip);
1012 my $change_gw = &$safe_string_ne($oldgw, $newgw);
1014 return if !$change_ip && !$change_gw;
1016 # step 1: add new IP, if this fails we cancel
1017 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
1018 if ($change_ip && $is_real_ip) {
1019 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
1026 # step 2: replace gateway
1027 # If this fails we delete the added IP and cancel.
1028 # If it succeeds we save the config and delete the old IP, ignoring
1029 # errors. The config is then saved.
1030 # Note: 'ip route replace' can add
1034 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
1035 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1037 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1041 # the route was not replaced, the old IP is still available
1042 # rollback (delete new IP) and cancel
1044 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
1045 warn $@ if $@; # no need to die here
1050 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
1051 # if the route was not deleted, the guest might have deleted it manually
1055 if ($oldgw && $oldip && !PVE
::Network
::is_ip_in_cidr
($oldgw, $oldip)) {
1056 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
1057 # warn if the route was deleted manually
1062 # from this point on we save the configuration
1063 # step 3: delete old IP ignoring errors
1064 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
1065 # We need to enable promote_secondaries, otherwise our newly added
1066 # address will be removed along with the old one.
1069 if ($ipversion == 4) {
1070 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
1071 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1072 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1074 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1076 warn $@ if $@; # no need to die here
1078 if ($ipversion == 4) {
1079 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1083 foreach my $property ($ip, $gw) {
1084 if ($newnet->{$property}) {
1085 $optdata->{$property} = $newnet->{$property};
1087 delete $optdata->{$property};
1090 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
1091 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1092 $lxc_setup->setup_network($conf);
1095 &$change_ip_config(4);
1096 &$change_ip_config(6);
1100 my $open_namespace = sub {
1101 my ($vmid, $pid, $kind) = @_;
1102 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1103 or die "failed to open $kind namespace of container $vmid: $!\n";
1107 my $enter_namespace = sub {
1108 my ($vmid, $pid, $kind, $type) = @_;
1109 my $fd = $open_namespace->($vmid, $pid, $kind);
1110 PVE
::Tools
::setns
(fileno($fd), $type)
1111 or die "failed to enter $kind namespace of container $vmid: $!\n";
1115 my $get_container_namespace = sub {
1116 my ($vmid, $pid, $kind) = @_;
1119 if (!defined($pid)) {
1120 # Pin the pid while we're grabbing its stuff from /proc
1121 ($pid, $pidfd) = open_lxc_pid
($vmid)
1122 or die "failed to open pidfd of container $vmid\'s init process\n";
1125 return $open_namespace->($vmid, $pid, $kind);
1128 my $do_syncfs = sub {
1129 my ($vmid, $pid, $socket) = @_;
1131 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
1133 # Tell the parent process to start reading our /proc/mounts
1134 print {$socket} "go\n";
1137 # Receive /proc/self/mounts
1138 my $mountdata = do { local $/ = undef; <$socket> };
1141 # Now sync all mountpoints...
1142 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
1143 foreach my $mp (@$mounts) {
1144 my ($what, $dir, $fs) = @$mp;
1145 next if $fs eq 'fuse.lxcfs';
1146 eval { PVE
::Tools
::sync_mountpoint
($dir); };
1151 sub sync_container_namespace
{
1153 my $pid = find_lxc_pid
($vmid);
1155 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1156 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
1157 or die "failed to create socketpair: $!\n";
1160 die "fork failed: $!\n" if !defined($child);
1165 &$do_syncfs($vmid, $pid, $cfd);
1175 die "failed to enter container namespace\n" if $go ne "go\n";
1177 open my $mounts, '<', "/proc/$child/mounts"
1178 or die "failed to open container's /proc/mounts: $!\n";
1179 my $mountdata = do { local $/ = undef; <$mounts> };
1181 print {$pfd} $mountdata;
1184 while (waitpid($child, 0) != $child) {}
1185 die "failed to sync container namespace\n" if $? != 0;
1188 sub template_create
{
1189 my ($vmid, $conf) = @_;
1191 my $storecfg = PVE
::Storage
::config
();
1193 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1194 my ($ms, $mountpoint) = @_;
1196 my $volid = $mountpoint->{volume
};
1198 die "Template feature is not available for '$volid'\n"
1199 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1202 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1203 my ($ms, $mountpoint) = @_;
1205 my $volid = $mountpoint->{volume
};
1207 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
1209 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
1210 $mountpoint->{volume
} = $template_volid;
1211 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1214 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1217 sub check_ct_modify_config_perm
{
1218 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
1220 return 1 if $authuser eq 'root@pam';
1223 my ($opt, $delete) = @_;
1224 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1225 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1226 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1227 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1229 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
1230 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
1231 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
1232 if $data->{type
} ne 'volume';
1233 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1234 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1235 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1236 $opt eq 'searchdomain' || $opt eq 'hostname') {
1237 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1238 } elsif ($opt eq 'features') {
1239 # For now this is restricted to root@pam
1240 raise_perm_exc
("changing feature flags is only allowed for root\@pam");
1241 } elsif ($opt eq 'hookscript') {
1242 # For now this is restricted to root@pam
1243 raise_perm_exc
("changing the hookscript is only allowed for root\@pam");
1245 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1249 foreach my $opt (keys %$newconf) {
1252 foreach my $opt (@$delete) {
1260 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1262 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1263 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1267 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
1268 my ($ms, $mountpoint) = @_;
1270 my $volid = $mountpoint->{volume
};
1271 my $mount = $mountpoint->{mp
};
1273 return if !$volid || !$mount;
1275 my $mount_path = "$rootdir/$mount";
1276 $mount_path =~ s!/+!/!g;
1278 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1281 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
1293 return $res; # tell caller if (some) umounts failed for the noerr case
1297 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1299 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1300 File
::Path
::make_path
($rootdir);
1302 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1303 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
1305 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1308 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1309 my ($ms, $mountpoint) = @_;
1311 $mountpoint->{ro
} = 0 if $ignore_ro;
1313 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1317 warn "mounting container failed\n";
1318 umount_all
($vmid, $storage_cfg, $conf, 1);
1326 sub mountpoint_mount_path
{
1327 my ($mountpoint, $storage_cfg, $snapname) = @_;
1329 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1337 if ($line =~ m
@^(/dev/loop\d
+):@) {
1341 my $cmd = ['losetup', '--associated', $path];
1342 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1346 # Run a function with a file attached to a loop device.
1347 # The loop device is always detached afterwards (or set to autoclear).
1348 # Returns the loop device.
1349 sub run_with_loopdev
{
1350 my ($func, $file, $readonly) = @_;
1351 my $device = query_loopdev
($file);
1352 # Try to reuse an existing device
1354 # We assume that whoever setup the loop device is responsible for
1362 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1372 push @$losetup_cmd, '-r' if $readonly;
1373 PVE
::Tools
::run_command
($losetup_cmd, outfunc
=> $parser);
1374 die "failed to setup loop device for $file\n" if !$device;
1375 eval { &$func($device); };
1377 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1382 # In scalar mode: returns a file handle to the deepest directory node.
1383 # In list context: returns a list of:
1384 # * the deepest directory node
1385 # * the 2nd deepest directory (parent of the above)
1386 # * directory name of the last directory
1387 # So that the path $2/$3 should lead to $1 afterwards.
1388 sub walk_tree_nofollow
($$$;$$) {
1389 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1391 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1392 or die "failed to open start directory $start: $!\n";
1394 return walk_tree_nofollow_fd
($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1398 sub walk_tree_nofollow_fd
($$$$;$$) {
1399 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1401 # splitdir() returns '' for empty components including the leading /
1402 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1405 my $dir = $start_dirname;
1406 my $last_component = undef;
1408 foreach my $component (@comps) {
1409 $dir .= "/$component";
1410 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1413 # failed, check for symlinks and try to create the path
1414 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1415 die "cannot open directory $dir: $!\n" if !$mkdir;
1417 # We don't check for errors on mkdirat() here and just try to
1418 # openat() again, since at least one error (EEXIST) is an
1419 # expected possibility if multiple containers start
1420 # simultaneously. If someone else injects a symlink now then
1421 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1422 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1424 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1425 die "failed to create path: $dir: $!\n" if !$next;
1427 PVE
::Tools
::fchownat
(fileno($next), '', $rootuid, $rootgid, PVE
::Tools
::AT_EMPTY_PATH
)
1428 if defined($rootuid) && defined($rootgid);
1431 close $second if defined($last_component) && $second != $start_fd;
1432 $last_component = $component;
1437 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1438 close $second if defined($last_component) && $second != $start_fd;
1442 # To guard against symlink attack races against other currently running
1443 # containers with shared recursive bind mount hierarchies we prepare a
1444 # directory handle for the directory we're mounting over to verify the
1445 # mountpoint afterwards.
1446 sub __bindmount_prepare
{
1447 my ($hostroot, $dir) = @_;
1448 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1452 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1453 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1454 # we intended to bind mount.
1455 sub __bindmount_verify
{
1456 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1459 # Open the mount point path coming from the parent directory since the
1460 # filehandle we would have gotten as first result of walk_tree_nofollow
1461 # earlier is still a handle to the underlying directory instead of the
1463 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1464 die "failed to open mount point: $!\n" if !$destdh;
1467 # no separate function because 99% of the time it's the wrong thing to use.
1468 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1469 die "failed to mark bind mount read only\n";
1471 die "read-only check failed: $!\n" if $! != EROFS
;
1474 # For the rootfs we don't have a parentfd so we open the path directly.
1475 # Note that this means bindmounting any prefix of the host's
1476 # /var/lib/lxc/$vmid path into another container is considered a grave
1478 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1479 die "failed to open mount point: $!\n" if !$destdh;
1482 my ($srcdev, $srcinode) = stat($srcdh);
1483 my ($dstdev, $dstinode) = stat($destdh);
1487 return ($srcdev == $dstdev && $srcinode == $dstinode);
1490 # Perform the actual bind mounting:
1491 sub __bindmount_do
{
1492 my ($dir, $dest, $ro, @extra_opts) = @_;
1493 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1495 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1497 warn "bindmount error\n";
1498 # don't leave writable bind-mounts behind...
1499 PVE
::Tools
::run_command
(['umount', $dest]);
1506 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1508 my $srcdh = __bindmount_prepare
('/', $dir);
1510 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1512 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1513 PVE
::Tools
::run_command
(['umount', $dest]);
1514 die "detected mount path change at: $dir\n";
1518 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1519 # from $rootdir and $mount and walk the path from $rootdir to the final
1520 # directory to check for symlinks.
1521 sub __mount_prepare_rootdir
{
1522 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1523 $rootdir =~ s!/+!/!g;
1524 $rootdir =~ s!/+$!!;
1525 my $mount_path = "$rootdir/$mount";
1526 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1, $rootuid, $rootgid);
1527 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1530 # use $rootdir = undef to just return the corresponding mount path
1531 sub mountpoint_mount
{
1532 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1533 return __mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1536 sub mountpoint_stage
{
1537 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1538 my ($path, $loop, $dev) =
1539 __mountpoint_mount
($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1541 if (!defined($path)) {
1542 return undef if $! == ENOSYS
;
1543 die "failed to mount subvolume: $!\n";
1546 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1547 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1550 my $fd = PVE
::Tools
::open_tree
(&AT_FDCWD
, $stage_dir, &OPEN_TREE_CLOEXEC
| &OPEN_TREE_CLONE
)
1551 or die "open_tree() on mount point failed: $!\n";
1553 return wantarray ?
($path, $loop, $dev, $fd) : $fd;
1556 sub mountpoint_insert_staged
{
1557 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1559 if (!defined($rootdir_fd)) {
1560 sysopen($rootdir_fd, '.', O_PATH
| O_DIRECTORY
)
1561 or die "failed to open '.': $!\n";
1564 my $dest_fd = walk_tree_nofollow_fd
('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1566 PVE
::Tools
::move_mount
(
1571 &MOVE_MOUNT_F_EMPTY_PATH
| &MOVE_MOUNT_T_EMPTY_PATH
,
1572 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1575 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1576 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1577 # Note that if the kernel does not support the new mount API, this will not perform any action
1578 # and return `undef` with $! = ENOSYS.
1579 sub __mountpoint_mount
{
1580 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1582 if (defined($stage_mount) && !PVE
::LXC
::Tools
::can_use_new_mount_api
()) {
1587 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1588 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1589 # which we use in __bindmount_verify()!
1590 my $mount = $stage_mount ?
'/': $mountpoint->{mp
};
1592 my $volid = $mountpoint->{volume
};
1593 my $type = $mountpoint->{type
};
1594 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1597 return if !$volid || !$mount;
1602 my ($mpfd, $parentfd, $last_dir);
1604 if (defined($rootdir)) {
1605 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1606 __mount_prepare_rootdir
($rootdir, $mount, $rootuid, $rootgid);
1609 if (defined($stage_mount)) {
1610 $mount_path = $rootdir;
1613 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1615 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1619 if (my $mountopts = $mountpoint->{mountoptions
}) {
1620 my @opts = split(/;/, $mountpoint->{mountoptions
});
1621 push @$optlist, grep { PVE
::LXC
::Config
::is_valid_mount_option
($_) } @opts;
1624 my $acl = $mountpoint->{acl
};
1625 if (defined($acl)) {
1626 push @$optlist, ($acl ?
'acl' : 'noacl');
1629 my $optstring = join(',', @$optlist);
1630 my $readonly = $mountpoint->{ro
};
1633 @extra_opts = ('-o', $optstring) if $optstring;
1637 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1639 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid, $snapname);
1641 $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname) if !defined($path);
1643 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1644 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1646 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1648 if ($format eq 'subvol') {
1651 if ($scfg->{type
} eq 'zfspool') {
1652 my $path_arg = $path;
1653 $path_arg =~ s!^/+!!;
1654 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1656 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1659 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1660 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1661 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1662 $name .= "\@$snapname" if defined($snapname);
1663 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1665 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1666 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1669 return wantarray ?
($path, 0, undef) : $path;
1670 } elsif ($format eq 'raw' || $format eq 'iso') {
1671 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1672 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1673 # Our autodev hook expects the /dev/dm-* device currently
1674 # and will create the /dev/mapper symlink accordingly
1675 $path = Cwd
::realpath
($path);
1676 die "failed to get device path\n" if !$path;
1677 ($path) = ($path =~ /^(.*)$/s); #untaint
1681 if ($format eq 'iso') {
1682 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1683 } elsif ($isBase || defined($snapname)) {
1684 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1687 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1689 push @extra_opts, '-o', 'ro' if $readonly;
1690 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1694 my $use_loopdev = 0;
1695 if ($scfg->{path
}) {
1696 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1698 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1699 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1700 $mounted_dev = $path;
1703 die "unsupported storage type '$scfg->{type}'\n";
1705 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1707 die "unsupported image format '$format'\n";
1709 } elsif ($type eq 'device') {
1710 push @extra_opts, '-o', 'ro' if $readonly;
1711 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1712 # See the NOTE above about devicemapper canonicalization
1713 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1714 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1715 return wantarray ?
($volid, 0, $devpath) : $volid;
1716 } elsif ($type eq 'bind') {
1717 die "directory '$volid' does not exist\n" if ! -d
$volid;
1718 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1719 warn "cannot enable quota control for bind mounts\n" if $quota;
1720 return wantarray ?
($volid, 0, undef) : $volid;
1723 die "unsupported storage";
1726 sub mountpoint_hotplug
($$$) {
1727 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1729 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1731 # We do the rest in a fork with an unshared mount namespace, because:
1732 # -) change our papparmor profile to that of /usr/bin/lxc-start
1733 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1734 # container's namespace, then mount it.
1736 PVE
::Tools
::run_fork
(sub {
1737 # Pin the container pid longer, we also need to get its monitor/parent:
1738 my ($ct_pid, $ct_pidfd) = open_lxc_pid
($vmid)
1739 or die "failed to open pidfd of container $vmid\'s init process\n";
1741 my ($monitor_pid, $monitor_pidfd) = open_ppid
($ct_pid)
1742 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1744 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1745 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1747 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1748 # profile to lower our privileges to the same level we have in the start hook:
1749 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY
)
1750 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1751 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1754 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1755 # namespace for it to remain active there since the container will be able to unmount
1756 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1758 PVE
::Tools
::setns
(fileno($monitor_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1760 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1762 my $dir = get_staging_mount_path
($opt);
1764 # Now switch our apparmor profile before mounting:
1765 my $data = 'changeprofile /usr/bin/lxc-start';
1766 if (syswrite($aa_fd, $data, length($data)) != length($data)) {
1767 die "failed to change apparmor profile: $!\n";
1769 # Check errors on close as well:
1771 or die "failed to change apparmor profile (close() failed): $!\n";
1773 my $mount_fd = mountpoint_stage
($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1775 PVE
::Tools
::setns
(fileno($ct_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1777 or die "failed to change root directory within the container's mount namespace: $!\n";
1779 mountpoint_insert_staged
($mount_fd, undef, $mp->{mp
}, $opt, $rootuid, $rootgid);
1783 # Create a directory in the mountpoint staging tempfs.
1784 sub get_staging_mount_path
($) {
1787 my $target = get_staging_tempfs
() . "/$opt";
1788 if (!mkdir($target) && $! != EEXIST
) {
1789 die "failed to create directory $target: $!\n";
1795 # Mount /run/pve/mountpoints as tmpfs
1796 sub get_staging_tempfs
() {
1797 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
1799 my $target = '/var/lib/lxc/.pve-staged-mounts';
1800 if (!mkdir($target)) {
1801 return $target if $! == EEXIST
;
1802 die "failed to create directory $target: $!\n";
1805 PVE
::Tools
::mount
("none", $target, 'tmpfs', 0, "size=8k,mode=755")
1806 or die "failed to mount $target as tmpfs: $!\n";
1812 my ($dev, $rootuid, $rootgid) = @_;
1814 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1815 '-E', "root_owner=$rootuid:$rootgid",
1820 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1822 if ($volid =~ m!^/dev/.+!) {
1827 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1829 die "cannot format volume '$volid' with no storage\n" if !$storage;
1831 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1833 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid);
1835 $path = PVE
::Storage
::path
($storage_cfg, $volid) if !defined($path);
1837 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1838 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1840 die "cannot format volume '$volid' (format == $format)\n"
1841 if $format ne 'raw';
1843 mkfs
($path, $rootuid, $rootgid);
1847 my ($storecfg, $vollist) = @_;
1849 foreach my $volid (@$vollist) {
1850 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1856 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1858 my $needs_chown = 0;
1861 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1862 # fixme: use better naming ct-$vmid-disk-X.raw?
1866 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs' || $scfg->{type
} eq 'cifs' ) {
1868 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1872 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1876 } elsif ($scfg->{type
} eq 'zfspool') {
1878 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1881 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1883 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1886 } elsif ($scfg->{type
} eq 'rbd') {
1888 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1891 die "unable to create containers on storage type '$scfg->{type}'\n";
1893 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1896 # in case formatting got interrupted:
1897 if (defined($volid)) {
1898 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1904 return ($volid, $needs_chown);
1907 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1909 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
1914 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1915 my $chown_vollist = [];
1917 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1918 my ($ms, $mountpoint) = @_;
1920 my $volid = $mountpoint->{volume
};
1921 my $mp = $mountpoint->{mp
};
1923 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1925 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1926 my ($storeid, $size_gb) = ($1, $2);
1928 my $size_kb = int(${size_gb
}*1024) * 1024;
1930 my $needs_chown = 0;
1931 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1932 push @$chown_vollist, $volid if $needs_chown;
1933 push @$vollist, $volid;
1934 $mountpoint->{volume
} = $volid;
1935 $mountpoint->{size
} = $size_kb * 1024;
1937 $conf->{pending
}->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1939 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1942 # use specified/existing volid/dir/device
1943 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1947 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1948 foreach my $volid (@$chown_vollist) {
1949 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1950 chown($rootuid, $rootgid, $path);
1952 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1954 # free allocated images on error
1956 destroy_disks
($storecfg, $vollist);
1962 sub update_disksize
{
1963 my ($vmid, $conf, $all_volumes) = @_;
1966 my $prefix = "CT $vmid:";
1968 my $update_mp = sub {
1969 my ($key, $mp, @param) = @_;
1970 my $size = $all_volumes->{$mp->{volume
}}->{size
} // 0;
1972 if (!defined($mp->{size
}) || $size != $mp->{size
}) {
1974 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1975 $mp->{size
} = $size;
1976 my $nomp = 1 if ($key eq 'rootfs');
1977 $conf->{$key} = PVE
::LXC
::Config-
>print_ct_mountpoint($mp, $nomp);
1981 PVE
::LXC
::Config-
>foreach_mountpoint($conf, $update_mp);
1987 my ($vmid, $conf, $all_volumes) = @_;
1990 my $prefix = "CT $vmid:";
1992 # Note: it is allowed to define multiple storage entries with the same path
1993 # (alias), so we need to check both 'volid' and real 'path' (two different
1994 # volid can point to the same path).
1996 # used and unused disks
2000 foreach my $opt (keys %$conf) {
2001 next if ($opt !~ m/^unused\d+$/);
2002 my $vol = $all_volumes->{$conf->{$opt}};
2003 $refpath->{$vol->{path
}} = $vol->{volid
};
2006 foreach my $key (keys %$all_volumes) {
2007 my $vol = $all_volumes->{$key};
2008 my $in_use = PVE
::LXC
::Config-
>is_volume_in_use($conf, $vol->{volid
});
2009 my $path = $vol->{path
};
2012 $refpath->{$path} = $key;
2013 delete $orphans->{$path};
2015 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
2016 $orphans->{$path} = $key;
2021 for my $key (keys %$orphans) {
2022 my $disk = $orphans->{$key};
2023 my $unused = PVE
::LXC
::Config-
>add_unused_volume($conf, $disk);
2027 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
2035 my ($cfg, $vmid) = @_;
2037 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid);
2039 my $all_volumes = {};
2040 foreach my $storeid (keys %$info) {
2041 foreach my $item (@{$info->{$storeid}}) {
2042 my $volid = $item->{volid
};
2043 next if !($volid && $item->{size
});
2044 $item->{path
} = PVE
::Storage
::path
($cfg, $volid);
2045 $all_volumes->{$volid} = $item;
2049 return $all_volumes;
2053 my ($vmid, $nolock, $dryrun) = @_;
2055 my $cfg = PVE
::Storage
::config
();
2057 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
2058 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
2059 foreach my $stor (keys %{$cfg->{ids
}}) {
2060 delete($cfg->{ids
}->{$stor}) if !$cfg->{ids
}->{$stor}->{content
}->{rootdir
};
2063 print "rescan volumes...\n";
2064 my $all_volumes = scan_volids
($cfg, $vmid);
2066 my $updatefn = sub {
2070 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2072 PVE
::LXC
::Config-
>check_lock($conf);
2075 foreach my $volid (keys %$all_volumes) {
2076 my $info = $all_volumes->{$volid};
2077 $vm_volids->{$volid} = $info if $info->{vmid
} == $vmid;
2080 my $upu = update_unused
($vmid, $conf, $vm_volids);
2081 my $upd = update_disksize
($vmid, $conf, $vm_volids);
2082 $changes = $upu || $upd;
2084 PVE
::LXC
::Config-
>write_config($vmid, $conf) if $changes && !$dryrun;
2087 if (defined($vmid)) {
2091 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2094 my $vmlist = config_list
();
2095 foreach my $vmid (keys %$vmlist) {
2099 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2106 # bash completion helper
2108 sub complete_os_templates
{
2109 my ($cmdname, $pname, $cvalue) = @_;
2111 my $cfg = PVE
::Storage
::config
();
2115 if ($cvalue =~ m/^([^:]+):/) {
2119 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
2120 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
2123 foreach my $id (keys %$data) {
2124 foreach my $item (@{$data->{$id}}) {
2125 push @$res, $item->{volid
} if defined($item->{volid
});
2132 my $complete_ctid_full = sub {
2135 my $idlist = vmstatus
();
2137 my $active_hash = list_active_containers
();
2141 foreach my $id (keys %$idlist) {
2142 my $d = $idlist->{$id};
2143 if (defined($running)) {
2144 next if $d->{template
};
2145 next if $running && !$active_hash->{$id};
2146 next if !$running && $active_hash->{$id};
2155 return &$complete_ctid_full();
2158 sub complete_ctid_stopped
{
2159 return &$complete_ctid_full(0);
2162 sub complete_ctid_running
{
2163 return &$complete_ctid_full(1);
2173 my $lxc = $conf->{lxc
};
2174 foreach my $entry (@$lxc) {
2175 my ($key, $value) = @$entry;
2176 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
2177 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
2178 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2179 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2180 push @$id_map, [$type, $ct, $host, $length];
2182 $rootuid = $host if $type eq 'u';
2183 $rootgid = $host if $type eq 'g';
2186 die "failed to parse idmap: $value\n";
2190 if (!@$id_map && $conf->{unprivileged
}) {
2191 # Should we read them from /etc/subuid?
2192 $id_map = [ ['u', '0', '100000', '65536'],
2193 ['g', '0', '100000', '65536'] ];
2194 $rootuid = $rootgid = 100000;
2197 return ($id_map, $rootuid, $rootgid);
2200 sub userns_command
{
2203 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2209 my ($vmid, $conf, $skiplock) = @_;
2211 # apply pending changes while starting
2212 if (scalar(keys %{$conf->{pending
}})) {
2213 my $storecfg = PVE
::Storage
::config
();
2214 PVE
::LXC
::Config-
>vmconfig_apply_pending($vmid, $conf, $storecfg);
2215 $conf = PVE
::LXC
::Config-
>load_config($vmid); # update/reload
2218 update_lxc_config
($vmid, $conf);
2220 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2223 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2227 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
2229 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-start', 1);
2230 eval { PVE
::Tools
::run_command
($cmd); };
2232 unlink $skiplock_flag_fn;
2235 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'post-start');
2240 # Helper to stop a container completely and make sure it has stopped completely.
2241 # This is necessary because we want the post-stop hook to have completed its
2242 # unmount-all step, but post-stop happens after lxc puts the container into the
2244 # $kill - if true it will always do an immediate hard-stop
2245 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2246 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2248 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2250 # Open the container's command socket.
2251 my $path = "\0/var/lib/lxc/$vmid/command";
2252 my $sock = IO
::Socket
::UNIX-
>new(
2253 Type
=> SOCK_STREAM
(),
2257 return if $! == ECONNREFUSED
; # The container is not running
2258 die "failed to open container ${vmid}'s command socket: $!\n";
2261 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2262 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-stop');
2264 # Stop the container:
2266 my $cmd = ['lxc-stop', '-n', $vmid];
2269 push @$cmd, '--kill'; # doesn't allow timeouts
2271 # lxc-stop uses a default timeout
2272 push @$cmd, '--nokill' if !$kill_after_timeout;
2274 if (defined($shutdown_timeout)) {
2275 push @$cmd, '--timeout', $shutdown_timeout;
2276 # Give run_command 5 extra seconds
2277 $shutdown_timeout += 5;
2281 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
2286 my $result = <$sock>;
2288 return if !defined $result; # monitor is gone and the ct has stopped.
2289 die "container did not stop\n";
2293 my ($vmid, $timeout, $skiplock) = @_;
2295 PVE
::LXC
::Config-
>lock_config($vmid, sub {
2296 return if !check_running
($vmid);
2298 vm_stop
($vmid, 0, $timeout, 1); # kill if timeout exceeds
2300 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2301 vm_start
($vmid, $conf);
2308 return PVE
::Tools
::run_fork
(sub {
2309 # Unshare the mount namespace
2310 die "failed to unshare mount namespace: $!\n"
2311 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
2312 PVE
::Tools
::run_command
(['mount', '--make-rslave', '/']);
2317 my $copy_volume = sub {
2318 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2320 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
2321 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
2323 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
2324 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
2330 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2331 push @mounted, $src;
2333 mountpoint_mount
($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2334 push @mounted, $dest;
2338 PVE
::Tools
::run_command
(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2339 '-aH', '--whole-file', '--sparse', '--one-file-system',
2340 "--bwlimit=$bwlimit", "$src/", $dest]);
2344 # Wait for rsync's children to release dest so that
2345 # consequent file operations (umount, remove) are possible
2346 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2348 foreach my $mount (reverse @mounted) {
2349 eval { PVE
::Tools
::run_command
(['/bin/umount', $mount], errfunc
=> sub{})};
2350 warn "Can't umount $mount\n" if $@;
2353 # If this fails they're used as mount points in a concurrent operation
2354 # (which should not happen but there's also no real need to get rid of them).
2361 # Should not be called after unsharing the mount namespace!
2363 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2365 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
2366 File
::Path
::make_path
("/var/lib/lxc/$vmid");
2367 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2368 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2370 # get id's for unprivileged container
2371 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
2373 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2374 # are visible in this namespace, otherwise the host only sees the empty
2375 # (not-mounted) directory.
2378 # Make sure $mp contains a correct size.
2379 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
2381 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
2383 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
2384 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
2385 chown($rootuid, $rootgid, $path);
2389 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2393 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
2394 if defined($new_volid);