13 use Fcntl
qw(O_RDONLY O_NOFOLLOW O_DIRECTORY);
14 use Errno
qw(ELOOP ENOTDIR EROFS ECONNREFUSED ENOSYS);
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.",
169 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc', vmid
=> $opt_vmid }} : config_list
();
171 my $active_hash = list_active_containers
();
173 my $cpucount = $cpuinfo->{cpus
} || 1;
175 my $cdtime = gettimeofday
;
177 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
178 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
180 my $unprivileged = {};
182 foreach my $vmid (keys %$list) {
183 my $d = $list->{$vmid};
185 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
186 warn $@ if $@; # ignore errors (consider them stopped)
188 $d->{status
} = $active_hash->{$vmid} ?
'running' : 'stopped';
190 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
191 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
193 $unprivileged->{$vmid} = $conf->{unprivileged
};
195 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
196 $d->{name
} =~ s/[\s]//g;
198 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
199 $d->{cpus
} = $cpucount if !$d->{cpus
};
201 $d->{lock} = $conf->{lock} || '';
204 my $res = get_container_disk_usage
($vmid, $d->{pid
});
205 $d->{disk
} = $res->{used
};
206 $d->{maxdisk
} = $res->{total
};
209 # use 4GB by default ??
210 if (my $rootfs = $conf->{rootfs
}) {
211 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($rootfs);
212 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
214 $d->{maxdisk
} = 4*1024*1024*1024;
220 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
221 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
232 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
233 $d->{lock} = $conf->{lock} if $conf->{lock};
236 foreach my $vmid (keys %$list) {
237 my $d = $list->{$vmid};
240 next if !$pid; # skip stopped CTs
242 my $proc_pid_stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
243 $d->{uptime
} = int(($uptime - $proc_pid_stat->{starttime
}) / $clock_ticks); # the method lxcfs uses
245 my $unpriv = $unprivileged->{$vmid};
247 if (-d
'/sys/fs/cgroup/memory') {
248 my $memory_stat = read_cgroup_list
('memory', $vmid, $unpriv, 'memory.stat');
249 my $mem_usage_in_bytes = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
251 $d->{mem
} = $mem_usage_in_bytes - $memory_stat->{total_cache
};
252 $d->{swap
} = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
258 if (-d
'/sys/fs/cgroup/blkio') {
259 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, 0, 'blkio.throttle.io_service_bytes', 1); # don't check if unpriv
260 my @bytes = split(/\n/, $blkio_bytes);
261 foreach my $byte (@bytes) {
262 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
263 $d->{diskread
} += $2 if $key eq 'Read';
264 $d->{diskwrite
} += $2 if $key eq 'Write';
272 if (-d
'/sys/fs/cgroup/cpuacct') {
273 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
275 my $used = $pstat->{utime} + $pstat->{stime
};
277 my $old = $last_proc_vmid_stat->{$vmid};
279 $last_proc_vmid_stat->{$vmid} = {
287 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
290 my $dutime = $used - $old->{used
};
292 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
293 $last_proc_vmid_stat->{$vmid} = {
299 $d->{cpu
} = $old->{cpu
};
306 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
308 foreach my $dev (keys %$netdev) {
309 next if $dev !~ m/^veth([1-9]\d*)i/;
311 my $d = $list->{$vmid};
315 $d->{netout
} += $netdev->{$dev}->{receive
};
316 $d->{netin
} += $netdev->{$dev}->{transmit
};
323 sub read_cgroup_list
($$$$) {
324 my ($group, $vmid, $unprivileged, $name) = @_;
326 my $content = read_cgroup_value
($group, $vmid, $unprivileged, $name, 1);
328 return { split(/\s+/, $content) };
331 sub read_cgroup_value
($$$$$) {
332 my ($group, $vmid, $unprivileged, $name, $full) = @_;
334 my $nsdir = $unprivileged ?
'' : 'ns/';
335 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
337 return PVE
::Tools
::file_get_contents
($path) if $full;
339 return PVE
::Tools
::file_read_firstline
($path);
342 sub write_cgroup_value
{
343 my ($group, $vmid, $name, $value) = @_;
345 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
346 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
350 sub find_lxc_console_pids
{
354 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
357 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
360 my @args = split(/\0/, $cmdline);
362 # search for lxc-console -n <vmid>
363 return if scalar(@args) != 3;
364 return if $args[1] ne '-n';
365 return if $args[2] !~ m/^\d+$/;
366 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
370 push @{$res->{$vmid}}, $pid;
382 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
384 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
386 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
391 # Note: we cannot use Net:IP, because that only allows strict
393 sub parse_ipv4_cidr
{
394 my ($cidr, $noerr) = @_;
396 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
397 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
400 return undef if $noerr;
402 die "unable to parse ipv4 address/mask\n";
405 sub get_cgroup_subsystems
{
408 my $data = PVE
::Tools
::file_get_contents
('/proc/self/cgroup');
409 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
412 $v1->{$_} = 1 foreach split(/,/, $type);
417 return wantarray ?
($v1, $v2) : $v1;
420 # Currently we do not need to create seccomp profile 'files' as the only
421 # choice our configuration actually allows is "with or without keyctl()",
422 # so we distinguish between using lxc's "default" seccomp profile and our
423 # added pve-userns.seccomp file.
425 # This returns a configuration line added to the raw lxc config.
426 sub make_seccomp_config
{
427 my ($conf, $unprivileged, $features) = @_;
428 # User-configured profile has precedence, note that the user's entry would
429 # be written 'after' this line anyway...
430 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.seccomp.profile')) {
431 # Warn the user if this conflicts with a feature:
432 if ($features->{keyctl
}) {
433 warn "explicitly configured lxc.seccomp.profile overrides the following settings: features:keyctl\n";
438 # Privileged containers keep using the default (which is already part of
439 # the files included via lxc.include, so we don't need to write it out,
440 # that way it stays admin-configurable via /usr/share/lxc/config/... as
442 return '' if !$unprivileged;
444 # Unprivileged containers will get keyctl() disabled by default as a
445 # workaround for systemd-networkd behavior. But we have an option to
446 # explicitly enable it:
447 return '' if $features->{keyctl
};
449 # Finally we're in an unprivileged container without `keyctl` set
450 # explicitly. We have a file prepared for this:
451 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
454 # Since lxc-3.0.2 we can have lxc generate a profile for the container
455 # automatically. The default should be equivalent to the old
456 # `lxc-container-default-cgns` profile.
458 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
459 # additional lines into the profile. We can use that to allow mounting specific
461 sub make_apparmor_config
{
462 my ($conf, $unprivileged, $features) = @_;
464 # user-configured profile has precedence, but first we go through our own
465 # code to figure out whether we should warn the user:
467 my $raw = "lxc.apparmor.profile = generated\n";
470 if ($features->{fuse
}) {
471 # For the informational warning:
472 push @profile_uses, 'features:fuse';
475 # There's lxc.apparmor.allow_nesting now, which will add the necessary
476 # apparmor lines, create an apparmor namespace for the container, but also
477 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
478 # lxcfs mounted over them, because that would prevent the container from
479 # mounting new instances of them for nested containers.
480 if ($features->{nesting
}) {
481 push @profile_uses, 'features:nesting';
482 $raw .= "lxc.apparmor.allow_nesting = 1\n"
484 # In the default profile in /etc/apparmor.d we patch this in because
485 # otherwise a container can for example run `chown` on /sys, breaking
486 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
487 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
488 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
489 # Preferably we could use the 'remount' flag but this does not sit well
490 # with apparmor_parser currently:
491 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
494 if (my $mount = $features->{mount
}) {
495 push @profile_uses, 'features:mount';
496 foreach my $fs (PVE
::Tools
::split_list
($mount)) {
497 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
503 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.apparmor.profile')) {
504 if (length(my $used = join(', ', @profile_uses))) {
505 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
513 sub update_lxc_config
{
514 my ($vmid, $conf) = @_;
516 my $dir = "/var/lib/lxc/$vmid";
518 if ($conf->{template
}) {
520 unlink "$dir/config";
527 die "missing 'arch' - internal error" if !$conf->{arch
};
528 $raw .= "lxc.arch = $conf->{arch}\n";
530 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
531 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
533 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
535 my $cfgpath = '/usr/share/lxc/config';
536 my $inc = "$cfgpath/$ostype.common.conf";
537 $inc ="$cfgpath/common.conf" if !-f
$inc;
538 $raw .= "lxc.include = $inc\n";
540 $inc = "$cfgpath/$ostype.userns.conf";
541 $inc = "$cfgpath/userns.conf" if !-f
$inc;
542 $raw .= "lxc.include = $inc\n";
545 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
547 $raw .= make_seccomp_config
($conf, $unprivileged, $features);
548 $raw .= make_apparmor_config
($conf, $unprivileged, $features);
549 if ($features->{fuse
}) {
550 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
551 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
554 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
555 # cannot be exposed to the container with r/w access (cgroup perms).
556 # When this is enabled mounts will still remain in the monitor's namespace
557 # after the container unmounted them and thus will not detach from their
558 # files while the container is running!
559 $raw .= "lxc.monitor.unshare = 1\n";
561 my $cgv1 = get_cgroup_subsystems
();
563 # Should we read them from /etc/subuid?
564 if ($unprivileged && !$custom_idmap) {
565 $raw .= "lxc.idmap = u 0 100000 65536\n";
566 $raw .= "lxc.idmap = g 0 100000 65536\n";
569 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
570 $raw .= "lxc.console.path = none\n";
571 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices
};
574 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
575 $raw .= "lxc.tty.max = $ttycount\n";
577 # some init scripts expect a linux terminal (turnkey).
578 $raw .= "lxc.environment = TERM=linux\n";
580 my $utsname = $conf->{hostname
} || "CT$vmid";
581 $raw .= "lxc.uts.name = $utsname\n";
583 if ($cgv1->{memory
}) {
584 my $memory = $conf->{memory
} || 512;
585 my $swap = $conf->{swap
} // 0;
587 my $lxcmem = int($memory*1024*1024);
588 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
590 my $lxcswap = int(($memory + $swap)*1024*1024);
591 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
595 if (my $cpulimit = $conf->{cpulimit
}) {
596 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
597 my $value = int(100000*$cpulimit);
598 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
601 my $shares = $conf->{cpuunits
} || 1024;
602 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
605 die "missing 'rootfs' configuration\n"
606 if !defined($conf->{rootfs
});
608 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
610 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
612 foreach my $k (sort keys %$conf) {
613 next if $k !~ m/^net(\d+)$/;
615 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
616 $raw .= "lxc.net.$ind.type = veth\n";
617 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
618 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
619 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
620 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu
});
623 if ($cgv1->{cpuset
}) {
625 if (my $lxcconf = $conf->{lxc
}) {
626 foreach my $entry (@$lxcconf) {
627 my ($k, $v) = @$entry;
628 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
633 my $cores = $conf->{cores
};
634 if (!$had_cpuset && $cores) {
635 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup('lxc', 'effective_cpus') };
636 $cpuset = PVE
::CpuSet-
>new_from_cgroup('', 'effective_cpus') if !$cpuset;
637 my @members = $cpuset->members();
638 while (scalar(@members) > $cores) {
639 my $randidx = int(rand(scalar(@members)));
640 $cpuset->delete($members[$randidx]);
641 splice(@members, $randidx, 1); # keep track of the changes
643 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
647 File
::Path
::mkpath
("$dir/rootfs");
649 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
652 # verify and cleanup nameserver list (replace \0 with ' ')
653 sub verify_nameserver_list
{
654 my ($nameserver_list) = @_;
657 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
658 PVE
::JSONSchema
::pve_verify_ip
($server);
662 return join(' ', @list);
665 sub verify_searchdomain_list
{
666 my ($searchdomain_list) = @_;
669 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
670 # todo: should we add checks for valid dns domains?
674 return join(' ', @list);
677 sub get_console_command
{
678 my ($vmid, $conf, $escapechar) = @_;
680 # '-1' as $escapechar disables keyboard escape sequence
681 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
683 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
686 if ($cmode eq 'console') {
687 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
688 push @$cmd, '-e', $escapechar if $escapechar;
689 } elsif ($cmode eq 'tty') {
690 push @$cmd, 'lxc-console', '-n', $vmid;
691 push @$cmd, '-e', $escapechar if $escapechar;
692 } elsif ($cmode eq 'shell') {
693 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
695 die "internal error";
701 sub get_primary_ips
{
704 # return data from net0
706 return undef if !defined($conf->{net0
});
707 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
709 my $ipv4 = $net->{ip
};
711 if ($ipv4 =~ /^(dhcp|manual)$/) {
717 my $ipv6 = $net->{ip6
};
719 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
726 return ($ipv4, $ipv6);
729 sub delete_mountpoint_volume
{
730 my ($storage_cfg, $vmid, $volume) = @_;
732 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
734 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
736 if ($vmid == $owner) {
737 PVE
::Storage
::vdisk_free
($storage_cfg, $volume);
739 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
743 sub destroy_lxc_container
{
744 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
746 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
747 my ($ms, $mountpoint) = @_;
748 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
751 rmdir "/var/lib/lxc/$vmid/rootfs";
752 unlink "/var/lib/lxc/$vmid/config";
753 rmdir "/var/lib/lxc/$vmid";
754 if (defined $replacement_conf) {
755 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
757 PVE
::LXC
::Config-
>destroy_config($vmid);
761 sub vm_stop_cleanup
{
762 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
764 return if $keepActive;
767 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
768 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
770 warn $@ if $@; # avoid errors - just warn
773 my $safe_num_ne = sub {
776 return 0 if !defined($a) && !defined($b);
777 return 1 if !defined($a);
778 return 1 if !defined($b);
783 my $safe_string_ne = sub {
786 return 0 if !defined($a) && !defined($b);
787 return 1 if !defined($a);
788 return 1 if !defined($b);
794 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
796 if ($newnet->{type
} ne 'veth') {
797 # for when there are physical interfaces
798 die "cannot update interface of type $newnet->{type}";
801 my $veth = "veth${vmid}i${netid}";
802 my $eth = $newnet->{name
};
804 if (my $oldnetcfg = $conf->{$opt}) {
805 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
807 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
808 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
810 PVE
::Network
::veth_delete
($veth);
811 delete $conf->{$opt};
812 PVE
::LXC
::Config-
>write_config($vmid, $conf);
814 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
817 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
818 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
819 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
821 if ($oldnet->{bridge
}) {
822 PVE
::Network
::tap_unplug
($veth);
823 foreach (qw(bridge tag firewall)) {
824 delete $oldnet->{$_};
826 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
827 PVE
::LXC
::Config-
>write_config($vmid, $conf);
830 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
831 # This includes the rate:
832 foreach (qw(bridge tag firewall rate)) {
833 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
835 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
836 # Rate can be applied on its own but any change above needs to
837 # include the rate in tap_plug since OVS resets everything.
838 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
839 $oldnet->{rate
} = $newnet->{rate
}
841 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
842 PVE
::LXC
::Config-
>write_config($vmid, $conf);
845 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
848 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
852 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
854 my $veth = "veth${vmid}i${netid}";
855 my $vethpeer = $veth . "p";
856 my $eth = $newnet->{name
};
858 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
859 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
861 # attach peer in container
862 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
863 PVE
::Tools
::run_command
($cmd);
865 # link up peer in container
866 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
867 PVE
::Tools
::run_command
($cmd);
869 my $done = { type
=> 'veth' };
870 foreach (qw(bridge tag firewall hwaddr name)) {
871 $done->{$_} = $newnet->{$_} if $newnet->{$_};
873 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
875 PVE
::LXC
::Config-
>write_config($vmid, $conf);
878 sub update_ipconfig
{
879 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
881 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
883 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
888 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
890 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
892 my $change_ip_config = sub {
893 my ($ipversion) = @_;
895 my $family_opt = "-$ipversion";
896 my $suffix = $ipversion == 4 ?
'' : $ipversion;
900 my $newip = $newnet->{$ip};
901 my $newgw = $newnet->{$gw};
902 my $oldip = $optdata->{$ip};
903 my $oldgw = $optdata->{$gw};
905 my $change_ip = &$safe_string_ne($oldip, $newip);
906 my $change_gw = &$safe_string_ne($oldgw, $newgw);
908 return if !$change_ip && !$change_gw;
910 # step 1: add new IP, if this fails we cancel
911 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
912 if ($change_ip && $is_real_ip) {
913 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
920 # step 2: replace gateway
921 # If this fails we delete the added IP and cancel.
922 # If it succeeds we save the config and delete the old IP, ignoring
923 # errors. The config is then saved.
924 # Note: 'ip route replace' can add
928 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
929 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
931 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
935 # the route was not replaced, the old IP is still available
936 # rollback (delete new IP) and cancel
938 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
939 warn $@ if $@; # no need to die here
944 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
945 # if the route was not deleted, the guest might have deleted it manually
949 if ($oldgw && $oldip && !PVE
::Network
::is_ip_in_cidr
($oldgw, $oldip)) {
950 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
951 # warn if the route was deleted manually
956 # from this point on we save the configuration
957 # step 3: delete old IP ignoring errors
958 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
959 # We need to enable promote_secondaries, otherwise our newly added
960 # address will be removed along with the old one.
963 if ($ipversion == 4) {
964 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
965 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
966 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
968 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
970 warn $@ if $@; # no need to die here
972 if ($ipversion == 4) {
973 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
977 foreach my $property ($ip, $gw) {
978 if ($newnet->{$property}) {
979 $optdata->{$property} = $newnet->{$property};
981 delete $optdata->{$property};
984 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
985 PVE
::LXC
::Config-
>write_config($vmid, $conf);
986 $lxc_setup->setup_network($conf);
989 &$change_ip_config(4);
990 &$change_ip_config(6);
994 my $enter_namespace = sub {
995 my ($vmid, $pid, $which, $type) = @_;
996 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
997 or die "failed to open $which namespace of container $vmid: $!\n";
998 PVE
::Tools
::setns
(fileno($fd), $type)
999 or die "failed to enter $which namespace of container $vmid: $!\n";
1003 my $do_syncfs = sub {
1004 my ($vmid, $pid, $socket) = @_;
1006 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
1008 # Tell the parent process to start reading our /proc/mounts
1009 print {$socket} "go\n";
1012 # Receive /proc/self/mounts
1013 my $mountdata = do { local $/ = undef; <$socket> };
1016 # Now sync all mountpoints...
1017 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
1018 foreach my $mp (@$mounts) {
1019 my ($what, $dir, $fs) = @$mp;
1020 next if $fs eq 'fuse.lxcfs';
1021 eval { PVE
::Tools
::sync_mountpoint
($dir); };
1026 sub sync_container_namespace
{
1028 my $pid = find_lxc_pid
($vmid);
1030 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1031 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
1032 or die "failed to create socketpair: $!\n";
1035 die "fork failed: $!\n" if !defined($child);
1040 &$do_syncfs($vmid, $pid, $cfd);
1050 die "failed to enter container namespace\n" if $go ne "go\n";
1052 open my $mounts, '<', "/proc/$child/mounts"
1053 or die "failed to open container's /proc/mounts: $!\n";
1054 my $mountdata = do { local $/ = undef; <$mounts> };
1056 print {$pfd} $mountdata;
1059 while (waitpid($child, 0) != $child) {}
1060 die "failed to sync container namespace\n" if $? != 0;
1063 sub template_create
{
1064 my ($vmid, $conf) = @_;
1066 my $storecfg = PVE
::Storage
::config
();
1068 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1069 my ($ms, $mountpoint) = @_;
1071 my $volid = $mountpoint->{volume
};
1073 die "Template feature is not available for '$volid'\n"
1074 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1077 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1078 my ($ms, $mountpoint) = @_;
1080 my $volid = $mountpoint->{volume
};
1082 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
1084 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
1085 $mountpoint->{volume
} = $template_volid;
1086 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1089 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1092 sub check_ct_modify_config_perm
{
1093 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
1095 return 1 if $authuser eq 'root@pam';
1098 my ($opt, $delete) = @_;
1099 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1100 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1101 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1102 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1104 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
1105 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
1106 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
1107 if $data->{type
} ne 'volume';
1108 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1109 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1110 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1111 $opt eq 'searchdomain' || $opt eq 'hostname') {
1112 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1113 } elsif ($opt eq 'features') {
1114 # For now this is restricted to root@pam
1115 raise_perm_exc
("changing feature flags is only allowed for root\@pam");
1116 } elsif ($opt eq 'hookscript') {
1117 # For now this is restricted to root@pam
1118 raise_perm_exc
("changing the hookscript is only allowed for root\@pam");
1120 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1124 foreach my $opt (keys %$newconf) {
1127 foreach my $opt (@$delete) {
1135 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1137 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1138 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1142 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
1143 my ($ms, $mountpoint) = @_;
1145 my $volid = $mountpoint->{volume
};
1146 my $mount = $mountpoint->{mp
};
1148 return if !$volid || !$mount;
1150 my $mount_path = "$rootdir/$mount";
1151 $mount_path =~ s!/+!/!g;
1153 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1156 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
1168 return $res; # tell caller if (some) umounts failed for the noerr case
1172 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1174 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1175 File
::Path
::make_path
($rootdir);
1177 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1178 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
1180 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1183 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1184 my ($ms, $mountpoint) = @_;
1186 $mountpoint->{ro
} = 0 if $ignore_ro;
1188 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1192 warn "mounting container failed\n";
1193 umount_all
($vmid, $storage_cfg, $conf, 1);
1201 sub mountpoint_mount_path
{
1202 my ($mountpoint, $storage_cfg, $snapname) = @_;
1204 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1212 if ($line =~ m
@^(/dev/loop\d
+):@) {
1216 my $cmd = ['losetup', '--associated', $path];
1217 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1221 # Run a function with a file attached to a loop device.
1222 # The loop device is always detached afterwards (or set to autoclear).
1223 # Returns the loop device.
1224 sub run_with_loopdev
{
1225 my ($func, $file, $readonly) = @_;
1226 my $device = query_loopdev
($file);
1227 # Try to reuse an existing device
1229 # We assume that whoever setup the loop device is responsible for
1237 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1247 push @$losetup_cmd, '-r' if $readonly;
1248 PVE
::Tools
::run_command
($losetup_cmd, outfunc
=> $parser);
1249 die "failed to setup loop device for $file\n" if !$device;
1250 eval { &$func($device); };
1252 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1257 # In scalar mode: returns a file handle to the deepest directory node.
1258 # In list context: returns a list of:
1259 # * the deepest directory node
1260 # * the 2nd deepest directory (parent of the above)
1261 # * directory name of the last directory
1262 # So that the path $2/$3 should lead to $1 afterwards.
1263 sub walk_tree_nofollow
($$$;$$) {
1264 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1266 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1267 or die "failed to open start directory $start: $!\n";
1269 return walk_tree_nofollow_fd
($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1273 sub walk_tree_nofollow_fd
($$$$;$$) {
1274 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1276 # splitdir() returns '' for empty components including the leading /
1277 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1280 my $dir = $start_dirname;
1281 my $last_component = undef;
1283 foreach my $component (@comps) {
1284 $dir .= "/$component";
1285 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1288 # failed, check for symlinks and try to create the path
1289 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1290 die "cannot open directory $dir: $!\n" if !$mkdir;
1292 # We don't check for errors on mkdirat() here and just try to
1293 # openat() again, since at least one error (EEXIST) is an
1294 # expected possibility if multiple containers start
1295 # simultaneously. If someone else injects a symlink now then
1296 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1297 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1299 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1300 die "failed to create path: $dir: $!\n" if !$next;
1302 PVE
::Tools
::fchownat
(fileno($next), '', $rootuid, $rootgid, PVE
::Tools
::AT_EMPTY_PATH
)
1303 if defined($rootuid) && defined($rootgid);
1306 close $second if defined($last_component) && $second != $start_fd;
1307 $last_component = $component;
1312 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1313 close $second if defined($last_component) && $second != $start_fd;
1317 # To guard against symlink attack races against other currently running
1318 # containers with shared recursive bind mount hierarchies we prepare a
1319 # directory handle for the directory we're mounting over to verify the
1320 # mountpoint afterwards.
1321 sub __bindmount_prepare
{
1322 my ($hostroot, $dir) = @_;
1323 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1327 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1328 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1329 # we intended to bind mount.
1330 sub __bindmount_verify
{
1331 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1334 # Open the mount point path coming from the parent directory since the
1335 # filehandle we would have gotten as first result of walk_tree_nofollow
1336 # earlier is still a handle to the underlying directory instead of the
1338 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1339 die "failed to open mount point: $!\n" if !$destdh;
1342 # no separate function because 99% of the time it's the wrong thing to use.
1343 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1344 die "failed to mark bind mount read only\n";
1346 die "read-only check failed: $!\n" if $! != EROFS
;
1349 # For the rootfs we don't have a parentfd so we open the path directly.
1350 # Note that this means bindmounting any prefix of the host's
1351 # /var/lib/lxc/$vmid path into another container is considered a grave
1353 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1354 die "failed to open mount point: $!\n" if !$destdh;
1357 my ($srcdev, $srcinode) = stat($srcdh);
1358 my ($dstdev, $dstinode) = stat($destdh);
1362 return ($srcdev == $dstdev && $srcinode == $dstinode);
1365 # Perform the actual bind mounting:
1366 sub __bindmount_do
{
1367 my ($dir, $dest, $ro, @extra_opts) = @_;
1368 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1370 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1372 warn "bindmount error\n";
1373 # don't leave writable bind-mounts behind...
1374 PVE
::Tools
::run_command
(['umount', $dest]);
1381 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1383 my $srcdh = __bindmount_prepare
('/', $dir);
1385 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1387 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1388 PVE
::Tools
::run_command
(['umount', $dest]);
1389 die "detected mount path change at: $dir\n";
1393 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1394 # from $rootdir and $mount and walk the path from $rootdir to the final
1395 # directory to check for symlinks.
1396 sub __mount_prepare_rootdir
{
1397 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1398 $rootdir =~ s!/+!/!g;
1399 $rootdir =~ s!/+$!!;
1400 my $mount_path = "$rootdir/$mount";
1401 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1, $rootuid, $rootgid);
1402 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1405 # use $rootdir = undef to just return the corresponding mount path
1406 sub mountpoint_mount
{
1407 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1408 return __mountpoint_mount
($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1411 sub mountpoint_stage
{
1412 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1413 my ($path, $loop, $dev) =
1414 __mountpoint_mount
($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1416 if (!defined($path)) {
1417 return undef if $! == ENOSYS
;
1418 die "failed to mount subvolume: $!\n";
1422 my $fd = PVE
::Tools
::open_tree
(&AT_FDCWD
, $stage_dir, &OPEN_TREE_CLOEXEC
| &OPEN_TREE_CLONE
)
1423 or die "open_tree() on mount point failed: $!\n";
1425 return wantarray ?
($path, $loop, $dev, $fd) : $fd;
1428 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1429 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1430 # Note that if the kernel does not support the new mount API, this will not perform any action
1431 # and return `undef` with $! = ENOSYS.
1432 sub __mountpoint_mount
{
1433 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1435 if (defined($stage_mount) && !PVE
::LXC
::Tools
::can_use_new_mount_api
()) {
1440 my $volid = $mountpoint->{volume
};
1441 my $mount = $mountpoint->{mp
};
1442 my $type = $mountpoint->{type
};
1443 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1446 return if !$volid || !$mount;
1451 my ($mpfd, $parentfd, $last_dir);
1453 if (defined($rootdir)) {
1454 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1455 __mount_prepare_rootdir
($rootdir, $mount, $rootuid, $rootgid);
1458 if (defined($stage_mount)) {
1459 $mount_path = $rootdir;
1462 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1464 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1468 if (my $mountopts = $mountpoint->{mountoptions
}) {
1469 my @opts = split(/;/, $mountpoint->{mountoptions
});
1470 push @$optlist, grep { PVE
::LXC
::Config
::is_valid_mount_option
($_) } @opts;
1473 my $acl = $mountpoint->{acl
};
1474 if (defined($acl)) {
1475 push @$optlist, ($acl ?
'acl' : 'noacl');
1478 my $optstring = join(',', @$optlist);
1479 my $readonly = $mountpoint->{ro
};
1482 @extra_opts = ('-o', $optstring) if $optstring;
1486 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1488 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid, $snapname);
1490 $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname) if !defined($path);
1492 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1493 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1495 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1497 if ($format eq 'subvol') {
1500 if ($scfg->{type
} eq 'zfspool') {
1501 my $path_arg = $path;
1502 $path_arg =~ s!^/+!!;
1503 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1505 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1508 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1509 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1510 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1511 $name .= "\@$snapname" if defined($snapname);
1512 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1514 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1515 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1518 return wantarray ?
($path, 0, undef) : $path;
1519 } elsif ($format eq 'raw' || $format eq 'iso') {
1520 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1521 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1522 # Our autodev hook expects the /dev/dm-* device currently
1523 # and will create the /dev/mapper symlink accordingly
1524 $path = Cwd
::realpath
($path);
1525 die "failed to get device path\n" if !$path;
1526 ($path) = ($path =~ /^(.*)$/s); #untaint
1530 if ($format eq 'iso') {
1531 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1532 } elsif ($isBase || defined($snapname)) {
1533 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1536 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1538 push @extra_opts, '-o', 'ro' if $readonly;
1539 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1543 my $use_loopdev = 0;
1544 if ($scfg->{path
}) {
1545 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1547 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1548 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1549 $mounted_dev = $path;
1552 die "unsupported storage type '$scfg->{type}'\n";
1554 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1556 die "unsupported image format '$format'\n";
1558 } elsif ($type eq 'device') {
1559 push @extra_opts, '-o', 'ro' if $readonly;
1560 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1561 # See the NOTE above about devicemapper canonicalization
1562 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1563 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1564 return wantarray ?
($volid, 0, $devpath) : $volid;
1565 } elsif ($type eq 'bind') {
1566 die "directory '$volid' does not exist\n" if ! -d
$volid;
1567 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1568 warn "cannot enable quota control for bind mounts\n" if $quota;
1569 return wantarray ?
($volid, 0, undef) : $volid;
1572 die "unsupported storage";
1576 my ($dev, $rootuid, $rootgid) = @_;
1578 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1579 '-E', "root_owner=$rootuid:$rootgid",
1584 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1586 if ($volid =~ m!^/dev/.+!) {
1591 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1593 die "cannot format volume '$volid' with no storage\n" if !$storage;
1595 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1597 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid);
1599 $path = PVE
::Storage
::path
($storage_cfg, $volid) if !defined($path);
1601 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1602 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1604 die "cannot format volume '$volid' (format == $format)\n"
1605 if $format ne 'raw';
1607 mkfs
($path, $rootuid, $rootgid);
1611 my ($storecfg, $vollist) = @_;
1613 foreach my $volid (@$vollist) {
1614 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1620 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1622 my $needs_chown = 0;
1625 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1626 # fixme: use better naming ct-$vmid-disk-X.raw?
1630 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs' || $scfg->{type
} eq 'cifs' ) {
1632 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1636 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1640 } elsif ($scfg->{type
} eq 'zfspool') {
1642 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1645 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1647 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1650 } elsif ($scfg->{type
} eq 'rbd') {
1652 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1655 die "unable to create containers on storage type '$scfg->{type}'\n";
1657 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1660 # in case formatting got interrupted:
1661 if (defined($volid)) {
1662 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1668 return ($volid, $needs_chown);
1671 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1673 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
1678 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1679 my $chown_vollist = [];
1681 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1682 my ($ms, $mountpoint) = @_;
1684 my $volid = $mountpoint->{volume
};
1685 my $mp = $mountpoint->{mp
};
1687 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1689 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1690 my ($storeid, $size_gb) = ($1, $2);
1692 my $size_kb = int(${size_gb
}*1024) * 1024;
1694 my $needs_chown = 0;
1695 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1696 push @$chown_vollist, $volid if $needs_chown;
1697 push @$vollist, $volid;
1698 $mountpoint->{volume
} = $volid;
1699 $mountpoint->{size
} = $size_kb * 1024;
1701 $conf->{pending
}->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1703 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1706 # use specified/existing volid/dir/device
1707 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1711 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1712 foreach my $volid (@$chown_vollist) {
1713 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1714 chown($rootuid, $rootgid, $path);
1716 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1718 # free allocated images on error
1720 destroy_disks
($storecfg, $vollist);
1726 sub update_disksize
{
1727 my ($vmid, $conf, $all_volumes) = @_;
1730 my $prefix = "CT $vmid:";
1732 my $update_mp = sub {
1733 my ($key, $mp, @param) = @_;
1734 my $size = $all_volumes->{$mp->{volume
}}->{size
} // 0;
1736 if (!defined($mp->{size
}) || $size != $mp->{size
}) {
1738 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1739 $mp->{size
} = $size;
1740 my $nomp = 1 if ($key eq 'rootfs');
1741 $conf->{$key} = PVE
::LXC
::Config-
>print_ct_mountpoint($mp, $nomp);
1745 PVE
::LXC
::Config-
>foreach_mountpoint($conf, $update_mp);
1751 my ($vmid, $conf, $all_volumes) = @_;
1754 my $prefix = "CT $vmid:";
1756 # Note: it is allowed to define multiple storage entries with the same path
1757 # (alias), so we need to check both 'volid' and real 'path' (two different
1758 # volid can point to the same path).
1760 # used and unused disks
1764 foreach my $opt (keys %$conf) {
1765 next if ($opt !~ m/^unused\d+$/);
1766 my $vol = $all_volumes->{$conf->{$opt}};
1767 $refpath->{$vol->{path
}} = $vol->{volid
};
1770 foreach my $key (keys %$all_volumes) {
1771 my $vol = $all_volumes->{$key};
1772 my $in_use = PVE
::LXC
::Config-
>is_volume_in_use($conf, $vol->{volid
});
1773 my $path = $vol->{path
};
1776 $refpath->{$path} = $key;
1777 delete $orphans->{$path};
1779 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
1780 $orphans->{$path} = $key;
1785 for my $key (keys %$orphans) {
1786 my $disk = $orphans->{$key};
1787 my $unused = PVE
::LXC
::Config-
>add_unused_volume($conf, $disk);
1791 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
1799 my ($cfg, $vmid) = @_;
1801 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid);
1803 my $all_volumes = {};
1804 foreach my $storeid (keys %$info) {
1805 foreach my $item (@{$info->{$storeid}}) {
1806 my $volid = $item->{volid
};
1807 next if !($volid && $item->{size
});
1808 $item->{path
} = PVE
::Storage
::path
($cfg, $volid);
1809 $all_volumes->{$volid} = $item;
1813 return $all_volumes;
1817 my ($vmid, $nolock, $dryrun) = @_;
1819 my $cfg = PVE
::Storage
::config
();
1821 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
1822 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
1823 foreach my $stor (keys %{$cfg->{ids
}}) {
1824 delete($cfg->{ids
}->{$stor}) if !$cfg->{ids
}->{$stor}->{content
}->{rootdir
};
1827 print "rescan volumes...\n";
1828 my $all_volumes = scan_volids
($cfg, $vmid);
1830 my $updatefn = sub {
1834 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
1836 PVE
::LXC
::Config-
>check_lock($conf);
1839 foreach my $volid (keys %$all_volumes) {
1840 my $info = $all_volumes->{$volid};
1841 $vm_volids->{$volid} = $info if $info->{vmid
} == $vmid;
1844 my $upu = update_unused
($vmid, $conf, $vm_volids);
1845 my $upd = update_disksize
($vmid, $conf, $vm_volids);
1846 $changes = $upu || $upd;
1848 PVE
::LXC
::Config-
>write_config($vmid, $conf) if $changes && !$dryrun;
1851 if (defined($vmid)) {
1855 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
1858 my $vmlist = config_list
();
1859 foreach my $vmid (keys %$vmlist) {
1863 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
1870 # bash completion helper
1872 sub complete_os_templates
{
1873 my ($cmdname, $pname, $cvalue) = @_;
1875 my $cfg = PVE
::Storage
::config
();
1879 if ($cvalue =~ m/^([^:]+):/) {
1883 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
1884 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
1887 foreach my $id (keys %$data) {
1888 foreach my $item (@{$data->{$id}}) {
1889 push @$res, $item->{volid
} if defined($item->{volid
});
1896 my $complete_ctid_full = sub {
1899 my $idlist = vmstatus
();
1901 my $active_hash = list_active_containers
();
1905 foreach my $id (keys %$idlist) {
1906 my $d = $idlist->{$id};
1907 if (defined($running)) {
1908 next if $d->{template
};
1909 next if $running && !$active_hash->{$id};
1910 next if !$running && $active_hash->{$id};
1919 return &$complete_ctid_full();
1922 sub complete_ctid_stopped
{
1923 return &$complete_ctid_full(0);
1926 sub complete_ctid_running
{
1927 return &$complete_ctid_full(1);
1937 my $lxc = $conf->{lxc
};
1938 foreach my $entry (@$lxc) {
1939 my ($key, $value) = @$entry;
1940 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1941 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
1942 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1943 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1944 push @$id_map, [$type, $ct, $host, $length];
1946 $rootuid = $host if $type eq 'u';
1947 $rootgid = $host if $type eq 'g';
1950 die "failed to parse idmap: $value\n";
1954 if (!@$id_map && $conf->{unprivileged
}) {
1955 # Should we read them from /etc/subuid?
1956 $id_map = [ ['u', '0', '100000', '65536'],
1957 ['g', '0', '100000', '65536'] ];
1958 $rootuid = $rootgid = 100000;
1961 return ($id_map, $rootuid, $rootgid);
1964 sub userns_command
{
1967 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1973 my ($vmid, $conf, $skiplock) = @_;
1975 # apply pending changes while starting
1976 if (scalar(keys %{$conf->{pending
}})) {
1977 my $storecfg = PVE
::Storage
::config
();
1978 PVE
::LXC
::Config-
>vmconfig_apply_pending($vmid, $conf, $storecfg);
1979 $conf = PVE
::LXC
::Config-
>load_config($vmid); # update/reload
1982 update_lxc_config
($vmid, $conf);
1984 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1987 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1991 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1993 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-start', 1);
1994 eval { PVE
::Tools
::run_command
($cmd); };
1996 unlink $skiplock_flag_fn;
1999 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'post-start');
2004 # Helper to stop a container completely and make sure it has stopped completely.
2005 # This is necessary because we want the post-stop hook to have completed its
2006 # unmount-all step, but post-stop happens after lxc puts the container into the
2008 # $kill - if true it will always do an immediate hard-stop
2009 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2010 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2012 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2014 # Open the container's command socket.
2015 my $path = "\0/var/lib/lxc/$vmid/command";
2016 my $sock = IO
::Socket
::UNIX-
>new(
2017 Type
=> SOCK_STREAM
(),
2021 return if $! == ECONNREFUSED
; # The container is not running
2022 die "failed to open container ${vmid}'s command socket: $!\n";
2025 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
2026 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-stop');
2028 # Stop the container:
2030 my $cmd = ['lxc-stop', '-n', $vmid];
2033 push @$cmd, '--kill'; # doesn't allow timeouts
2035 # lxc-stop uses a default timeout
2036 push @$cmd, '--nokill' if !$kill_after_timeout;
2038 if (defined($shutdown_timeout)) {
2039 push @$cmd, '--timeout', $shutdown_timeout;
2040 # Give run_command 5 extra seconds
2041 $shutdown_timeout += 5;
2045 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
2050 my $result = <$sock>;
2052 return if !defined $result; # monitor is gone and the ct has stopped.
2053 die "container did not stop\n";
2059 return PVE
::Tools
::run_fork
(sub {
2060 # Unshare the mount namespace
2061 die "failed to unshare mount namespace: $!\n"
2062 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
2063 PVE
::Tools
::run_command
(['mount', '--make-rslave', '/']);
2068 my $copy_volume = sub {
2069 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2071 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
2072 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
2074 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
2075 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
2081 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2082 push @mounted, $src;
2084 mountpoint_mount
($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2085 push @mounted, $dest;
2089 PVE
::Tools
::run_command
(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2090 '-aH', '--whole-file', '--sparse', '--one-file-system',
2091 "--bwlimit=$bwlimit", "$src/", $dest]);
2095 # Wait for rsync's children to release dest so that
2096 # consequent file operations (umount, remove) are possible
2097 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2099 foreach my $mount (reverse @mounted) {
2100 eval { PVE
::Tools
::run_command
(['/bin/umount', $mount], errfunc
=> sub{})};
2101 warn "Can't umount $mount\n" if $@;
2104 # If this fails they're used as mount points in a concurrent operation
2105 # (which should not happen but there's also no real need to get rid of them).
2112 # Should not be called after unsharing the mount namespace!
2114 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2116 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
2117 File
::Path
::make_path
("/var/lib/lxc/$vmid");
2118 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2119 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2121 # get id's for unprivileged container
2122 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
2124 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2125 # are visible in this namespace, otherwise the host only sees the empty
2126 # (not-mounted) directory.
2129 # Make sure $mp contains a correct size.
2130 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
2132 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
2134 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
2135 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
2136 chown($rootuid, $rootgid, $path);
2140 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2144 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
2145 if defined($new_volid);