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);
22 use PVE
::Tools
qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH AT_FDCWD);
25 use PVE
::AccessControl
;
27 use PVE
::Syscall
qw(:fsmount);
29 use PVE
::GuestHelpers
;
32 use Time
::HiRes qw
(gettimeofday
);
34 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
36 my $nodename = PVE
::INotify
::nodename
();
38 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
41 my $vmlist = PVE
::Cluster
::get_vmlist
();
43 return $res if !$vmlist || !$vmlist->{ids
};
44 my $ids = $vmlist->{ids
};
46 foreach my $vmid (keys %$ids) {
47 next if !$vmid; # skip CT0
48 my $d = $ids->{$vmid};
49 next if !$d->{node
} || $d->{node
} ne $nodename;
50 next if !$d->{type
} || $d->{type
} ne 'lxc';
51 $res->{$vmid} = { type
=> 'lxc', vmid
=> $vmid };
56 # container status helpers
58 sub list_active_containers
{
60 my $filename = "/proc/net/unix";
62 # similar test is used by lcxcontainers.c: list_active_containers
65 my $fh = IO
::File-
>new ($filename, "r");
68 while (defined(my $line = <$fh>)) {
69 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
71 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
82 # warning: this is slow
86 my $active_hash = list_active_containers
();
88 return 1 if defined($active_hash->{$vmid});
93 sub get_container_disk_usage
{
94 my ($vmid, $pid) = @_;
96 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
99 my $last_proc_vmid_stat;
101 my $parse_cpuacct_stat = sub {
102 my ($vmid, $unprivileged) = @_;
104 my $raw = read_cgroup_value
('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
108 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
118 our $vmstatus_return_properties = {
119 vmid
=> get_standard_option
('pve-vmid'),
121 description
=> "LXC Container status.",
123 enum
=> ['stopped', 'running'],
126 description
=> "Maximum memory in bytes.",
132 description
=> "Maximum SWAP memory in bytes.",
138 description
=> "Root disk size in bytes.",
144 description
=> "Container name.",
149 description
=> "Uptime.",
152 renderer
=> 'duration',
155 description
=> "Maximum usable CPUs.",
160 description
=> "The current config lock, if any.",
165 description
=> "The current configured tags, if any.",
174 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc', vmid
=> $opt_vmid }} : config_list
();
176 my $active_hash = list_active_containers
();
178 my $cpucount = $cpuinfo->{cpus
} || 1;
180 my $cdtime = gettimeofday
;
182 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
183 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
185 my $unprivileged = {};
187 foreach my $vmid (keys %$list) {
188 my $d = $list->{$vmid};
190 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
191 warn $@ if $@; # ignore errors (consider them stopped)
193 $d->{status
} = $active_hash->{$vmid} ?
'running' : 'stopped';
195 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
196 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
198 $unprivileged->{$vmid} = $conf->{unprivileged
};
200 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
201 $d->{name
} =~ s/[\s]//g;
203 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
204 $d->{cpus
} = $cpucount if !$d->{cpus
};
206 $d->{lock} = $conf->{lock} || '';
207 $d->{tags
} = $conf->{tags
} if defined($conf->{tags
});
210 my $res = get_container_disk_usage
($vmid, $d->{pid
});
211 $d->{disk
} = $res->{used
};
212 $d->{maxdisk
} = $res->{total
};
215 # use 4GB by default ??
216 if (my $rootfs = $conf->{rootfs
}) {
217 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($rootfs);
218 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
220 $d->{maxdisk
} = 4*1024*1024*1024;
226 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
227 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
238 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
239 $d->{lock} = $conf->{lock} if $conf->{lock};
242 foreach my $vmid (keys %$list) {
243 my $d = $list->{$vmid};
246 next if !$pid; # skip stopped CTs
248 my $proc_pid_stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
249 $d->{uptime
} = int(($uptime - $proc_pid_stat->{starttime
}) / $clock_ticks); # the method lxcfs uses
251 my $unpriv = $unprivileged->{$vmid};
253 if (-d
'/sys/fs/cgroup/memory') {
254 my $memory_stat = read_cgroup_list
('memory', $vmid, $unpriv, 'memory.stat');
255 my $mem_usage_in_bytes = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
257 $d->{mem
} = $mem_usage_in_bytes - $memory_stat->{total_cache
};
258 $d->{swap
} = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
264 if (-d
'/sys/fs/cgroup/blkio') {
265 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, 0, 'blkio.throttle.io_service_bytes', 1); # don't check if unpriv
266 my @bytes = split(/\n/, $blkio_bytes);
267 foreach my $byte (@bytes) {
268 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
269 $d->{diskread
} += $2 if $key eq 'Read';
270 $d->{diskwrite
} += $2 if $key eq 'Write';
278 if (-d
'/sys/fs/cgroup/cpuacct') {
279 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
281 my $used = $pstat->{utime} + $pstat->{stime
};
283 my $old = $last_proc_vmid_stat->{$vmid};
285 $last_proc_vmid_stat->{$vmid} = {
293 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
296 my $dutime = $used - $old->{used
};
298 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
299 $last_proc_vmid_stat->{$vmid} = {
305 $d->{cpu
} = $old->{cpu
};
312 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
314 foreach my $dev (keys %$netdev) {
315 next if $dev !~ m/^veth([1-9]\d*)i/;
317 my $d = $list->{$vmid};
321 $d->{netout
} += $netdev->{$dev}->{receive
};
322 $d->{netin
} += $netdev->{$dev}->{transmit
};
329 sub read_cgroup_list
($$$$) {
330 my ($group, $vmid, $unprivileged, $name) = @_;
332 my $content = read_cgroup_value
($group, $vmid, $unprivileged, $name, 1);
334 return { split(/\s+/, $content) };
337 sub read_cgroup_value
($$$$$) {
338 my ($group, $vmid, $unprivileged, $name, $full) = @_;
340 my $nsdir = $unprivileged ?
'' : 'ns/';
341 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
343 return PVE
::Tools
::file_get_contents
($path) if $full;
345 return PVE
::Tools
::file_read_firstline
($path);
348 sub write_cgroup_value
{
349 my ($group, $vmid, $name, $value) = @_;
351 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
352 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
356 sub find_lxc_console_pids
{
360 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
363 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
366 my @args = split(/\0/, $cmdline);
368 # search for lxc-console -n <vmid>
369 return if scalar(@args) != 3;
370 return if $args[1] ne '-n';
371 return if $args[2] !~ m/^\d+$/;
372 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
376 push @{$res->{$vmid}}, $pid;
388 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
390 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
392 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
399 sysopen(my $fd, "/proc/$pid", O_RDONLY
| O_DIRECTORY
)
400 or die "failed to open /proc/$pid pid fd\n";
407 # Find the pid and open:
408 my $pid = find_lxc_pid
($vmid);
409 my $fd = open_pid_fd
($pid);
412 my $pid2 = find_lxc_pid
($vmid);
414 return () if $pid != $pid2;
421 # Find the parent pid via proc and open it:
422 my $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
423 my $ppid = $stat->{ppid
} // die "failed to get parent pid\n";
425 my $fd = open_pid_fd
($ppid);
428 $stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
429 my $ppid2 = $stat->{ppid
} // die "failed to get parent pid for verification\n";
431 return () if $ppid != $ppid2;
435 # Note: we cannot use Net:IP, because that only allows strict
437 sub parse_ipv4_cidr
{
438 my ($cidr, $noerr) = @_;
440 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
441 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
444 return undef if $noerr;
446 die "unable to parse ipv4 address/mask\n";
449 sub get_cgroup_subsystems
{
452 my $data = PVE
::Tools
::file_get_contents
('/proc/self/cgroup');
453 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
456 $v1->{$_} = 1 foreach split(/,/, $type);
461 return wantarray ?
($v1, $v2) : $v1;
464 # Currently we do not need to create seccomp profile 'files' as the only
465 # choice our configuration actually allows is "with or without keyctl()",
466 # so we distinguish between using lxc's "default" seccomp profile and our
467 # added pve-userns.seccomp file.
469 # This returns a configuration line added to the raw lxc config.
470 sub make_seccomp_config
{
471 my ($conf, $unprivileged, $features) = @_;
472 # User-configured profile has precedence, note that the user's entry would
473 # be written 'after' this line anyway...
474 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.seccomp.profile')) {
475 # Warn the user if this conflicts with a feature:
476 if ($features->{keyctl
}) {
477 warn "explicitly configured lxc.seccomp.profile overrides the following settings: features:keyctl\n";
482 # Privileged containers keep using the default (which is already part of
483 # the files included via lxc.include, so we don't need to write it out,
484 # that way it stays admin-configurable via /usr/share/lxc/config/... as
486 return '' if !$unprivileged;
488 # Unprivileged containers will get keyctl() disabled by default as a
489 # workaround for systemd-networkd behavior. But we have an option to
490 # explicitly enable it:
491 return '' if $features->{keyctl
};
493 # Finally we're in an unprivileged container without `keyctl` set
494 # explicitly. We have a file prepared for this:
495 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
498 # Since lxc-3.0.2 we can have lxc generate a profile for the container
499 # automatically. The default should be equivalent to the old
500 # `lxc-container-default-cgns` profile.
502 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
503 # additional lines into the profile. We can use that to allow mounting specific
505 sub make_apparmor_config
{
506 my ($conf, $unprivileged, $features) = @_;
508 # user-configured profile has precedence, but first we go through our own
509 # code to figure out whether we should warn the user:
511 my $raw = "lxc.apparmor.profile = generated\n";
514 if ($features->{fuse
}) {
515 # For the informational warning:
516 push @profile_uses, 'features:fuse';
519 # There's lxc.apparmor.allow_nesting now, which will add the necessary
520 # apparmor lines, create an apparmor namespace for the container, but also
521 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
522 # lxcfs mounted over them, because that would prevent the container from
523 # mounting new instances of them for nested containers.
524 if ($features->{nesting
}) {
525 push @profile_uses, 'features:nesting';
526 $raw .= "lxc.apparmor.allow_nesting = 1\n"
528 # In the default profile in /etc/apparmor.d we patch this in because
529 # otherwise a container can for example run `chown` on /sys, breaking
530 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
531 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
532 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
533 # Preferably we could use the 'remount' flag but this does not sit well
534 # with apparmor_parser currently:
535 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
538 if (my $mount = $features->{mount
}) {
539 push @profile_uses, 'features:mount';
540 foreach my $fs (PVE
::Tools
::split_list
($mount)) {
541 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
547 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.apparmor.profile')) {
548 if (length(my $used = join(', ', @profile_uses))) {
549 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
557 sub update_lxc_config
{
558 my ($vmid, $conf) = @_;
560 my $dir = "/var/lib/lxc/$vmid";
562 if ($conf->{template
}) {
564 unlink "$dir/config";
571 die "missing 'arch' - internal error" if !$conf->{arch
};
572 $raw .= "lxc.arch = $conf->{arch}\n";
574 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
575 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
577 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
579 my $cfgpath = '/usr/share/lxc/config';
580 my $inc = "$cfgpath/$ostype.common.conf";
581 $inc ="$cfgpath/common.conf" if !-f
$inc;
582 $raw .= "lxc.include = $inc\n";
584 $inc = "$cfgpath/$ostype.userns.conf";
585 $inc = "$cfgpath/userns.conf" if !-f
$inc;
586 $raw .= "lxc.include = $inc\n";
589 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
591 $raw .= make_seccomp_config
($conf, $unprivileged, $features);
592 $raw .= make_apparmor_config
($conf, $unprivileged, $features);
593 if ($features->{fuse
}) {
594 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
595 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
598 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
599 # cannot be exposed to the container with r/w access (cgroup perms).
600 # When this is enabled mounts will still remain in the monitor's namespace
601 # after the container unmounted them and thus will not detach from their
602 # files while the container is running!
603 $raw .= "lxc.monitor.unshare = 1\n";
605 my $cgv1 = get_cgroup_subsystems
();
607 # Should we read them from /etc/subuid?
608 if ($unprivileged && !$custom_idmap) {
609 $raw .= "lxc.idmap = u 0 100000 65536\n";
610 $raw .= "lxc.idmap = g 0 100000 65536\n";
613 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
614 $raw .= "lxc.console.path = none\n";
615 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices
};
618 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
619 $raw .= "lxc.tty.max = $ttycount\n";
621 # some init scripts expect a linux terminal (turnkey).
622 $raw .= "lxc.environment = TERM=linux\n";
624 my $utsname = $conf->{hostname
} || "CT$vmid";
625 $raw .= "lxc.uts.name = $utsname\n";
627 if ($cgv1->{memory
}) {
628 my $memory = $conf->{memory
} || 512;
629 my $swap = $conf->{swap
} // 0;
631 my $lxcmem = int($memory*1024*1024);
632 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
634 my $lxcswap = int(($memory + $swap)*1024*1024);
635 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
639 if (my $cpulimit = $conf->{cpulimit
}) {
640 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
641 my $value = int(100000*$cpulimit);
642 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
645 my $shares = $conf->{cpuunits
} || 1024;
646 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
649 die "missing 'rootfs' configuration\n"
650 if !defined($conf->{rootfs
});
652 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
654 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
656 foreach my $k (sort keys %$conf) {
657 next if $k !~ m/^net(\d+)$/;
659 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
660 $raw .= "lxc.net.$ind.type = veth\n";
661 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
662 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
663 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
664 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu
});
667 if ($cgv1->{cpuset
}) {
669 if (my $lxcconf = $conf->{lxc
}) {
670 foreach my $entry (@$lxcconf) {
671 my ($k, $v) = @$entry;
672 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
677 my $cores = $conf->{cores
};
678 if (!$had_cpuset && $cores) {
679 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup('lxc', 'effective_cpus') };
680 $cpuset = PVE
::CpuSet-
>new_from_cgroup('', 'effective_cpus') if !$cpuset;
681 my @members = $cpuset->members();
682 while (scalar(@members) > $cores) {
683 my $randidx = int(rand(scalar(@members)));
684 $cpuset->delete($members[$randidx]);
685 splice(@members, $randidx, 1); # keep track of the changes
687 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
691 File
::Path
::mkpath
("$dir/rootfs");
693 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
696 # verify and cleanup nameserver list (replace \0 with ' ')
697 sub verify_nameserver_list
{
698 my ($nameserver_list) = @_;
701 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
702 PVE
::JSONSchema
::pve_verify_ip
($server);
706 return join(' ', @list);
709 sub verify_searchdomain_list
{
710 my ($searchdomain_list) = @_;
713 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
714 # todo: should we add checks for valid dns domains?
718 return join(' ', @list);
721 sub get_console_command
{
722 my ($vmid, $conf, $escapechar) = @_;
724 # '-1' as $escapechar disables keyboard escape sequence
725 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
727 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
730 if ($cmode eq 'console') {
731 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
732 push @$cmd, '-e', $escapechar if $escapechar;
733 } elsif ($cmode eq 'tty') {
734 push @$cmd, 'lxc-console', '-n', $vmid;
735 push @$cmd, '-e', $escapechar if $escapechar;
736 } elsif ($cmode eq 'shell') {
737 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
739 die "internal error";
745 sub get_primary_ips
{
748 # return data from net0
750 return undef if !defined($conf->{net0
});
751 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
753 my $ipv4 = $net->{ip
};
755 if ($ipv4 =~ /^(dhcp|manual)$/) {
761 my $ipv6 = $net->{ip6
};
763 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
770 return ($ipv4, $ipv6);
773 sub delete_mountpoint_volume
{
774 my ($storage_cfg, $vmid, $volume) = @_;
776 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
778 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
780 if ($vmid == $owner) {
781 PVE
::Storage
::vdisk_free
($storage_cfg, $volume);
783 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
787 sub destroy_lxc_container
{
788 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
790 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
791 my ($ms, $mountpoint) = @_;
792 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
795 rmdir "/var/lib/lxc/$vmid/rootfs";
796 unlink "/var/lib/lxc/$vmid/config";
797 rmdir "/var/lib/lxc/$vmid";
798 if (defined $replacement_conf) {
799 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
801 PVE
::LXC
::Config-
>destroy_config($vmid);
805 sub vm_stop_cleanup
{
806 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
808 return if $keepActive;
811 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
812 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
814 warn $@ if $@; # avoid errors - just warn
817 my $safe_num_ne = sub {
820 return 0 if !defined($a) && !defined($b);
821 return 1 if !defined($a);
822 return 1 if !defined($b);
827 my $safe_string_ne = sub {
830 return 0 if !defined($a) && !defined($b);
831 return 1 if !defined($a);
832 return 1 if !defined($b);
838 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
840 if ($newnet->{type
} ne 'veth') {
841 # for when there are physical interfaces
842 die "cannot update interface of type $newnet->{type}";
845 my $veth = "veth${vmid}i${netid}";
846 my $eth = $newnet->{name
};
848 if (my $oldnetcfg = $conf->{$opt}) {
849 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
851 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
852 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
854 PVE
::Network
::veth_delete
($veth);
855 delete $conf->{$opt};
856 PVE
::LXC
::Config-
>write_config($vmid, $conf);
858 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
861 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
862 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
863 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
865 if ($oldnet->{bridge
}) {
866 PVE
::Network
::tap_unplug
($veth);
867 foreach (qw(bridge tag firewall)) {
868 delete $oldnet->{$_};
870 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
871 PVE
::LXC
::Config-
>write_config($vmid, $conf);
874 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
875 # This includes the rate:
876 foreach (qw(bridge tag firewall rate)) {
877 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
879 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
880 # Rate can be applied on its own but any change above needs to
881 # include the rate in tap_plug since OVS resets everything.
882 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
883 $oldnet->{rate
} = $newnet->{rate
}
885 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
886 PVE
::LXC
::Config-
>write_config($vmid, $conf);
889 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
892 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
896 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
898 my $veth = "veth${vmid}i${netid}";
899 my $vethpeer = $veth . "p";
900 my $eth = $newnet->{name
};
902 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
903 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
905 # attach peer in container
906 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
907 PVE
::Tools
::run_command
($cmd);
909 # link up peer in container
910 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
911 PVE
::Tools
::run_command
($cmd);
913 my $done = { type
=> 'veth' };
914 foreach (qw(bridge tag firewall hwaddr name)) {
915 $done->{$_} = $newnet->{$_} if $newnet->{$_};
917 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
919 PVE
::LXC
::Config-
>write_config($vmid, $conf);
922 sub update_ipconfig
{
923 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
925 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
927 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
932 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
934 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
936 my $change_ip_config = sub {
937 my ($ipversion) = @_;
939 my $family_opt = "-$ipversion";
940 my $suffix = $ipversion == 4 ?
'' : $ipversion;
944 my $newip = $newnet->{$ip};
945 my $newgw = $newnet->{$gw};
946 my $oldip = $optdata->{$ip};
947 my $oldgw = $optdata->{$gw};
949 my $change_ip = &$safe_string_ne($oldip, $newip);
950 my $change_gw = &$safe_string_ne($oldgw, $newgw);
952 return if !$change_ip && !$change_gw;
954 # step 1: add new IP, if this fails we cancel
955 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
956 if ($change_ip && $is_real_ip) {
957 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
964 # step 2: replace gateway
965 # If this fails we delete the added IP and cancel.
966 # If it succeeds we save the config and delete the old IP, ignoring
967 # errors. The config is then saved.
968 # Note: 'ip route replace' can add
972 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
973 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
975 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
979 # the route was not replaced, the old IP is still available
980 # rollback (delete new IP) and cancel
982 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
983 warn $@ if $@; # no need to die here
988 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
989 # if the route was not deleted, the guest might have deleted it manually
993 if ($oldgw && $oldip && !PVE
::Network
::is_ip_in_cidr
($oldgw, $oldip)) {
994 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
995 # warn if the route was deleted manually
1000 # from this point on we save the configuration
1001 # step 3: delete old IP ignoring errors
1002 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
1003 # We need to enable promote_secondaries, otherwise our newly added
1004 # address will be removed along with the old one.
1007 if ($ipversion == 4) {
1008 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
1009 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1010 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1012 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1014 warn $@ if $@; # no need to die here
1016 if ($ipversion == 4) {
1017 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1021 foreach my $property ($ip, $gw) {
1022 if ($newnet->{$property}) {
1023 $optdata->{$property} = $newnet->{$property};
1025 delete $optdata->{$property};
1028 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
1029 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1030 $lxc_setup->setup_network($conf);
1033 &$change_ip_config(4);
1034 &$change_ip_config(6);
1038 my $open_namespace = sub {
1039 my ($vmid, $pid, $kind) = @_;
1040 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1041 or die "failed to open $kind namespace of container $vmid: $!\n";
1045 my $enter_namespace = sub {
1046 my ($vmid, $pid, $kind, $type) = @_;
1047 my $fd = $open_namespace->($vmid, $pid, $kind);
1048 PVE
::Tools
::setns
(fileno($fd), $type)
1049 or die "failed to enter $kind namespace of container $vmid: $!\n";
1053 my $get_container_namespace = sub {
1054 my ($vmid, $pid, $kind) = @_;
1057 if (!defined($pid)) {
1058 # Pin the pid while we're grabbing its stuff from /proc
1059 ($pid, $pidfd) = open_lxc_pid
($vmid)
1060 or die "failed to open pidfd of container $vmid\'s init process\n";
1063 return $open_namespace->($vmid, $pid, $kind);
1066 my $do_syncfs = sub {
1067 my ($vmid, $pid, $socket) = @_;
1069 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
1071 # Tell the parent process to start reading our /proc/mounts
1072 print {$socket} "go\n";
1075 # Receive /proc/self/mounts
1076 my $mountdata = do { local $/ = undef; <$socket> };
1079 # Now sync all mountpoints...
1080 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
1081 foreach my $mp (@$mounts) {
1082 my ($what, $dir, $fs) = @$mp;
1083 next if $fs eq 'fuse.lxcfs';
1084 eval { PVE
::Tools
::sync_mountpoint
($dir); };
1089 sub sync_container_namespace
{
1091 my $pid = find_lxc_pid
($vmid);
1093 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1094 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
1095 or die "failed to create socketpair: $!\n";
1098 die "fork failed: $!\n" if !defined($child);
1103 &$do_syncfs($vmid, $pid, $cfd);
1113 die "failed to enter container namespace\n" if $go ne "go\n";
1115 open my $mounts, '<', "/proc/$child/mounts"
1116 or die "failed to open container's /proc/mounts: $!\n";
1117 my $mountdata = do { local $/ = undef; <$mounts> };
1119 print {$pfd} $mountdata;
1122 while (waitpid($child, 0) != $child) {}
1123 die "failed to sync container namespace\n" if $? != 0;
1126 sub template_create
{
1127 my ($vmid, $conf) = @_;
1129 my $storecfg = PVE
::Storage
::config
();
1131 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1132 my ($ms, $mountpoint) = @_;
1134 my $volid = $mountpoint->{volume
};
1136 die "Template feature is not available for '$volid'\n"
1137 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1140 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1141 my ($ms, $mountpoint) = @_;
1143 my $volid = $mountpoint->{volume
};
1145 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
1147 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
1148 $mountpoint->{volume
} = $template_volid;
1149 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1152 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1155 sub check_ct_modify_config_perm
{
1156 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
1158 return 1 if $authuser eq 'root@pam';
1161 my ($opt, $delete) = @_;
1162 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1163 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1164 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1165 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1167 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
1168 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
1169 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
1170 if $data->{type
} ne 'volume';
1171 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1172 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1173 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1174 $opt eq 'searchdomain' || $opt eq 'hostname') {
1175 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1176 } elsif ($opt eq 'features') {
1177 # For now this is restricted to root@pam
1178 raise_perm_exc
("changing feature flags is only allowed for root\@pam");
1179 } elsif ($opt eq 'hookscript') {
1180 # For now this is restricted to root@pam
1181 raise_perm_exc
("changing the hookscript is only allowed for root\@pam");
1183 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1187 foreach my $opt (keys %$newconf) {
1190 foreach my $opt (@$delete) {
1198 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1200 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1201 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1205 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
1206 my ($ms, $mountpoint) = @_;
1208 my $volid = $mountpoint->{volume
};
1209 my $mount = $mountpoint->{mp
};
1211 return if !$volid || !$mount;
1213 my $mount_path = "$rootdir/$mount";
1214 $mount_path =~ s!/+!/!g;
1216 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1219 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
1231 return $res; # tell caller if (some) umounts failed for the noerr case
1235 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1237 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1238 File
::Path
::make_path
($rootdir);
1240 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1241 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
1243 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1246 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1247 my ($ms, $mountpoint) = @_;
1249 $mountpoint->{ro
} = 0 if $ignore_ro;
1251 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1255 warn "mounting container failed\n";
1256 umount_all
($vmid, $storage_cfg, $conf, 1);
1264 sub mountpoint_mount_path
{
1265 my ($mountpoint, $storage_cfg, $snapname) = @_;
1267 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1275 if ($line =~ m
@^(/dev/loop\d
+):@) {
1279 my $cmd = ['losetup', '--associated', $path];
1280 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1284 # Run a function with a file attached to a loop device.
1285 # The loop device is always detached afterwards (or set to autoclear).
1286 # Returns the loop device.
1287 sub run_with_loopdev
{
1288 my ($func, $file, $readonly) = @_;
1289 my $device = query_loopdev
($file);
1290 # Try to reuse an existing device
1292 # We assume that whoever setup the loop device is responsible for
1300 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1310 push @$losetup_cmd, '-r' if $readonly;
1311 PVE
::Tools
::run_command
($losetup_cmd, outfunc
=> $parser);
1312 die "failed to setup loop device for $file\n" if !$device;
1313 eval { &$func($device); };
1315 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1320 # In scalar mode: returns a file handle to the deepest directory node.
1321 # In list context: returns a list of:
1322 # * the deepest directory node
1323 # * the 2nd deepest directory (parent of the above)
1324 # * directory name of the last directory
1325 # So that the path $2/$3 should lead to $1 afterwards.
1326 sub walk_tree_nofollow
($$$;$$) {
1327 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1329 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1330 or die "failed to open start directory $start: $!\n";
1332 return walk_tree_nofollow_fd
($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1336 sub walk_tree_nofollow_fd
($$$$;$$) {
1337 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1339 # splitdir() returns '' for empty components including the leading /
1340 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1343 my $dir = $start_dirname;
1344 my $last_component = undef;
1346 foreach my $component (@comps) {
1347 $dir .= "/$component";
1348 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1351 # failed, check for symlinks and try to create the path
1352 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1353 die "cannot open directory $dir: $!\n" if !$mkdir;
1355 # We don't check for errors on mkdirat() here and just try to
1356 # openat() again, since at least one error (EEXIST) is an
1357 # expected possibility if multiple containers start
1358 # simultaneously. If someone else injects a symlink now then
1359 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1360 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1362 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1363 die "failed to create path: $dir: $!\n" if !$next;
1365 PVE
::Tools
::fchownat
(fileno($next), '', $rootuid, $rootgid, PVE
::Tools
::AT_EMPTY_PATH
)
1366 if defined($rootuid) && defined($rootgid);
1369 close $second if defined($last_component) && $second != $start_fd;
1370 $last_component = $component;
1375 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1376 close $second if defined($last_component) && $second != $start_fd;
1380 # To guard against symlink attack races against other currently running
1381 # containers with shared recursive bind mount hierarchies we prepare a
1382 # directory handle for the directory we're mounting over to verify the
1383 # mountpoint afterwards.
1384 sub __bindmount_prepare
{
1385 my ($hostroot, $dir) = @_;
1386 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1390 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1391 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1392 # we intended to bind mount.
1393 sub __bindmount_verify
{
1394 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1397 # Open the mount point path coming from the parent directory since the
1398 # filehandle we would have gotten as first result of walk_tree_nofollow
1399 # earlier is still a handle to the underlying directory instead of the
1401 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1402 die "failed to open mount point: $!\n" if !$destdh;
1405 # no separate function because 99% of the time it's the wrong thing to use.
1406 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1407 die "failed to mark bind mount read only\n";
1409 die "read-only check failed: $!\n" if $! != EROFS
;
1412 # For the rootfs we don't have a parentfd so we open the path directly.
1413 # Note that this means bindmounting any prefix of the host's
1414 # /var/lib/lxc/$vmid path into another container is considered a grave
1416 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1417 die "failed to open mount point: $!\n" if !$destdh;
1420 my ($srcdev, $srcinode) = stat($srcdh);
1421 my ($dstdev, $dstinode) = stat($destdh);
1425 return ($srcdev == $dstdev && $srcinode == $dstinode);
1428 # Perform the actual bind mounting:
1429 sub __bindmount_do
{
1430 my ($dir, $dest, $ro, @extra_opts) = @_;
1431 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1433 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1435 warn "bindmount error\n";
1436 # don't leave writable bind-mounts behind...
1437 PVE
::Tools
::run_command
(['umount', $dest]);
1444 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1446 my $srcdh = __bindmount_prepare
('/', $dir);
1448 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1450 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1451 PVE
::Tools
::run_command
(['umount', $dest]);
1452 die "detected mount path change at: $dir\n";
1456 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1457 # from $rootdir and $mount and walk the path from $rootdir to the final
1458 # directory to check for symlinks.
1459 sub __mount_prepare_rootdir
{
1460 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1461 $rootdir =~ s!/+!/!g;
1462 $rootdir =~ s!/+$!!;
1463 my $mount_path = "$rootdir/$mount";
1464 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1, $rootuid, $rootgid);
1465 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1468 # use $rootdir = undef to just return the corresponding mount path
1469 sub mountpoint_mount
{
1470 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1471 return __mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1474 sub mountpoint_stage
{
1475 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1476 my ($path, $loop, $dev) =
1477 __mountpoint_mount
($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1479 if (!defined($path)) {
1480 return undef if $! == ENOSYS
;
1481 die "failed to mount subvolume: $!\n";
1484 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1485 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1488 my $fd = PVE
::Tools
::open_tree
(&AT_FDCWD
, $stage_dir, &OPEN_TREE_CLOEXEC
| &OPEN_TREE_CLONE
)
1489 or die "open_tree() on mount point failed: $!\n";
1491 return wantarray ?
($path, $loop, $dev, $fd) : $fd;
1494 sub mountpoint_insert_staged
{
1495 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1497 if (!defined($rootdir_fd)) {
1498 sysopen($rootdir_fd, '.', O_PATH
| O_DIRECTORY
)
1499 or die "failed to open '.': $!\n";
1502 my $dest_fd = walk_tree_nofollow_fd
('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1504 PVE
::Tools
::move_mount
(
1509 &MOVE_MOUNT_F_EMPTY_PATH
| &MOVE_MOUNT_T_EMPTY_PATH
,
1510 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1513 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1514 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1515 # Note that if the kernel does not support the new mount API, this will not perform any action
1516 # and return `undef` with $! = ENOSYS.
1517 sub __mountpoint_mount
{
1518 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1520 if (defined($stage_mount) && !PVE
::LXC
::Tools
::can_use_new_mount_api
()) {
1525 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1526 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1527 # which we use in __bindmount_verify()!
1528 my $mount = $stage_mount ?
'/': $mountpoint->{mp
};
1530 my $volid = $mountpoint->{volume
};
1531 my $type = $mountpoint->{type
};
1532 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1535 return if !$volid || !$mount;
1540 my ($mpfd, $parentfd, $last_dir);
1542 if (defined($rootdir)) {
1543 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1544 __mount_prepare_rootdir
($rootdir, $mount, $rootuid, $rootgid);
1547 if (defined($stage_mount)) {
1548 $mount_path = $rootdir;
1551 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1553 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1557 if (my $mountopts = $mountpoint->{mountoptions
}) {
1558 my @opts = split(/;/, $mountpoint->{mountoptions
});
1559 push @$optlist, grep { PVE
::LXC
::Config
::is_valid_mount_option
($_) } @opts;
1562 my $acl = $mountpoint->{acl
};
1563 if (defined($acl)) {
1564 push @$optlist, ($acl ?
'acl' : 'noacl');
1567 my $optstring = join(',', @$optlist);
1568 my $readonly = $mountpoint->{ro
};
1571 @extra_opts = ('-o', $optstring) if $optstring;
1575 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1577 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid, $snapname);
1579 $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname) if !defined($path);
1581 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1582 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1584 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1586 if ($format eq 'subvol') {
1589 if ($scfg->{type
} eq 'zfspool') {
1590 my $path_arg = $path;
1591 $path_arg =~ s!^/+!!;
1592 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1594 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1597 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1598 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1599 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1600 $name .= "\@$snapname" if defined($snapname);
1601 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1603 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1604 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1607 return wantarray ?
($path, 0, undef) : $path;
1608 } elsif ($format eq 'raw' || $format eq 'iso') {
1609 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1610 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1611 # Our autodev hook expects the /dev/dm-* device currently
1612 # and will create the /dev/mapper symlink accordingly
1613 $path = Cwd
::realpath
($path);
1614 die "failed to get device path\n" if !$path;
1615 ($path) = ($path =~ /^(.*)$/s); #untaint
1619 if ($format eq 'iso') {
1620 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1621 } elsif ($isBase || defined($snapname)) {
1622 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1625 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1627 push @extra_opts, '-o', 'ro' if $readonly;
1628 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1632 my $use_loopdev = 0;
1633 if ($scfg->{path
}) {
1634 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1636 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1637 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1638 $mounted_dev = $path;
1641 die "unsupported storage type '$scfg->{type}'\n";
1643 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1645 die "unsupported image format '$format'\n";
1647 } elsif ($type eq 'device') {
1648 push @extra_opts, '-o', 'ro' if $readonly;
1649 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1650 # See the NOTE above about devicemapper canonicalization
1651 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1652 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1653 return wantarray ?
($volid, 0, $devpath) : $volid;
1654 } elsif ($type eq 'bind') {
1655 die "directory '$volid' does not exist\n" if ! -d
$volid;
1656 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1657 warn "cannot enable quota control for bind mounts\n" if $quota;
1658 return wantarray ?
($volid, 0, undef) : $volid;
1661 die "unsupported storage";
1664 sub mountpoint_hotplug
($$$) {
1665 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1667 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1669 # We do the rest in a fork with an unshared mount namespace, because:
1670 # -) change our papparmor profile to that of /usr/bin/lxc-start
1671 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1672 # container's namespace, then mount it.
1674 PVE
::Tools
::run_fork
(sub {
1675 # Pin the container pid longer, we also need to get its monitor/parent:
1676 my ($ct_pid, $ct_pidfd) = open_lxc_pid
($vmid)
1677 or die "failed to open pidfd of container $vmid\'s init process\n";
1679 my ($monitor_pid, $monitor_pidfd) = open_ppid
($ct_pid)
1680 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1682 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1683 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1685 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1686 # profile to lower our privileges to the same level we have in the start hook:
1687 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY
)
1688 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1689 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1692 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1693 # namespace for it to remain active there since the container will be able to unmount
1694 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1696 PVE
::Tools
::setns
(fileno($monitor_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1698 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1700 my $dir = get_staging_mount_path
($opt);
1702 # Now switch our apparmor profile before mounting:
1703 my $data = 'changeprofile /usr/bin/lxc-start';
1704 if (syswrite($aa_fd, $data, length($data)) != length($data)) {
1705 die "failed to change apparmor profile: $!\n";
1707 # Check errors on close as well:
1709 or die "failed to change apparmor profile (close() failed): $!\n";
1711 my $mount_fd = mountpoint_stage
($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1713 PVE
::Tools
::setns
(fileno($ct_mnt_ns), PVE
::Tools
::CLONE_NEWNS
);
1715 or die "failed to change root directory within the container's mount namespace: $!\n";
1717 mountpoint_insert_staged
($mount_fd, undef, $mp->{mp
}, $opt, $rootuid, $rootgid);
1721 # Create a directory in the mountpoint staging tempfs.
1722 sub get_staging_mount_path
($) {
1725 my $target = get_staging_tempfs
() . "/$opt";
1726 if (!mkdir($target) && $! != EEXIST
) {
1727 die "failed to create directory $target: $!\n";
1733 # Mount /run/pve/mountpoints as tmpfs
1734 sub get_staging_tempfs
() {
1735 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
1737 my $target = '/var/lib/lxc/.pve-staged-mounts';
1738 if (!mkdir($target)) {
1739 return $target if $! == EEXIST
;
1740 die "failed to create directory $target: $!\n";
1743 PVE
::Tools
::mount
("none", $target, 'tmpfs', 0, "size=8k,mode=755")
1744 or die "failed to mount $target as tmpfs: $!\n";
1750 my ($dev, $rootuid, $rootgid) = @_;
1752 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1753 '-E', "root_owner=$rootuid:$rootgid",
1758 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1760 if ($volid =~ m!^/dev/.+!) {
1765 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1767 die "cannot format volume '$volid' with no storage\n" if !$storage;
1769 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1771 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid);
1773 $path = PVE
::Storage
::path
($storage_cfg, $volid) if !defined($path);
1775 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1776 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1778 die "cannot format volume '$volid' (format == $format)\n"
1779 if $format ne 'raw';
1781 mkfs
($path, $rootuid, $rootgid);
1785 my ($storecfg, $vollist) = @_;
1787 foreach my $volid (@$vollist) {
1788 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1794 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1796 my $needs_chown = 0;
1799 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1800 # fixme: use better naming ct-$vmid-disk-X.raw?
1804 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs' || $scfg->{type
} eq 'cifs' ) {
1806 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1810 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1814 } elsif ($scfg->{type
} eq 'zfspool') {
1816 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1819 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1821 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1824 } elsif ($scfg->{type
} eq 'rbd') {
1826 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1829 die "unable to create containers on storage type '$scfg->{type}'\n";
1831 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1834 # in case formatting got interrupted:
1835 if (defined($volid)) {
1836 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1842 return ($volid, $needs_chown);
1845 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1847 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
1852 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1853 my $chown_vollist = [];
1855 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1856 my ($ms, $mountpoint) = @_;
1858 my $volid = $mountpoint->{volume
};
1859 my $mp = $mountpoint->{mp
};
1861 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1863 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1864 my ($storeid, $size_gb) = ($1, $2);
1866 my $size_kb = int(${size_gb
}*1024) * 1024;
1868 my $needs_chown = 0;
1869 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1870 push @$chown_vollist, $volid if $needs_chown;
1871 push @$vollist, $volid;
1872 $mountpoint->{volume
} = $volid;
1873 $mountpoint->{size
} = $size_kb * 1024;
1875 $conf->{pending
}->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1877 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1880 # use specified/existing volid/dir/device
1881 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1885 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1886 foreach my $volid (@$chown_vollist) {
1887 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1888 chown($rootuid, $rootgid, $path);
1890 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1892 # free allocated images on error
1894 destroy_disks
($storecfg, $vollist);
1900 sub update_disksize
{
1901 my ($vmid, $conf, $all_volumes) = @_;
1904 my $prefix = "CT $vmid:";
1906 my $update_mp = sub {
1907 my ($key, $mp, @param) = @_;
1908 my $size = $all_volumes->{$mp->{volume
}}->{size
} // 0;
1910 if (!defined($mp->{size
}) || $size != $mp->{size
}) {
1912 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1913 $mp->{size
} = $size;
1914 my $nomp = 1 if ($key eq 'rootfs');
1915 $conf->{$key} = PVE
::LXC
::Config-
>print_ct_mountpoint($mp, $nomp);
1919 PVE
::LXC
::Config-
>foreach_mountpoint($conf, $update_mp);
1925 my ($vmid, $conf, $all_volumes) = @_;
1928 my $prefix = "CT $vmid:";
1930 # Note: it is allowed to define multiple storage entries with the same path
1931 # (alias), so we need to check both 'volid' and real 'path' (two different
1932 # volid can point to the same path).
1934 # used and unused disks
1938 foreach my $opt (keys %$conf) {
1939 next if ($opt !~ m/^unused\d+$/);
1940 my $vol = $all_volumes->{$conf->{$opt}};
1941 $refpath->{$vol->{path
}} = $vol->{volid
};
1944 foreach my $key (keys %$all_volumes) {
1945 my $vol = $all_volumes->{$key};
1946 my $in_use = PVE
::LXC
::Config-
>is_volume_in_use($conf, $vol->{volid
});
1947 my $path = $vol->{path
};
1950 $refpath->{$path} = $key;
1951 delete $orphans->{$path};
1953 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
1954 $orphans->{$path} = $key;
1959 for my $key (keys %$orphans) {
1960 my $disk = $orphans->{$key};
1961 my $unused = PVE
::LXC
::Config-
>add_unused_volume($conf, $disk);
1965 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
1973 my ($cfg, $vmid) = @_;
1975 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid);
1977 my $all_volumes = {};
1978 foreach my $storeid (keys %$info) {
1979 foreach my $item (@{$info->{$storeid}}) {
1980 my $volid = $item->{volid
};
1981 next if !($volid && $item->{size
});
1982 $item->{path
} = PVE
::Storage
::path
($cfg, $volid);
1983 $all_volumes->{$volid} = $item;
1987 return $all_volumes;
1991 my ($vmid, $nolock, $dryrun) = @_;
1993 my $cfg = PVE
::Storage
::config
();
1995 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
1996 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
1997 foreach my $stor (keys %{$cfg->{ids
}}) {
1998 delete($cfg->{ids
}->{$stor}) if !$cfg->{ids
}->{$stor}->{content
}->{rootdir
};
2001 print "rescan volumes...\n";
2002 my $all_volumes = scan_volids
($cfg, $vmid);
2004 my $updatefn = sub {
2008 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2010 PVE
::LXC
::Config-
>check_lock($conf);
2013 foreach my $volid (keys %$all_volumes) {
2014 my $info = $all_volumes->{$volid};
2015 $vm_volids->{$volid} = $info if $info->{vmid
} == $vmid;
2018 my $upu = update_unused
($vmid, $conf, $vm_volids);
2019 my $upd = update_disksize
($vmid, $conf, $vm_volids);
2020 $changes = $upu || $upd;
2022 PVE
::LXC
::Config-
>write_config($vmid, $conf) if $changes && !$dryrun;
2025 if (defined($vmid)) {
2029 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2032 my $vmlist = config_list
();
2033 foreach my $vmid (keys %$vmlist) {
2037 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
2044 # bash completion helper
2046 sub complete_os_templates
{
2047 my ($cmdname, $pname, $cvalue) = @_;
2049 my $cfg = PVE
::Storage
::config
();
2053 if ($cvalue =~ m/^([^:]+):/) {
2057 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
2058 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
2061 foreach my $id (keys %$data) {
2062 foreach my $item (@{$data->{$id}}) {
2063 push @$res, $item->{volid
} if defined($item->{volid
});
2070 my $complete_ctid_full = sub {
2073 my $idlist = vmstatus
();
2075 my $active_hash = list_active_containers
();
2079 foreach my $id (keys %$idlist) {
2080 my $d = $idlist->{$id};
2081 if (defined($running)) {
2082 next if $d->{template
};
2083 next if $running && !$active_hash->{$id};
2084 next if !$running && $active_hash->{$id};
2093 return &$complete_ctid_full();
2096 sub complete_ctid_stopped
{
2097 return &$complete_ctid_full(0);
2100 sub complete_ctid_running
{
2101 return &$complete_ctid_full(1);
2111 my $lxc = $conf->{lxc
};
2112 foreach my $entry (@$lxc) {
2113 my ($key, $value) = @$entry;
2114 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
2115 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
2116 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2117 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2118 push @$id_map, [$type, $ct, $host, $length];
2120 $rootuid = $host if $type eq 'u';
2121 $rootgid = $host if $type eq 'g';
2124 die "failed to parse idmap: $value\n";
2128 if (!@$id_map && $conf->{unprivileged
}) {
2129 # Should we read them from /etc/subuid?
2130 $id_map = [ ['u', '0', '100000', '65536'],
2131 ['g', '0', '100000', '65536'] ];
2132 $rootuid = $rootgid = 100000;
2135 return ($id_map, $rootuid, $rootgid);
2138 sub userns_command
{
2141 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2147 my ($vmid, $conf, $skiplock) = @_;
2149 # apply pending changes while starting
2150 if (scalar(keys %{$conf->{pending
}})) {
2151 my $storecfg = PVE
::Storage
::config
();
2152 PVE
::LXC
::Config-
>vmconfig_apply_pending($vmid, $conf, $storecfg);
2153 $conf = PVE
::LXC
::Config-
>load_config($vmid); # update/reload
2156 update_lxc_config
($vmid, $conf);
2158 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2161 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2165 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
2167 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-start', 1);
2168 eval { PVE
::Tools
::run_command
($cmd); };
2170 unlink $skiplock_flag_fn;
2173 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'post-start');
2178 # Helper to stop a container completely and make sure it has stopped completely.
2179 # This is necessary because we want the post-stop hook to have completed its
2180 # unmount-all step, but post-stop happens after lxc puts the container into the
2182 # $kill - if true it will always do an immediate hard-stop
2183 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2184 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2186 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2188 # Open the container's command socket.
2189 my $path = "\0/var/lib/lxc/$vmid/command";
2190 my $sock = IO
::Socket
::UNIX-
>new(
2191 Type
=> SOCK_STREAM
(),
2195 return if $! == ECONNREFUSED
; # The container is not running
2196 die "failed to open container ${vmid}'s command socket: $!\n";
2199 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2200 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-stop');
2202 # Stop the container:
2204 my $cmd = ['lxc-stop', '-n', $vmid];
2207 push @$cmd, '--kill'; # doesn't allow timeouts
2209 # lxc-stop uses a default timeout
2210 push @$cmd, '--nokill' if !$kill_after_timeout;
2212 if (defined($shutdown_timeout)) {
2213 push @$cmd, '--timeout', $shutdown_timeout;
2214 # Give run_command 5 extra seconds
2215 $shutdown_timeout += 5;
2219 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
2224 my $result = <$sock>;
2226 return if !defined $result; # monitor is gone and the ct has stopped.
2227 die "container did not stop\n";
2231 my ($vmid, $timeout, $skiplock) = @_;
2233 PVE
::LXC
::Config-
>lock_config($vmid, sub {
2234 return if !check_running
($vmid);
2236 vm_stop
($vmid, 0, $timeout, 1); # kill if timeout exceeds
2238 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2239 vm_start
($vmid, $conf);
2246 return PVE
::Tools
::run_fork
(sub {
2247 # Unshare the mount namespace
2248 die "failed to unshare mount namespace: $!\n"
2249 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
2250 PVE
::Tools
::run_command
(['mount', '--make-rslave', '/']);
2255 my $copy_volume = sub {
2256 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2258 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
2259 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
2261 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
2262 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
2268 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2269 push @mounted, $src;
2271 mountpoint_mount
($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2272 push @mounted, $dest;
2276 PVE
::Tools
::run_command
(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2277 '-aH', '--whole-file', '--sparse', '--one-file-system',
2278 "--bwlimit=$bwlimit", "$src/", $dest]);
2282 # Wait for rsync's children to release dest so that
2283 # consequent file operations (umount, remove) are possible
2284 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2286 foreach my $mount (reverse @mounted) {
2287 eval { PVE
::Tools
::run_command
(['/bin/umount', $mount], errfunc
=> sub{})};
2288 warn "Can't umount $mount\n" if $@;
2291 # If this fails they're used as mount points in a concurrent operation
2292 # (which should not happen but there's also no real need to get rid of them).
2299 # Should not be called after unsharing the mount namespace!
2301 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2303 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
2304 File
::Path
::make_path
("/var/lib/lxc/$vmid");
2305 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2306 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2308 # get id's for unprivileged container
2309 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
2311 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2312 # are visible in this namespace, otherwise the host only sees the empty
2313 # (not-mounted) directory.
2316 # Make sure $mp contains a correct size.
2317 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
2319 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
2321 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
2322 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
2323 chown($rootuid, $rootgid, $path);
2327 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2331 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
2332 if defined($new_volid);