13 use Fcntl
qw(O_RDONLY O_NOFOLLOW O_DIRECTORY);
14 use Errno
qw(ELOOP ENOTDIR EROFS ECONNREFUSED);
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);
25 use PVE
::AccessControl
;
29 use PVE
::GuestHelpers
;
31 use Time
::HiRes qw
(gettimeofday
);
33 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
35 my $nodename = PVE
::INotify
::nodename
();
37 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
40 my $vmlist = PVE
::Cluster
::get_vmlist
();
42 return $res if !$vmlist || !$vmlist->{ids
};
43 my $ids = $vmlist->{ids
};
45 foreach my $vmid (keys %$ids) {
46 next if !$vmid; # skip CT0
47 my $d = $ids->{$vmid};
48 next if !$d->{node
} || $d->{node
} ne $nodename;
49 next if !$d->{type
} || $d->{type
} ne 'lxc';
50 $res->{$vmid} = { type
=> 'lxc', vmid
=> $vmid };
58 my $config_fn = PVE
::LXC
::Config-
>config_file($vmid, $nodename);
59 unlink $config_fn or die "failed to remove config file: $!\n";
62 # container status helpers
64 sub list_active_containers
{
66 my $filename = "/proc/net/unix";
68 # similar test is used by lcxcontainers.c: list_active_containers
71 my $fh = IO
::File-
>new ($filename, "r");
74 while (defined(my $line = <$fh>)) {
75 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
77 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
88 # warning: this is slow
92 my $active_hash = list_active_containers
();
94 return 1 if defined($active_hash->{$vmid});
99 sub get_container_disk_usage
{
100 my ($vmid, $pid) = @_;
102 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
105 my $last_proc_vmid_stat;
107 my $parse_cpuacct_stat = sub {
108 my ($vmid, $unprivileged) = @_;
110 my $raw = read_cgroup_value
('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
114 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
124 our $vmstatus_return_properties = {
125 vmid
=> get_standard_option
('pve-vmid'),
127 description
=> "LXC Container status.",
129 enum
=> ['stopped', 'running'],
132 description
=> "Maximum memory in bytes.",
138 description
=> "Maximum SWAP memory in bytes.",
144 description
=> "Root disk size in bytes.",
150 description
=> "Container name.",
155 description
=> "Uptime.",
158 renderer
=> 'duration',
161 description
=> "Maximum usable CPUs.",
166 description
=> "The current config lock, if any.",
175 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc', vmid
=> $opt_vmid }} : config_list
();
177 my $active_hash = list_active_containers
();
179 my $cpucount = $cpuinfo->{cpus
} || 1;
181 my $cdtime = gettimeofday
;
183 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
184 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
186 my $unprivileged = {};
188 foreach my $vmid (keys %$list) {
189 my $d = $list->{$vmid};
191 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
192 warn $@ if $@; # ignore errors (consider them stopped)
194 $d->{status
} = $active_hash->{$vmid} ?
'running' : 'stopped';
196 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
197 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
199 $unprivileged->{$vmid} = $conf->{unprivileged
};
201 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
202 $d->{name
} =~ s/[\s]//g;
204 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
205 $d->{cpus
} = $cpucount if !$d->{cpus
};
207 $d->{lock} = $conf->{lock} || '';
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;
397 # Note: we cannot use Net:IP, because that only allows strict
399 sub parse_ipv4_cidr
{
400 my ($cidr, $noerr) = @_;
402 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
403 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
406 return undef if $noerr;
408 die "unable to parse ipv4 address/mask\n";
411 sub get_cgroup_subsystems
{
414 my $data = PVE
::Tools
::file_get_contents
('/proc/self/cgroup');
415 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
418 $v1->{$_} = 1 foreach split(/,/, $type);
423 return wantarray ?
($v1, $v2) : $v1;
426 # Currently we do not need to create seccomp profile 'files' as the only
427 # choice our configuration actually allows is "with or without keyctl()",
428 # so we distinguish between using lxc's "default" seccomp profile and our
429 # added pve-userns.seccomp file.
431 # This returns a configuration line added to the raw lxc config.
432 sub make_seccomp_config
{
433 my ($conf, $unprivileged, $features) = @_;
434 # User-configured profile has precedence, note that the user's entry would
435 # be written 'after' this line anyway...
436 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.seccomp.profile')) {
437 # Warn the user if this conflicts with a feature:
438 if ($features->{keyctl
}) {
439 warn "explicitly configured lxc.seccomp.profile overrides the following settings: features:keyctl\n";
444 # Privileged containers keep using the default (which is already part of
445 # the files included via lxc.include, so we don't need to write it out,
446 # that way it stays admin-configurable via /usr/share/lxc/config/... as
448 return '' if !$unprivileged;
450 # Unprivileged containers will get keyctl() disabled by default as a
451 # workaround for systemd-networkd behavior. But we have an option to
452 # explicitly enable it:
453 return '' if $features->{keyctl
};
455 # Finally we're in an unprivileged container without `keyctl` set
456 # explicitly. We have a file prepared for this:
457 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
460 # Since lxc-3.0.2 we can have lxc generate a profile for the container
461 # automatically. The default should be equivalent to the old
462 # `lxc-container-default-cgns` profile.
464 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
465 # additional lines into the profile. We can use that to allow mounting specific
467 sub make_apparmor_config
{
468 my ($conf, $unprivileged, $features) = @_;
470 # user-configured profile has precedence, but first we go through our own
471 # code to figure out whether we should warn the user:
473 my $raw = "lxc.apparmor.profile = generated\n";
476 if ($features->{fuse
}) {
477 # For the informational warning:
478 push @profile_uses, 'features:fuse';
481 # There's lxc.apparmor.allow_nesting now, which will add the necessary
482 # apparmor lines, create an apparmor namespace for the container, but also
483 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
484 # lxcfs mounted over them, because that would prevent the container from
485 # mounting new instances of them for nested containers.
486 if ($features->{nesting
}) {
487 push @profile_uses, 'features:nesting';
488 $raw .= "lxc.apparmor.allow_nesting = 1\n"
490 # In the default profile in /etc/apparmor.d we patch this in because
491 # otherwise a container can for example run `chown` on /sys, breaking
492 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
493 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
494 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
495 # Preferably we could use the 'remount' flag but this does not sit well
496 # with apparmor_parser currently:
497 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
500 if (my $mount = $features->{mount
}) {
501 push @profile_uses, 'features:mount';
502 foreach my $fs (PVE
::Tools
::split_list
($mount)) {
503 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
509 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.apparmor.profile')) {
510 if (length(my $used = join(', ', @profile_uses))) {
511 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
519 sub update_lxc_config
{
520 my ($vmid, $conf) = @_;
522 my $dir = "/var/lib/lxc/$vmid";
524 if ($conf->{template
}) {
526 unlink "$dir/config";
533 die "missing 'arch' - internal error" if !$conf->{arch
};
534 $raw .= "lxc.arch = $conf->{arch}\n";
536 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
537 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
539 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
541 my $cfgpath = '/usr/share/lxc/config';
542 my $inc = "$cfgpath/$ostype.common.conf";
543 $inc ="$cfgpath/common.conf" if !-f
$inc;
544 $raw .= "lxc.include = $inc\n";
546 $inc = "$cfgpath/$ostype.userns.conf";
547 $inc = "$cfgpath/userns.conf" if !-f
$inc;
548 $raw .= "lxc.include = $inc\n";
551 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
553 $raw .= make_seccomp_config
($conf, $unprivileged, $features);
554 $raw .= make_apparmor_config
($conf, $unprivileged, $features);
555 if ($features->{fuse
}) {
556 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
557 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
560 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
561 # cannot be exposed to the container with r/w access (cgroup perms).
562 # When this is enabled mounts will still remain in the monitor's namespace
563 # after the container unmounted them and thus will not detach from their
564 # files while the container is running!
565 $raw .= "lxc.monitor.unshare = 1\n";
567 my $cgv1 = get_cgroup_subsystems
();
569 # Should we read them from /etc/subuid?
570 if ($unprivileged && !$custom_idmap) {
571 $raw .= "lxc.idmap = u 0 100000 65536\n";
572 $raw .= "lxc.idmap = g 0 100000 65536\n";
575 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
576 $raw .= "lxc.console.path = none\n";
577 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices
};
580 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
581 $raw .= "lxc.tty.max = $ttycount\n";
583 # some init scripts expect a linux terminal (turnkey).
584 $raw .= "lxc.environment = TERM=linux\n";
586 my $utsname = $conf->{hostname
} || "CT$vmid";
587 $raw .= "lxc.uts.name = $utsname\n";
589 if ($cgv1->{memory
}) {
590 my $memory = $conf->{memory
} || 512;
591 my $swap = $conf->{swap
} // 0;
593 my $lxcmem = int($memory*1024*1024);
594 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
596 my $lxcswap = int(($memory + $swap)*1024*1024);
597 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
601 if (my $cpulimit = $conf->{cpulimit
}) {
602 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
603 my $value = int(100000*$cpulimit);
604 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
607 my $shares = $conf->{cpuunits
} || 1024;
608 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
611 die "missing 'rootfs' configuration\n"
612 if !defined($conf->{rootfs
});
614 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
616 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
618 foreach my $k (sort keys %$conf) {
619 next if $k !~ m/^net(\d+)$/;
621 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
622 $raw .= "lxc.net.$ind.type = veth\n";
623 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
624 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
625 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
626 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu
});
629 if ($cgv1->{cpuset
}) {
631 if (my $lxcconf = $conf->{lxc
}) {
632 foreach my $entry (@$lxcconf) {
633 my ($k, $v) = @$entry;
634 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
639 my $cores = $conf->{cores
};
640 if (!$had_cpuset && $cores) {
641 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup('lxc', 'effective_cpus') };
642 $cpuset = PVE
::CpuSet-
>new_from_cgroup('', 'effective_cpus') if !$cpuset;
643 my @members = $cpuset->members();
644 while (scalar(@members) > $cores) {
645 my $randidx = int(rand(scalar(@members)));
646 $cpuset->delete($members[$randidx]);
647 splice(@members, $randidx, 1); # keep track of the changes
649 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
653 File
::Path
::mkpath
("$dir/rootfs");
655 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
658 # verify and cleanup nameserver list (replace \0 with ' ')
659 sub verify_nameserver_list
{
660 my ($nameserver_list) = @_;
663 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
664 PVE
::JSONSchema
::pve_verify_ip
($server);
668 return join(' ', @list);
671 sub verify_searchdomain_list
{
672 my ($searchdomain_list) = @_;
675 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
676 # todo: should we add checks for valid dns domains?
680 return join(' ', @list);
683 sub get_console_command
{
684 my ($vmid, $conf, $escapechar) = @_;
686 # '-1' as $escapechar disables keyboard escape sequence
687 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
689 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
692 if ($cmode eq 'console') {
693 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
694 push @$cmd, '-e', $escapechar if $escapechar;
695 } elsif ($cmode eq 'tty') {
696 push @$cmd, 'lxc-console', '-n', $vmid;
697 push @$cmd, '-e', $escapechar if $escapechar;
698 } elsif ($cmode eq 'shell') {
699 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
701 die "internal error";
707 sub get_primary_ips
{
710 # return data from net0
712 return undef if !defined($conf->{net0
});
713 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
715 my $ipv4 = $net->{ip
};
717 if ($ipv4 =~ /^(dhcp|manual)$/) {
723 my $ipv6 = $net->{ip6
};
725 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
732 return ($ipv4, $ipv6);
735 sub delete_mountpoint_volume
{
736 my ($storage_cfg, $vmid, $volume) = @_;
738 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
740 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
741 PVE
::Storage
::vdisk_free
($storage_cfg, $volume) if $vmid == $owner;
744 sub destroy_lxc_container
{
745 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
747 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
748 my ($ms, $mountpoint) = @_;
749 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
752 rmdir "/var/lib/lxc/$vmid/rootfs";
753 unlink "/var/lib/lxc/$vmid/config";
754 rmdir "/var/lib/lxc/$vmid";
755 if (defined $replacement_conf) {
756 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
758 destroy_config
($vmid);
761 #my $cmd = ['lxc-destroy', '-n', $vmid ];
762 #PVE::Tools::run_command($cmd);
765 sub vm_stop_cleanup
{
766 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
771 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
772 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
775 warn $@ if $@; # avoid errors - just warn
778 my $safe_num_ne = sub {
781 return 0 if !defined($a) && !defined($b);
782 return 1 if !defined($a);
783 return 1 if !defined($b);
788 my $safe_string_ne = sub {
791 return 0 if !defined($a) && !defined($b);
792 return 1 if !defined($a);
793 return 1 if !defined($b);
799 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
801 if ($newnet->{type
} ne 'veth') {
802 # for when there are physical interfaces
803 die "cannot update interface of type $newnet->{type}";
806 my $veth = "veth${vmid}i${netid}";
807 my $eth = $newnet->{name
};
809 if (my $oldnetcfg = $conf->{$opt}) {
810 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
812 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
813 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
815 PVE
::Network
::veth_delete
($veth);
816 delete $conf->{$opt};
817 PVE
::LXC
::Config-
>write_config($vmid, $conf);
819 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
822 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
823 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
824 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
826 if ($oldnet->{bridge
}) {
827 PVE
::Network
::tap_unplug
($veth);
828 foreach (qw(bridge tag firewall)) {
829 delete $oldnet->{$_};
831 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
832 PVE
::LXC
::Config-
>write_config($vmid, $conf);
835 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
836 # This includes the rate:
837 foreach (qw(bridge tag firewall rate)) {
838 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
840 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
841 # Rate can be applied on its own but any change above needs to
842 # include the rate in tap_plug since OVS resets everything.
843 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
844 $oldnet->{rate
} = $newnet->{rate
}
846 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
847 PVE
::LXC
::Config-
>write_config($vmid, $conf);
850 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
853 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
857 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
859 my $veth = "veth${vmid}i${netid}";
860 my $vethpeer = $veth . "p";
861 my $eth = $newnet->{name
};
863 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
864 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
866 # attach peer in container
867 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
868 PVE
::Tools
::run_command
($cmd);
870 # link up peer in container
871 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
872 PVE
::Tools
::run_command
($cmd);
874 my $done = { type
=> 'veth' };
875 foreach (qw(bridge tag firewall hwaddr name)) {
876 $done->{$_} = $newnet->{$_} if $newnet->{$_};
878 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
880 PVE
::LXC
::Config-
>write_config($vmid, $conf);
883 sub update_ipconfig
{
884 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
886 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
888 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
893 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
895 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
897 my $change_ip_config = sub {
898 my ($ipversion) = @_;
900 my $family_opt = "-$ipversion";
901 my $suffix = $ipversion == 4 ?
'' : $ipversion;
905 my $newip = $newnet->{$ip};
906 my $newgw = $newnet->{$gw};
907 my $oldip = $optdata->{$ip};
908 my $oldgw = $optdata->{$gw};
910 my $change_ip = &$safe_string_ne($oldip, $newip);
911 my $change_gw = &$safe_string_ne($oldgw, $newgw);
913 return if !$change_ip && !$change_gw;
915 # step 1: add new IP, if this fails we cancel
916 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
917 if ($change_ip && $is_real_ip) {
918 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
925 # step 2: replace gateway
926 # If this fails we delete the added IP and cancel.
927 # If it succeeds we save the config and delete the old IP, ignoring
928 # errors. The config is then saved.
929 # Note: 'ip route replace' can add
933 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
934 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
936 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
940 # the route was not replaced, the old IP is still available
941 # rollback (delete new IP) and cancel
943 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
944 warn $@ if $@; # no need to die here
949 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
950 # if the route was not deleted, the guest might have deleted it manually
954 if ($oldgw && $oldip && !PVE
::Network
::is_ip_in_cidr
($oldgw, $oldip)) {
955 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
956 # warn if the route was deleted manually
961 # from this point on we save the configuration
962 # step 3: delete old IP ignoring errors
963 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
964 # We need to enable promote_secondaries, otherwise our newly added
965 # address will be removed along with the old one.
968 if ($ipversion == 4) {
969 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
970 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
971 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
973 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
975 warn $@ if $@; # no need to die here
977 if ($ipversion == 4) {
978 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
982 foreach my $property ($ip, $gw) {
983 if ($newnet->{$property}) {
984 $optdata->{$property} = $newnet->{$property};
986 delete $optdata->{$property};
989 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
990 PVE
::LXC
::Config-
>write_config($vmid, $conf);
991 $lxc_setup->setup_network($conf);
994 &$change_ip_config(4);
995 &$change_ip_config(6);
999 my $enter_namespace = sub {
1000 my ($vmid, $pid, $which, $type) = @_;
1001 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
1002 or die "failed to open $which namespace of container $vmid: $!\n";
1003 PVE
::Tools
::setns
(fileno($fd), $type)
1004 or die "failed to enter $which namespace of container $vmid: $!\n";
1008 my $do_syncfs = sub {
1009 my ($vmid, $pid, $socket) = @_;
1011 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
1013 # Tell the parent process to start reading our /proc/mounts
1014 print {$socket} "go\n";
1017 # Receive /proc/self/mounts
1018 my $mountdata = do { local $/ = undef; <$socket> };
1021 # Now sync all mountpoints...
1022 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
1023 foreach my $mp (@$mounts) {
1024 my ($what, $dir, $fs) = @$mp;
1025 next if $fs eq 'fuse.lxcfs';
1026 eval { PVE
::Tools
::sync_mountpoint
($dir); };
1031 sub sync_container_namespace
{
1033 my $pid = find_lxc_pid
($vmid);
1035 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1036 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
1037 or die "failed to create socketpair: $!\n";
1040 die "fork failed: $!\n" if !defined($child);
1045 &$do_syncfs($vmid, $pid, $cfd);
1055 die "failed to enter container namespace\n" if $go ne "go\n";
1057 open my $mounts, '<', "/proc/$child/mounts"
1058 or die "failed to open container's /proc/mounts: $!\n";
1059 my $mountdata = do { local $/ = undef; <$mounts> };
1061 print {$pfd} $mountdata;
1064 while (waitpid($child, 0) != $child) {}
1065 die "failed to sync container namespace\n" if $? != 0;
1068 sub template_create
{
1069 my ($vmid, $conf) = @_;
1071 my $storecfg = PVE
::Storage
::config
();
1073 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1074 my ($ms, $mountpoint) = @_;
1076 my $volid = $mountpoint->{volume
};
1078 die "Template feature is not available for '$volid'\n"
1079 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1082 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1083 my ($ms, $mountpoint) = @_;
1085 my $volid = $mountpoint->{volume
};
1087 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
1089 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
1090 $mountpoint->{volume
} = $template_volid;
1091 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1094 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1097 sub check_ct_modify_config_perm
{
1098 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
1100 return 1 if $authuser eq 'root@pam';
1103 my ($opt, $delete) = @_;
1104 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1105 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1106 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1107 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1109 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
1110 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
1111 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
1112 if $data->{type
} ne 'volume';
1113 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1114 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1115 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1116 $opt eq 'searchdomain' || $opt eq 'hostname') {
1117 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1118 } elsif ($opt eq 'features') {
1119 # For now this is restricted to root@pam
1120 raise_perm_exc
("changing feature flags is only allowed for root\@pam");
1121 } elsif ($opt eq 'hookscript') {
1122 # For now this is restricted to root@pam
1123 raise_perm_exc
("changing the hookscript is only allowed for root\@pam");
1125 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1129 foreach my $opt (keys %$newconf) {
1132 foreach my $opt (@$delete) {
1140 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1142 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1143 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1145 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
1146 my ($ms, $mountpoint) = @_;
1148 my $volid = $mountpoint->{volume
};
1149 my $mount = $mountpoint->{mp
};
1151 return if !$volid || !$mount;
1153 my $mount_path = "$rootdir/$mount";
1154 $mount_path =~ s!/+!/!g;
1156 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1159 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
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);
1181 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1182 my ($ms, $mountpoint) = @_;
1184 $mountpoint->{ro
} = 0 if $ignore_ro;
1186 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg);
1190 warn "mounting container failed\n";
1191 umount_all
($vmid, $storage_cfg, $conf, 1);
1199 sub mountpoint_mount_path
{
1200 my ($mountpoint, $storage_cfg, $snapname) = @_;
1202 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1210 if ($line =~ m
@^(/dev/loop\d
+):@) {
1214 my $cmd = ['losetup', '--associated', $path];
1215 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1219 # Run a function with a file attached to a loop device.
1220 # The loop device is always detached afterwards (or set to autoclear).
1221 # Returns the loop device.
1222 sub run_with_loopdev
{
1223 my ($func, $file, $readonly) = @_;
1224 my $device = query_loopdev
($file);
1225 # Try to reuse an existing device
1227 # We assume that whoever setup the loop device is responsible for
1235 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1245 push @$losetup_cmd, '-r' if $readonly;
1246 PVE
::Tools
::run_command
($losetup_cmd, outfunc
=> $parser);
1247 die "failed to setup loop device for $file\n" if !$device;
1248 eval { &$func($device); };
1250 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1255 # In scalar mode: returns a file handle to the deepest directory node.
1256 # In list context: returns a list of:
1257 # * the deepest directory node
1258 # * the 2nd deepest directory (parent of the above)
1259 # * directory name of the last directory
1260 # So that the path $2/$3 should lead to $1 afterwards.
1261 sub walk_tree_nofollow
($$$) {
1262 my ($start, $subdir, $mkdir) = @_;
1264 # splitdir() returns '' for empty components including the leading /
1265 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1267 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1268 or die "failed to open start directory $start: $!\n";
1271 my $last_component = undef;
1273 foreach my $component (@comps) {
1274 $dir .= "/$component";
1275 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1278 # failed, check for symlinks and try to create the path
1279 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1280 die "cannot open directory $dir: $!\n" if !$mkdir;
1282 # We don't check for errors on mkdirat() here and just try to
1283 # openat() again, since at least one error (EEXIST) is an
1284 # expected possibility if multiple containers start
1285 # simultaneously. If someone else injects a symlink now then
1286 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1287 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1289 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1290 die "failed to create path: $dir: $!\n" if !$next;
1293 close $second if defined($last_component);
1294 $last_component = $component;
1299 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1300 close $second if defined($last_component);
1304 # To guard against symlink attack races against other currently running
1305 # containers with shared recursive bind mount hierarchies we prepare a
1306 # directory handle for the directory we're mounting over to verify the
1307 # mountpoint afterwards.
1308 sub __bindmount_prepare
{
1309 my ($hostroot, $dir) = @_;
1310 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1314 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1315 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1316 # we intended to bind mount.
1317 sub __bindmount_verify
{
1318 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1321 # Open the mount point path coming from the parent directory since the
1322 # filehandle we would have gotten as first result of walk_tree_nofollow
1323 # earlier is still a handle to the underlying directory instead of the
1325 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1326 die "failed to open mount point: $!\n" if !$destdh;
1329 # no separate function because 99% of the time it's the wrong thing to use.
1330 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1331 die "failed to mark bind mount read only\n";
1333 die "read-only check failed: $!\n" if $! != EROFS
;
1336 # For the rootfs we don't have a parentfd so we open the path directly.
1337 # Note that this means bindmounting any prefix of the host's
1338 # /var/lib/lxc/$vmid path into another container is considered a grave
1340 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1341 die "failed to open mount point: $!\n" if !$destdh;
1344 my ($srcdev, $srcinode) = stat($srcdh);
1345 my ($dstdev, $dstinode) = stat($destdh);
1349 return ($srcdev == $dstdev && $srcinode == $dstinode);
1352 # Perform the actual bind mounting:
1353 sub __bindmount_do
{
1354 my ($dir, $dest, $ro, @extra_opts) = @_;
1355 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1357 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1359 warn "bindmount error\n";
1360 # don't leave writable bind-mounts behind...
1361 PVE
::Tools
::run_command
(['umount', $dest]);
1368 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1370 my $srcdh = __bindmount_prepare
('/', $dir);
1372 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1374 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1375 PVE
::Tools
::run_command
(['umount', $dest]);
1376 die "detected mount path change at: $dir\n";
1380 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1381 # from $rootdir and $mount and walk the path from $rootdir to the final
1382 # directory to check for symlinks.
1383 sub __mount_prepare_rootdir
{
1384 my ($rootdir, $mount) = @_;
1385 $rootdir =~ s!/+!/!g;
1386 $rootdir =~ s!/+$!!;
1387 my $mount_path = "$rootdir/$mount";
1388 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1);
1389 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1392 # use $rootdir = undef to just return the corresponding mount path
1393 sub mountpoint_mount
{
1394 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1396 my $volid = $mountpoint->{volume
};
1397 my $mount = $mountpoint->{mp
};
1398 my $type = $mountpoint->{type
};
1399 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1402 return if !$volid || !$mount;
1407 my ($mpfd, $parentfd, $last_dir);
1409 if (defined($rootdir)) {
1410 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1411 __mount_prepare_rootdir
($rootdir, $mount);
1414 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1416 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1419 my $acl = $mountpoint->{acl
};
1420 if (defined($acl)) {
1421 $optstring .= ($acl ?
'acl' : 'noacl');
1423 my $readonly = $mountpoint->{ro
};
1426 @extra_opts = ('-o', $optstring) if $optstring;
1430 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1432 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid, $snapname);
1434 $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname) if !defined($path);
1436 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1437 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1439 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1441 if ($format eq 'subvol') {
1444 if ($scfg->{type
} eq 'zfspool') {
1445 my $path_arg = $path;
1446 $path_arg =~ s!^/+!!;
1447 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1449 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1452 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1453 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1454 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1455 $name .= "\@$snapname" if defined($snapname);
1456 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1458 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1459 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1462 return wantarray ?
($path, 0, undef) : $path;
1463 } elsif ($format eq 'raw' || $format eq 'iso') {
1464 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1465 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1466 # Our autodev hook expects the /dev/dm-* device currently
1467 # and will create the /dev/mapper symlink accordingly
1468 $path = Cwd
::realpath
($path);
1469 die "failed to get device path\n" if !$path;
1470 ($path) = ($path =~ /^(.*)$/s); #untaint
1474 if ($format eq 'iso') {
1475 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1476 } elsif ($isBase || defined($snapname)) {
1477 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1480 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1482 push @extra_opts, '-o', 'ro' if $readonly;
1483 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1487 my $use_loopdev = 0;
1488 if ($scfg->{path
}) {
1489 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1491 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1492 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1493 $mounted_dev = $path;
1496 die "unsupported storage type '$scfg->{type}'\n";
1498 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1500 die "unsupported image format '$format'\n";
1502 } elsif ($type eq 'device') {
1503 push @extra_opts, '-o', 'ro' if $readonly;
1504 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1505 # See the NOTE above about devicemapper canonicalization
1506 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1507 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1508 return wantarray ?
($volid, 0, $devpath) : $volid;
1509 } elsif ($type eq 'bind') {
1510 die "directory '$volid' does not exist\n" if ! -d
$volid;
1511 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1512 warn "cannot enable quota control for bind mounts\n" if $quota;
1513 return wantarray ?
($volid, 0, undef) : $volid;
1516 die "unsupported storage";
1520 my ($dev, $rootuid, $rootgid) = @_;
1522 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1523 '-E', "root_owner=$rootuid:$rootgid",
1528 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1530 if ($volid =~ m!^/dev/.+!) {
1535 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1537 die "cannot format volume '$volid' with no storage\n" if !$storage;
1539 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1541 my $path = PVE
::Storage
::map_volume
($storage_cfg, $volid);
1543 $path = PVE
::Storage
::path
($storage_cfg, $volid) if !defined($path);
1545 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1546 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1548 die "cannot format volume '$volid' (format == $format)\n"
1549 if $format ne 'raw';
1551 mkfs
($path, $rootuid, $rootgid);
1555 my ($storecfg, $vollist) = @_;
1557 foreach my $volid (@$vollist) {
1558 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1564 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1566 my $needs_chown = 0;
1569 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1570 # fixme: use better naming ct-$vmid-disk-X.raw?
1574 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs' || $scfg->{type
} eq 'cifs' ) {
1576 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1580 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1584 } elsif ($scfg->{type
} eq 'zfspool') {
1586 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1589 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1591 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1594 } elsif ($scfg->{type
} eq 'rbd') {
1596 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1599 die "unable to create containers on storage type '$scfg->{type}'\n";
1601 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1604 # in case formatting got interrupted:
1605 if (defined($volid)) {
1606 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1612 return ($volid, $needs_chown);
1615 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1617 my ($storecfg, $vmid, $settings, $conf) = @_;
1622 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1623 my $chown_vollist = [];
1625 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1626 my ($ms, $mountpoint) = @_;
1628 my $volid = $mountpoint->{volume
};
1629 my $mp = $mountpoint->{mp
};
1631 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1633 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1634 my ($storeid, $size_gb) = ($1, $2);
1636 my $size_kb = int(${size_gb
}*1024) * 1024;
1638 my $needs_chown = 0;
1639 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1640 push @$chown_vollist, $volid if $needs_chown;
1641 push @$vollist, $volid;
1642 $mountpoint->{volume
} = $volid;
1643 $mountpoint->{size
} = $size_kb * 1024;
1644 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1646 # use specified/existing volid/dir/device
1647 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1651 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1652 foreach my $volid (@$chown_vollist) {
1653 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1654 chown($rootuid, $rootgid, $path);
1656 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1658 # free allocated images on error
1660 destroy_disks
($storecfg, $vollist);
1666 sub update_disksize
{
1667 my ($vmid, $conf, $all_volumes) = @_;
1670 my $prefix = "CT $vmid:";
1672 my $update_mp = sub {
1673 my ($key, $mp, @param) = @_;
1674 my $size = $all_volumes->{$mp->{volume
}}->{size
} // 0;
1676 if (!defined($mp->{size
}) || $size != $mp->{size
}) {
1678 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1679 $mp->{size
} = $size;
1680 my $nomp = 1 if ($key eq 'rootfs');
1681 $conf->{$key} = PVE
::LXC
::Config-
>print_ct_mountpoint($mp, $nomp);
1685 PVE
::LXC
::Config-
>foreach_mountpoint($conf, $update_mp);
1691 my ($vmid, $conf, $all_volumes) = @_;
1694 my $prefix = "CT $vmid:";
1696 # Note: it is allowed to define multiple storage entries with the same path
1697 # (alias), so we need to check both 'volid' and real 'path' (two different
1698 # volid can point to the same path).
1700 # used and unused disks
1704 foreach my $opt (keys %$conf) {
1705 next if ($opt !~ m/^unused\d+$/);
1706 my $vol = $all_volumes->{$conf->{$opt}};
1707 $refpath->{$vol->{path
}} = $vol->{volid
};
1710 foreach my $key (keys %$all_volumes) {
1711 my $vol = $all_volumes->{$key};
1712 my $in_use = PVE
::LXC
::Config-
>is_volume_in_use($conf, $vol->{volid
});
1713 my $path = $vol->{path
};
1716 $refpath->{$path} = $key;
1717 delete $orphans->{$path};
1719 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
1720 $orphans->{$path} = $key;
1725 for my $key (keys %$orphans) {
1726 my $disk = $orphans->{$key};
1727 my $unused = PVE
::LXC
::Config-
>add_unused_volume($conf, $disk);
1731 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
1739 my ($cfg, $vmid) = @_;
1741 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid);
1743 my $all_volumes = {};
1744 foreach my $storeid (keys %$info) {
1745 foreach my $item (@{$info->{$storeid}}) {
1746 my $volid = $item->{volid
};
1747 next if !($volid && $item->{size
});
1748 $item->{path
} = PVE
::Storage
::path
($cfg, $volid);
1749 $all_volumes->{$volid} = $item;
1753 return $all_volumes;
1757 my ($vmid, $nolock, $dryrun) = @_;
1759 my $cfg = PVE
::Storage
::config
();
1761 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
1762 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
1763 foreach my $stor (keys %{$cfg->{ids
}}) {
1764 delete($cfg->{ids
}->{$stor}) if !$cfg->{ids
}->{$stor}->{content
}->{rootdir
};
1767 print "rescan volumes...\n";
1768 my $all_volumes = scan_volids
($cfg, $vmid);
1770 my $updatefn = sub {
1774 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
1776 PVE
::LXC
::Config-
>check_lock($conf);
1779 foreach my $volid (keys %$all_volumes) {
1780 my $info = $all_volumes->{$volid};
1781 $vm_volids->{$volid} = $info if $info->{vmid
} == $vmid;
1784 my $upu = update_unused
($vmid, $conf, $vm_volids);
1785 my $upd = update_disksize
($vmid, $conf, $vm_volids);
1786 $changes = $upu || $upd;
1788 PVE
::LXC
::Config-
>write_config($vmid, $conf) if $changes && !$dryrun;
1791 if (defined($vmid)) {
1795 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
1798 my $vmlist = config_list
();
1799 foreach my $vmid (keys %$vmlist) {
1803 PVE
::LXC
::Config-
>lock_config($vmid, $updatefn, $vmid);
1810 # bash completion helper
1812 sub complete_os_templates
{
1813 my ($cmdname, $pname, $cvalue) = @_;
1815 my $cfg = PVE
::Storage
::config
();
1819 if ($cvalue =~ m/^([^:]+):/) {
1823 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
1824 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
1827 foreach my $id (keys %$data) {
1828 foreach my $item (@{$data->{$id}}) {
1829 push @$res, $item->{volid
} if defined($item->{volid
});
1836 my $complete_ctid_full = sub {
1839 my $idlist = vmstatus
();
1841 my $active_hash = list_active_containers
();
1845 foreach my $id (keys %$idlist) {
1846 my $d = $idlist->{$id};
1847 if (defined($running)) {
1848 next if $d->{template
};
1849 next if $running && !$active_hash->{$id};
1850 next if !$running && $active_hash->{$id};
1859 return &$complete_ctid_full();
1862 sub complete_ctid_stopped
{
1863 return &$complete_ctid_full(0);
1866 sub complete_ctid_running
{
1867 return &$complete_ctid_full(1);
1877 my $lxc = $conf->{lxc
};
1878 foreach my $entry (@$lxc) {
1879 my ($key, $value) = @$entry;
1880 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1881 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
1882 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1883 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1884 push @$id_map, [$type, $ct, $host, $length];
1886 $rootuid = $host if $type eq 'u';
1887 $rootgid = $host if $type eq 'g';
1890 die "failed to parse idmap: $value\n";
1894 if (!@$id_map && $conf->{unprivileged
}) {
1895 # Should we read them from /etc/subuid?
1896 $id_map = [ ['u', '0', '100000', '65536'],
1897 ['g', '0', '100000', '65536'] ];
1898 $rootuid = $rootgid = 100000;
1901 return ($id_map, $rootuid, $rootgid);
1904 sub userns_command
{
1907 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1913 my ($vmid, $conf, $skiplock) = @_;
1915 update_lxc_config
($vmid, $conf);
1917 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1920 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1924 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1926 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-start', 1);
1927 eval { PVE
::Tools
::run_command
($cmd); };
1929 unlink $skiplock_flag_fn;
1932 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'post-start');
1937 # Helper to stop a container completely and make sure it has stopped completely.
1938 # This is necessary because we want the post-stop hook to have completed its
1939 # unmount-all step, but post-stop happens after lxc puts the container into the
1941 # $kill - if true it will always do an immediate hard-stop
1942 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
1943 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
1945 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
1947 # Open the container's command socket.
1948 my $path = "\0/var/lib/lxc/$vmid/command";
1949 my $sock = IO
::Socket
::UNIX-
>new(
1950 Type
=> SOCK_STREAM
(),
1954 return if $! == ECONNREFUSED
; # The container is not running
1955 die "failed to open container ${vmid}'s command socket: $!\n";
1958 my $conf = PVE
::LXC
::Config-
>load_config($vmid);
1959 PVE
::GuestHelpers
::exec_hookscript
($conf, $vmid, 'pre-stop');
1961 # Stop the container:
1963 my $cmd = ['lxc-stop', '-n', $vmid];
1966 push @$cmd, '--kill'; # doesn't allow timeouts
1968 # lxc-stop uses a default timeout
1969 push @$cmd, '--nokill' if !$kill_after_timeout;
1971 if (defined($shutdown_timeout)) {
1972 push @$cmd, '--timeout', $shutdown_timeout;
1973 # Give run_command 5 extra seconds
1974 $shutdown_timeout += 5;
1978 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
1983 my $result = <$sock>;
1985 return if !defined $result; # monitor is gone and the ct has stopped.
1986 die "container did not stop\n";
1992 return PVE
::Tools
::run_fork
(sub {
1993 # Unshare the mount namespace
1994 die "failed to unshare mount namespace: $!\n"
1995 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
1996 PVE
::Tools
::run_command
(['mount', '--make-rslave', '/']);
2001 my $copy_volume = sub {
2002 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit) = @_;
2004 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
2005 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
2007 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
2008 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
2014 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname);
2015 push @mounted, $src;
2017 mountpoint_mount
($dst_mp, $dest, $storage_cfg);
2018 push @mounted, $dest;
2022 PVE
::Tools
::run_command
(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2023 '-aH', '--whole-file', '--sparse', '--one-file-system',
2024 "--bwlimit=$bwlimit", "$src/", $dest]);
2027 foreach my $mount (reverse @mounted) {
2028 eval { PVE
::Tools
::run_command
(['/bin/umount', '--lazy', $mount], errfunc
=> sub{})};
2029 warn "Can't umount $mount\n" if $@;
2032 # If this fails they're used as mount points in a concurrent operation
2033 # (which should not happen but there's also no real need to get rid of them).
2040 # Should not be called after unsharing the mount namespace!
2042 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2044 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
2045 File
::Path
::make_path
("/var/lib/lxc/$vmid");
2046 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2047 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2049 # get id's for unprivileged container
2050 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
2052 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2053 # are visible in this namespace, otherwise the host only sees the empty
2054 # (not-mounted) directory.
2057 # Make sure $mp contains a correct size.
2058 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
2060 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
2062 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
2063 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
2064 chown($rootuid, $rootgid, $path);
2068 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit);
2072 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
2073 if defined($new_volid);