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
;
30 use Time
::HiRes qw
(gettimeofday
);
32 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
34 my $nodename = PVE
::INotify
::nodename
();
36 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
39 my $vmlist = PVE
::Cluster
::get_vmlist
();
41 return $res if !$vmlist || !$vmlist->{ids
};
42 my $ids = $vmlist->{ids
};
44 foreach my $vmid (keys %$ids) {
45 next if !$vmid; # skip CT0
46 my $d = $ids->{$vmid};
47 next if !$d->{node
} || $d->{node
} ne $nodename;
48 next if !$d->{type
} || $d->{type
} ne 'lxc';
49 $res->{$vmid} = { type
=> 'lxc', vmid
=> $vmid };
57 unlink PVE
::LXC
::Config-
>config_file($vmid, $nodename);
60 # container status helpers
62 sub list_active_containers
{
64 my $filename = "/proc/net/unix";
66 # similar test is used by lcxcontainers.c: list_active_containers
69 my $fh = IO
::File-
>new ($filename, "r");
72 while (defined(my $line = <$fh>)) {
73 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
75 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
86 # warning: this is slow
90 my $active_hash = list_active_containers
();
92 return 1 if defined($active_hash->{$vmid});
97 sub get_container_disk_usage
{
98 my ($vmid, $pid) = @_;
100 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
103 my $last_proc_vmid_stat;
105 my $parse_cpuacct_stat = sub {
106 my ($vmid, $unprivileged) = @_;
108 my $raw = read_cgroup_value
('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
112 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
122 our $vmstatus_return_properties = {
123 vmid
=> get_standard_option
('pve-vmid'),
125 description
=> "LXC Container status.",
127 enum
=> ['stopped', 'running'],
130 description
=> "Maximum memory in bytes.",
136 description
=> "Maximum SWAP memory in bytes.",
142 description
=> "Root disk size in bytes.",
148 description
=> "Container name.",
153 description
=> "Uptime.",
156 renderer
=> 'duration',
159 description
=> "Maximum usable CPUs.",
168 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc', vmid
=> $opt_vmid }} : config_list
();
170 my $active_hash = list_active_containers
();
172 my $cpucount = $cpuinfo->{cpus
} || 1;
174 my $cdtime = gettimeofday
;
176 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
177 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
179 my $unprivileged = {};
181 foreach my $vmid (keys %$list) {
182 my $d = $list->{$vmid};
184 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
185 warn $@ if $@; # ignore errors (consider them stopped)
187 $d->{status
} = $d->{pid
} ?
'running' : 'stopped';
189 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
190 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
192 $unprivileged->{$vmid} = $conf->{unprivileged
};
194 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
195 $d->{name
} =~ s/[\s]//g;
197 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
198 $d->{cpus
} = $cpucount if !$d->{cpus
};
200 $d->{lock} = $conf->{lock} || '';
203 my $res = get_container_disk_usage
($vmid, $d->{pid
});
204 $d->{disk
} = $res->{used
};
205 $d->{maxdisk
} = $res->{total
};
208 # use 4GB by default ??
209 if (my $rootfs = $conf->{rootfs
}) {
210 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($rootfs);
211 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
213 $d->{maxdisk
} = 4*1024*1024*1024;
219 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
220 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
231 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
234 foreach my $vmid (keys %$list) {
235 my $d = $list->{$vmid};
238 next if !$pid; # skip stopped CTs
240 my $proc_pid_stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
241 $d->{uptime
} = int(($uptime - $proc_pid_stat->{starttime
}) / $clock_ticks); # the method lxcfs uses
243 my $unpriv = $unprivileged->{$vmid};
245 if (-d
'/sys/fs/cgroup/memory') {
246 my $memory_stat = read_cgroup_list
('memory', $vmid, $unpriv, 'memory.stat');
247 my $mem_usage_in_bytes = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
249 $d->{mem
} = $mem_usage_in_bytes - $memory_stat->{total_cache
};
250 $d->{swap
} = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
256 if (-d
'/sys/fs/cgroup/blkio') {
257 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, $unpriv, 'blkio.throttle.io_service_bytes', 1);
258 my @bytes = split(/\n/, $blkio_bytes);
259 foreach my $byte (@bytes) {
260 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
261 $d->{diskread
} += $2 if $key eq 'Read';
262 $d->{diskwrite
} += $2 if $key eq 'Write';
270 if (-d
'/sys/fs/cgroup/cpuacct') {
271 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
273 my $used = $pstat->{utime} + $pstat->{stime
};
275 my $old = $last_proc_vmid_stat->{$vmid};
277 $last_proc_vmid_stat->{$vmid} = {
285 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
288 my $dutime = $used - $old->{used
};
290 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
291 $last_proc_vmid_stat->{$vmid} = {
297 $d->{cpu
} = $old->{cpu
};
304 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
306 foreach my $dev (keys %$netdev) {
307 next if $dev !~ m/^veth([1-9]\d*)i/;
309 my $d = $list->{$vmid};
313 $d->{netout
} += $netdev->{$dev}->{receive
};
314 $d->{netin
} += $netdev->{$dev}->{transmit
};
321 sub read_cgroup_list
($$$$) {
322 my ($group, $vmid, $unprivileged, $name) = @_;
324 my $content = read_cgroup_value
($group, $vmid, $unprivileged, $name, 1);
326 return { split(/\s+/, $content) };
329 sub read_cgroup_value
($$$$$) {
330 my ($group, $vmid, $unprivileged, $name, $full) = @_;
332 my $nsdir = $unprivileged ?
'' : 'ns/';
333 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
335 return PVE
::Tools
::file_get_contents
($path) if $full;
337 return PVE
::Tools
::file_read_firstline
($path);
340 sub write_cgroup_value
{
341 my ($group, $vmid, $name, $value) = @_;
343 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
344 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
348 sub find_lxc_console_pids
{
352 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
355 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
358 my @args = split(/\0/, $cmdline);
360 # search for lxc-console -n <vmid>
361 return if scalar(@args) != 3;
362 return if $args[1] ne '-n';
363 return if $args[2] !~ m/^\d+$/;
364 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
368 push @{$res->{$vmid}}, $pid;
380 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
382 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
384 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
389 # Note: we cannot use Net:IP, because that only allows strict
391 sub parse_ipv4_cidr
{
392 my ($cidr, $noerr) = @_;
394 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
395 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
398 return undef if $noerr;
400 die "unable to parse ipv4 address/mask\n";
403 sub get_cgroup_subsystems
{
406 my $data = PVE
::Tools
::file_get_contents
('/proc/self/cgroup');
407 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
410 $v1->{$_} = 1 foreach split(/,/, $type);
415 return wantarray ?
($v1, $v2) : $v1;
418 # Currently we do not need to create seccomp profile 'files' as the only
419 # choice our configuration actually allows is "with or without keyctl()",
420 # so we distinguish between using lxc's "default" seccomp profile and our
421 # added pve-userns.seccomp file.
423 # This returns a configuration line added to the raw lxc config.
424 sub make_seccomp_config
{
425 my ($conf, $unprivileged, $features) = @_;
426 # User-configured profile has precedence, note that the user's entry would
427 # be written 'after' this line anyway...
428 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.seccomp.profile')) {
429 # Warn the user if this conflicts with a feature:
430 if ($features->{keyctl
}) {
431 warn "explicitly configured lxc.seccomp.profile overrides the following settings: features:keyctl\n";
436 # Privileged containers keep using the default (which is already part of
437 # the files included via lxc.include, so we don't need to write it out,
438 # that way it stays admin-configurable via /usr/share/lxc/config/... as
440 return '' if !$unprivileged;
442 # Unprivileged containers will get keyctl() disabled by default as a
443 # workaround for systemd-networkd behavior. But we have an option to
444 # explicitly enable it:
445 return '' if $features->{keyctl
};
447 # Finally we're in an unprivileged container without `keyctl` set
448 # explicitly. We have a file prepared for this:
449 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
452 # Since lxc-3.0.2 we can have lxc generate a profile for the container
453 # automatically. The default should be equivalent to the old
454 # `lxc-container-default-cgns` profile.
456 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
457 # additional lines into the profile. We can use that to allow mounting specific
459 sub make_apparmor_config
{
460 my ($conf, $unprivileged, $features) = @_;
462 # user-configured profile has precedence, but first we go through our own
463 # code to figure out whether we should warn the user:
465 my $raw = "lxc.apparmor.profile = generated\n";
468 # There's lxc.apparmor.allow_nesting now, which will add the necessary
469 # apparmor lines, create an apparmor namespace for the container, but also
470 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
471 # lxcfs mounted over them, because that would prevent the container from
472 # mounting new instances of them for nested containers.
473 if ($features->{nesting
}) {
474 push @profile_uses, 'features:nesting';
475 $raw .= "lxc.apparmor.allow_nesting = 1\n"
477 # In the default profile in /etc/apparmor.d we patch this in because
478 # otherwise a container can for example run `chown` on /sys, breaking
479 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
480 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
481 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
482 # Preferably we could use the 'remount' flag but this does not sit well
483 # with apparmor_parser currently:
484 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
487 if (my $mount = $features->{mount
}) {
488 push @profile_uses, 'features:mount';
489 foreach my $fs (PVE
::Tools
::split_list
($mount)) {
490 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
496 if (PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.apparmor.profile')) {
497 if (length(my $used = join(', ', @profile_uses))) {
498 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
506 sub update_lxc_config
{
507 my ($vmid, $conf) = @_;
509 my $dir = "/var/lib/lxc/$vmid";
511 if ($conf->{template
}) {
513 unlink "$dir/config";
520 die "missing 'arch' - internal error" if !$conf->{arch
};
521 $raw .= "lxc.arch = $conf->{arch}\n";
523 my $custom_idmap = PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.idmap');
524 my $unprivileged = $conf->{unprivileged
} || $custom_idmap;
526 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
528 my $cfgpath = '/usr/share/lxc/config';
529 my $inc = "$cfgpath/$ostype.common.conf";
530 $inc ="$cfgpath/common.conf" if !-f
$inc;
531 $raw .= "lxc.include = $inc\n";
533 $inc = "$cfgpath/$ostype.userns.conf";
534 $inc = "$cfgpath/userns.conf" if !-f
$inc;
535 $raw .= "lxc.include = $inc\n";
538 my $features = PVE
::LXC
::Config-
>parse_features($conf->{features
});
540 $raw .= make_seccomp_config
($conf, $unprivileged, $features);
541 $raw .= make_apparmor_config
($conf, $unprivileged, $features);
543 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
544 # cannot be exposed to the container with r/w access (cgroup perms).
545 # When this is enabled mounts will still remain in the monitor's namespace
546 # after the container unmounted them and thus will not detach from their
547 # files while the container is running!
548 $raw .= "lxc.monitor.unshare = 1\n";
550 my $cgv1 = get_cgroup_subsystems
();
552 # Should we read them from /etc/subuid?
553 if ($unprivileged && !$custom_idmap) {
554 $raw .= "lxc.idmap = u 0 100000 65536\n";
555 $raw .= "lxc.idmap = g 0 100000 65536\n";
558 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
559 $raw .= "lxc.console.path = none\n";
560 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices
};
563 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
564 $raw .= "lxc.tty.max = $ttycount\n";
566 # some init scripts expect a linux terminal (turnkey).
567 $raw .= "lxc.environment = TERM=linux\n";
569 my $utsname = $conf->{hostname
} || "CT$vmid";
570 $raw .= "lxc.uts.name = $utsname\n";
572 if ($cgv1->{memory
}) {
573 my $memory = $conf->{memory
} || 512;
574 my $swap = $conf->{swap
} // 0;
576 my $lxcmem = int($memory*1024*1024);
577 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
579 my $lxcswap = int(($memory + $swap)*1024*1024);
580 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
584 if (my $cpulimit = $conf->{cpulimit
}) {
585 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
586 my $value = int(100000*$cpulimit);
587 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
590 my $shares = $conf->{cpuunits
} || 1024;
591 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
594 die "missing 'rootfs' configuration\n"
595 if !defined($conf->{rootfs
});
597 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
599 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
601 foreach my $k (sort keys %$conf) {
602 next if $k !~ m/^net(\d+)$/;
604 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
605 $raw .= "lxc.net.$ind.type = veth\n";
606 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
607 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
608 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
609 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu
});
612 if ($cgv1->{cpuset
}) {
614 if (my $lxcconf = $conf->{lxc
}) {
615 foreach my $entry (@$lxcconf) {
616 my ($k, $v) = @$entry;
617 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
622 my $cores = $conf->{cores
};
623 if (!$had_cpuset && $cores) {
624 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup('lxc', 'effective_cpus') };
625 $cpuset = PVE
::CpuSet-
>new_from_cgroup('', 'effective_cpus') if !$cpuset;
626 my @members = $cpuset->members();
627 while (scalar(@members) > $cores) {
628 my $randidx = int(rand(scalar(@members)));
629 $cpuset->delete($members[$randidx]);
630 splice(@members, $randidx, 1); # keep track of the changes
632 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
636 File
::Path
::mkpath
("$dir/rootfs");
638 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
641 # verify and cleanup nameserver list (replace \0 with ' ')
642 sub verify_nameserver_list
{
643 my ($nameserver_list) = @_;
646 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
647 PVE
::JSONSchema
::pve_verify_ip
($server);
651 return join(' ', @list);
654 sub verify_searchdomain_list
{
655 my ($searchdomain_list) = @_;
658 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
659 # todo: should we add checks for valid dns domains?
663 return join(' ', @list);
666 sub get_console_command
{
667 my ($vmid, $conf, $escapechar) = @_;
669 # '-1' as $escapechar disables keyboard escape sequence
670 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
672 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
675 if ($cmode eq 'console') {
676 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
677 push @$cmd, '-e', $escapechar if $escapechar;
678 } elsif ($cmode eq 'tty') {
679 push @$cmd, 'lxc-console', '-n', $vmid;
680 push @$cmd, '-e', $escapechar if $escapechar;
681 } elsif ($cmode eq 'shell') {
682 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
684 die "internal error";
690 sub get_primary_ips
{
693 # return data from net0
695 return undef if !defined($conf->{net0
});
696 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
698 my $ipv4 = $net->{ip
};
700 if ($ipv4 =~ /^(dhcp|manual)$/) {
706 my $ipv6 = $net->{ip6
};
708 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
715 return ($ipv4, $ipv6);
718 sub delete_mountpoint_volume
{
719 my ($storage_cfg, $vmid, $volume) = @_;
721 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
723 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
724 PVE
::Storage
::vdisk_free
($storage_cfg, $volume) if $vmid == $owner;
727 sub destroy_lxc_container
{
728 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
730 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
731 my ($ms, $mountpoint) = @_;
732 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
735 rmdir "/var/lib/lxc/$vmid/rootfs";
736 unlink "/var/lib/lxc/$vmid/config";
737 rmdir "/var/lib/lxc/$vmid";
738 if (defined $replacement_conf) {
739 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
741 destroy_config
($vmid);
744 #my $cmd = ['lxc-destroy', '-n', $vmid ];
745 #PVE::Tools::run_command($cmd);
748 sub vm_stop_cleanup
{
749 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
754 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
755 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
758 warn $@ if $@; # avoid errors - just warn
761 my $safe_num_ne = sub {
764 return 0 if !defined($a) && !defined($b);
765 return 1 if !defined($a);
766 return 1 if !defined($b);
771 my $safe_string_ne = sub {
774 return 0 if !defined($a) && !defined($b);
775 return 1 if !defined($a);
776 return 1 if !defined($b);
782 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
784 if ($newnet->{type
} ne 'veth') {
785 # for when there are physical interfaces
786 die "cannot update interface of type $newnet->{type}";
789 my $veth = "veth${vmid}i${netid}";
790 my $eth = $newnet->{name
};
792 if (my $oldnetcfg = $conf->{$opt}) {
793 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
795 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
796 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
798 PVE
::Network
::veth_delete
($veth);
799 delete $conf->{$opt};
800 PVE
::LXC
::Config-
>write_config($vmid, $conf);
802 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
805 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
806 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
807 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
809 if ($oldnet->{bridge
}) {
810 PVE
::Network
::tap_unplug
($veth);
811 foreach (qw(bridge tag firewall)) {
812 delete $oldnet->{$_};
814 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
815 PVE
::LXC
::Config-
>write_config($vmid, $conf);
818 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
819 # This includes the rate:
820 foreach (qw(bridge tag firewall rate)) {
821 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
823 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
824 # Rate can be applied on its own but any change above needs to
825 # include the rate in tap_plug since OVS resets everything.
826 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
827 $oldnet->{rate
} = $newnet->{rate
}
829 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
830 PVE
::LXC
::Config-
>write_config($vmid, $conf);
833 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
836 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
840 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
842 my $veth = "veth${vmid}i${netid}";
843 my $vethpeer = $veth . "p";
844 my $eth = $newnet->{name
};
846 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
847 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
849 # attach peer in container
850 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
851 PVE
::Tools
::run_command
($cmd);
853 # link up peer in container
854 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
855 PVE
::Tools
::run_command
($cmd);
857 my $done = { type
=> 'veth' };
858 foreach (qw(bridge tag firewall hwaddr name)) {
859 $done->{$_} = $newnet->{$_} if $newnet->{$_};
861 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
863 PVE
::LXC
::Config-
>write_config($vmid, $conf);
866 sub update_ipconfig
{
867 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
869 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
871 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
876 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
878 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
880 my $change_ip_config = sub {
881 my ($ipversion) = @_;
883 my $family_opt = "-$ipversion";
884 my $suffix = $ipversion == 4 ?
'' : $ipversion;
888 my $newip = $newnet->{$ip};
889 my $newgw = $newnet->{$gw};
890 my $oldip = $optdata->{$ip};
891 my $oldgw = $optdata->{$gw};
893 my $change_ip = &$safe_string_ne($oldip, $newip);
894 my $change_gw = &$safe_string_ne($oldgw, $newgw);
896 return if !$change_ip && !$change_gw;
898 # step 1: add new IP, if this fails we cancel
899 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
900 if ($change_ip && $is_real_ip) {
901 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
908 # step 2: replace gateway
909 # If this fails we delete the added IP and cancel.
910 # If it succeeds we save the config and delete the old IP, ignoring
911 # errors. The config is then saved.
912 # Note: 'ip route replace' can add
916 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
917 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
919 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
923 # the route was not replaced, the old IP is still available
924 # rollback (delete new IP) and cancel
926 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
927 warn $@ if $@; # no need to die here
932 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
933 # if the route was not deleted, the guest might have deleted it manually
937 if ($oldgw && $oldip && !PVE
::Network
::is_ip_in_cidr
($oldgw, $oldip)) {
938 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
939 # warn if the route was deleted manually
944 # from this point on we save the configuration
945 # step 3: delete old IP ignoring errors
946 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
947 # We need to enable promote_secondaries, otherwise our newly added
948 # address will be removed along with the old one.
951 if ($ipversion == 4) {
952 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
953 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
954 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
956 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
958 warn $@ if $@; # no need to die here
960 if ($ipversion == 4) {
961 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
965 foreach my $property ($ip, $gw) {
966 if ($newnet->{$property}) {
967 $optdata->{$property} = $newnet->{$property};
969 delete $optdata->{$property};
972 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
973 PVE
::LXC
::Config-
>write_config($vmid, $conf);
974 $lxc_setup->setup_network($conf);
977 &$change_ip_config(4);
978 &$change_ip_config(6);
982 my $enter_namespace = sub {
983 my ($vmid, $pid, $which, $type) = @_;
984 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
985 or die "failed to open $which namespace of container $vmid: $!\n";
986 PVE
::Tools
::setns
(fileno($fd), $type)
987 or die "failed to enter $which namespace of container $vmid: $!\n";
991 my $do_syncfs = sub {
992 my ($vmid, $pid, $socket) = @_;
994 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
996 # Tell the parent process to start reading our /proc/mounts
997 print {$socket} "go\n";
1000 # Receive /proc/self/mounts
1001 my $mountdata = do { local $/ = undef; <$socket> };
1004 # Now sync all mountpoints...
1005 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
1006 foreach my $mp (@$mounts) {
1007 my ($what, $dir, $fs) = @$mp;
1008 next if $fs eq 'fuse.lxcfs';
1009 eval { PVE
::Tools
::sync_mountpoint
($dir); };
1014 sub sync_container_namespace
{
1016 my $pid = find_lxc_pid
($vmid);
1018 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1019 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
1020 or die "failed to create socketpair: $!\n";
1023 die "fork failed: $!\n" if !defined($child);
1028 &$do_syncfs($vmid, $pid, $cfd);
1038 die "failed to enter container namespace\n" if $go ne "go\n";
1040 open my $mounts, '<', "/proc/$child/mounts"
1041 or die "failed to open container's /proc/mounts: $!\n";
1042 my $mountdata = do { local $/ = undef; <$mounts> };
1044 print {$pfd} $mountdata;
1047 while (waitpid($child, 0) != $child) {}
1048 die "failed to sync container namespace\n" if $? != 0;
1051 sub template_create
{
1052 my ($vmid, $conf) = @_;
1054 my $storecfg = PVE
::Storage
::config
();
1056 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1057 my ($ms, $mountpoint) = @_;
1059 my $volid = $mountpoint->{volume
};
1061 die "Template feature is not available for '$volid'\n"
1062 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
1065 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1066 my ($ms, $mountpoint) = @_;
1068 my $volid = $mountpoint->{volume
};
1070 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
1072 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
1073 $mountpoint->{volume
} = $template_volid;
1074 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1077 PVE
::LXC
::Config-
>write_config($vmid, $conf);
1080 sub check_ct_modify_config_perm
{
1081 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
1083 return 1 if $authuser eq 'root@pam';
1086 my ($opt, $delete) = @_;
1087 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1088 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1089 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1090 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1092 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
1093 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
1094 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
1095 if $data->{type
} ne 'volume';
1096 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1097 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1098 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1099 $opt eq 'searchdomain' || $opt eq 'hostname') {
1100 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1101 } elsif ($opt eq 'features') {
1102 # For now this is restricted to root@pam
1103 raise_perm_exc
("changing feature flags is only allowed for root\@pam");
1105 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1109 foreach my $opt (keys %$newconf) {
1112 foreach my $opt (@$delete) {
1120 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1122 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1123 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1125 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
1126 my ($ms, $mountpoint) = @_;
1128 my $volid = $mountpoint->{volume
};
1129 my $mount = $mountpoint->{mp
};
1131 return if !$volid || !$mount;
1133 my $mount_path = "$rootdir/$mount";
1134 $mount_path =~ s!/+!/!g;
1136 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
1139 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
1152 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1154 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1155 File
::Path
::make_path
($rootdir);
1157 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
1158 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
1161 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
1162 my ($ms, $mountpoint) = @_;
1164 $mountpoint->{ro
} = 0 if $ignore_ro;
1166 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg);
1170 warn "mounting container failed\n";
1171 umount_all
($vmid, $storage_cfg, $conf, 1);
1179 sub mountpoint_mount_path
{
1180 my ($mountpoint, $storage_cfg, $snapname) = @_;
1182 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1190 if ($line =~ m
@^(/dev/loop\d
+):@) {
1194 my $cmd = ['losetup', '--associated', $path];
1195 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1199 # Run a function with a file attached to a loop device.
1200 # The loop device is always detached afterwards (or set to autoclear).
1201 # Returns the loop device.
1202 sub run_with_loopdev
{
1203 my ($func, $file, $readonly) = @_;
1204 my $device = query_loopdev
($file);
1205 # Try to reuse an existing device
1207 # We assume that whoever setup the loop device is responsible for
1215 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1225 push @$losetup_cmd, '-r' if $readonly;
1226 PVE
::Tools
::run_command
($losetup_cmd, outfunc
=> $parser);
1227 die "failed to setup loop device for $file\n" if !$device;
1228 eval { &$func($device); };
1230 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1235 # In scalar mode: returns a file handle to the deepest directory node.
1236 # In list context: returns a list of:
1237 # * the deepest directory node
1238 # * the 2nd deepest directory (parent of the above)
1239 # * directory name of the last directory
1240 # So that the path $2/$3 should lead to $1 afterwards.
1241 sub walk_tree_nofollow
($$$) {
1242 my ($start, $subdir, $mkdir) = @_;
1244 # splitdir() returns '' for empty components including the leading /
1245 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1247 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1248 or die "failed to open start directory $start: $!\n";
1251 my $last_component = undef;
1253 foreach my $component (@comps) {
1254 $dir .= "/$component";
1255 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1258 # failed, check for symlinks and try to create the path
1259 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1260 die "cannot open directory $dir: $!\n" if !$mkdir;
1262 # We don't check for errors on mkdirat() here and just try to
1263 # openat() again, since at least one error (EEXIST) is an
1264 # expected possibility if multiple containers start
1265 # simultaneously. If someone else injects a symlink now then
1266 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1267 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1269 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1270 die "failed to create path: $dir: $!\n" if !$next;
1273 close $second if defined($last_component);
1274 $last_component = $component;
1279 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1280 close $second if defined($last_component);
1284 # To guard against symlink attack races against other currently running
1285 # containers with shared recursive bind mount hierarchies we prepare a
1286 # directory handle for the directory we're mounting over to verify the
1287 # mountpoint afterwards.
1288 sub __bindmount_prepare
{
1289 my ($hostroot, $dir) = @_;
1290 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1294 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1295 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1296 # we intended to bind mount.
1297 sub __bindmount_verify
{
1298 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1301 # Open the mount point path coming from the parent directory since the
1302 # filehandle we would have gotten as first result of walk_tree_nofollow
1303 # earlier is still a handle to the underlying directory instead of the
1305 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1306 die "failed to open mount point: $!\n" if !$destdh;
1309 # no separate function because 99% of the time it's the wrong thing to use.
1310 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1311 die "failed to mark bind mount read only\n";
1313 die "read-only check failed: $!\n" if $! != EROFS
;
1316 # For the rootfs we don't have a parentfd so we open the path directly.
1317 # Note that this means bindmounting any prefix of the host's
1318 # /var/lib/lxc/$vmid path into another container is considered a grave
1320 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1321 die "failed to open mount point: $!\n" if !$destdh;
1324 my ($srcdev, $srcinode) = stat($srcdh);
1325 my ($dstdev, $dstinode) = stat($destdh);
1329 return ($srcdev == $dstdev && $srcinode == $dstinode);
1332 # Perform the actual bind mounting:
1333 sub __bindmount_do
{
1334 my ($dir, $dest, $ro, @extra_opts) = @_;
1335 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1337 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1339 warn "bindmount error\n";
1340 # don't leave writable bind-mounts behind...
1341 PVE
::Tools
::run_command
(['umount', $dest]);
1348 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1350 my $srcdh = __bindmount_prepare
('/', $dir);
1352 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1354 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1355 PVE
::Tools
::run_command
(['umount', $dest]);
1356 die "detected mount path change at: $dir\n";
1360 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1361 # from $rootdir and $mount and walk the path from $rootdir to the final
1362 # directory to check for symlinks.
1363 sub __mount_prepare_rootdir
{
1364 my ($rootdir, $mount) = @_;
1365 $rootdir =~ s!/+!/!g;
1366 $rootdir =~ s!/+$!!;
1367 my $mount_path = "$rootdir/$mount";
1368 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1);
1369 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1372 # use $rootdir = undef to just return the corresponding mount path
1373 sub mountpoint_mount
{
1374 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1376 my $volid = $mountpoint->{volume
};
1377 my $mount = $mountpoint->{mp
};
1378 my $type = $mountpoint->{type
};
1379 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1382 return if !$volid || !$mount;
1387 my ($mpfd, $parentfd, $last_dir);
1389 if (defined($rootdir)) {
1390 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1391 __mount_prepare_rootdir
($rootdir, $mount);
1394 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1396 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1399 my $acl = $mountpoint->{acl
};
1400 if (defined($acl)) {
1401 $optstring .= ($acl ?
'acl' : 'noacl');
1403 my $readonly = $mountpoint->{ro
};
1406 @extra_opts = ('-o', $optstring) if $optstring;
1410 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1412 # early sanity checks:
1413 # we otherwise call realpath on the rbd url
1414 die "containers on rbd storage without krbd are not supported\n"
1415 if $scfg->{type
} eq 'rbd' && !$scfg->{krbd
};
1417 my $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname);
1419 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1420 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1422 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1424 if ($format eq 'subvol') {
1427 if ($scfg->{type
} eq 'zfspool') {
1428 my $path_arg = $path;
1429 $path_arg =~ s!^/+!!;
1430 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1432 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1435 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1436 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1437 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1438 $name .= "\@$snapname" if defined($snapname);
1439 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1441 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1442 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1445 return wantarray ?
($path, 0, undef) : $path;
1446 } elsif ($format eq 'raw' || $format eq 'iso') {
1447 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1448 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1449 # Our autodev hook expects the /dev/dm-* device currently
1450 # and will create the /dev/mapper symlink accordingly
1451 $path = Cwd
::realpath
($path);
1452 die "failed to get device path\n" if !$path;
1453 ($path) = ($path =~ /^(.*)$/s); #untaint
1457 if ($format eq 'iso') {
1458 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1459 } elsif ($isBase || defined($snapname)) {
1460 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1463 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1465 push @extra_opts, '-o', 'ro' if $readonly;
1466 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1470 my $use_loopdev = 0;
1471 if ($scfg->{path
}) {
1472 $mounted_dev = run_with_loopdev
($domount, $path, $readonly);
1474 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1475 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1476 $mounted_dev = $path;
1479 die "unsupported storage type '$scfg->{type}'\n";
1481 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1483 die "unsupported image format '$format'\n";
1485 } elsif ($type eq 'device') {
1486 push @extra_opts, '-o', 'ro' if $readonly;
1487 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1488 # See the NOTE above about devicemapper canonicalization
1489 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1490 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1491 return wantarray ?
($volid, 0, $devpath) : $volid;
1492 } elsif ($type eq 'bind') {
1493 die "directory '$volid' does not exist\n" if ! -d
$volid;
1494 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1495 warn "cannot enable quota control for bind mounts\n" if $quota;
1496 return wantarray ?
($volid, 0, undef) : $volid;
1499 die "unsupported storage";
1503 my ($dev, $rootuid, $rootgid) = @_;
1505 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1506 '-E', "root_owner=$rootuid:$rootgid",
1511 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1513 if ($volid =~ m!^/dev/.+!) {
1518 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1520 die "cannot format volume '$volid' with no storage\n" if !$storage;
1522 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1524 my $path = PVE
::Storage
::path
($storage_cfg, $volid);
1526 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1527 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1529 die "cannot format volume '$volid' (format == $format)\n"
1530 if $format ne 'raw';
1532 mkfs
($path, $rootuid, $rootgid);
1536 my ($storecfg, $vollist) = @_;
1538 foreach my $volid (@$vollist) {
1539 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1545 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1547 my $needs_chown = 0;
1550 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1551 # fixme: use better naming ct-$vmid-disk-X.raw?
1555 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs' || $scfg->{type
} eq 'cifs' ) {
1557 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1561 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1565 } elsif ($scfg->{type
} eq 'zfspool') {
1567 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1570 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1572 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1575 } elsif ($scfg->{type
} eq 'rbd') {
1577 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd
};
1578 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1581 die "unable to create containers on storage type '$scfg->{type}'\n";
1583 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1586 # in case formatting got interrupted:
1587 if (defined($volid)) {
1588 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1594 return ($volid, $needs_chown);
1597 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1599 my ($storecfg, $vmid, $settings, $conf) = @_;
1604 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1605 my $chown_vollist = [];
1607 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1608 my ($ms, $mountpoint) = @_;
1610 my $volid = $mountpoint->{volume
};
1611 my $mp = $mountpoint->{mp
};
1613 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1615 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1616 my ($storeid, $size_gb) = ($1, $2);
1618 my $size_kb = int(${size_gb
}*1024) * 1024;
1620 my $needs_chown = 0;
1621 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1622 push @$chown_vollist, $volid if $needs_chown;
1623 push @$vollist, $volid;
1624 $mountpoint->{volume
} = $volid;
1625 $mountpoint->{size
} = $size_kb * 1024;
1626 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1628 # use specified/existing volid/dir/device
1629 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1633 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1634 foreach my $volid (@$chown_vollist) {
1635 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1636 chown($rootuid, $rootgid, $path);
1638 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1640 # free allocated images on error
1642 destroy_disks
($storecfg, $vollist);
1648 # bash completion helper
1650 sub complete_os_templates
{
1651 my ($cmdname, $pname, $cvalue) = @_;
1653 my $cfg = PVE
::Storage
::config
();
1657 if ($cvalue =~ m/^([^:]+):/) {
1661 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
1662 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
1665 foreach my $id (keys %$data) {
1666 foreach my $item (@{$data->{$id}}) {
1667 push @$res, $item->{volid
} if defined($item->{volid
});
1674 my $complete_ctid_full = sub {
1677 my $idlist = vmstatus
();
1679 my $active_hash = list_active_containers
();
1683 foreach my $id (keys %$idlist) {
1684 my $d = $idlist->{$id};
1685 if (defined($running)) {
1686 next if $d->{template
};
1687 next if $running && !$active_hash->{$id};
1688 next if !$running && $active_hash->{$id};
1697 return &$complete_ctid_full();
1700 sub complete_ctid_stopped
{
1701 return &$complete_ctid_full(0);
1704 sub complete_ctid_running
{
1705 return &$complete_ctid_full(1);
1715 my $lxc = $conf->{lxc
};
1716 foreach my $entry (@$lxc) {
1717 my ($key, $value) = @$entry;
1718 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1719 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
1720 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1721 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1722 push @$id_map, [$type, $ct, $host, $length];
1724 $rootuid = $host if $type eq 'u';
1725 $rootgid = $host if $type eq 'g';
1728 die "failed to parse idmap: $value\n";
1732 if (!@$id_map && $conf->{unprivileged
}) {
1733 # Should we read them from /etc/subuid?
1734 $id_map = [ ['u', '0', '100000', '65536'],
1735 ['g', '0', '100000', '65536'] ];
1736 $rootuid = $rootgid = 100000;
1739 return ($id_map, $rootuid, $rootgid);
1742 sub userns_command
{
1745 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1751 my ($vmid, $conf, $skiplock) = @_;
1753 update_lxc_config
($vmid, $conf);
1755 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1758 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1762 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1764 eval { PVE
::Tools
::run_command
($cmd); };
1766 unlink $skiplock_flag_fn;
1773 # Helper to stop a container completely and make sure it has stopped completely.
1774 # This is necessary because we want the post-stop hook to have completed its
1775 # unmount-all step, but post-stop happens after lxc puts the container into the
1778 my ($vmid, $kill, $shutdown_timeout, $exit_timeout) = @_;
1780 # Open the container's command socket.
1781 my $path = "\0/var/lib/lxc/$vmid/command";
1782 my $sock = IO
::Socket
::UNIX-
>new(
1783 Type
=> SOCK_STREAM
(),
1787 return if $! == ECONNREFUSED
; # The container is not running
1788 die "failed to open container ${vmid}'s command socket: $!\n";
1791 # Stop the container:
1793 my $cmd = ['lxc-stop', '-n', $vmid];
1796 push @$cmd, '--kill'; # doesn't allow timeouts
1797 } elsif (defined($shutdown_timeout)) {
1798 push @$cmd, '--timeout', $shutdown_timeout;
1799 # Give run_command 5 extra seconds
1800 $shutdown_timeout += 5;
1803 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
1809 my $wait = sub { $result = <$sock>; };
1810 if (defined($exit_timeout)) {
1811 PVE
::Tools
::run_with_timeout
($exit_timeout, $wait);
1816 return if !defined $result; # monitor is gone and the ct has stopped.
1817 die "container did not stop\n";
1823 return PVE
::Tools
::run_fork
(sub {
1824 # Unshare the mount namespace
1825 die "failed to unshare mount namespace: $!\n"
1826 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
1827 PVE
::Tools
::run_command
(['mount', '--make-rslave', '/']);
1832 my $copy_volume = sub {
1833 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname) = @_;
1835 my $src_mp = { volume
=> $src_volid, mp
=> '/', ro
=> 1 };
1836 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
1838 my $dst_mp = { volume
=> $dst_volid, mp
=> '/', ro
=> 0 };
1839 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
1845 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname);
1846 push @mounted, $src;
1848 mountpoint_mount
($dst_mp, $dest, $storage_cfg);
1849 push @mounted, $dest;
1851 PVE
::Tools
::run_command
(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
1852 '-aH', '--whole-file', '--sparse', '--one-file-system',
1856 foreach my $mount (reverse @mounted) {
1857 eval { PVE
::Tools
::run_command
(['/bin/umount', '--lazy', $mount], errfunc
=> sub{})};
1858 warn "Can't umount $mount\n" if $@;
1861 # If this fails they're used as mount points in a concurrent operation
1862 # (which should not happen but there's also no real need to get rid of them).
1869 # Should not be called after unsharing the mount namespace!
1871 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname) = @_;
1873 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
1874 File
::Path
::make_path
("/var/lib/lxc/$vmid");
1875 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
1876 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
1878 # get id's for unprivileged container
1879 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1881 # Allocate the disk before unsharing in order to make sure zfs subvolumes
1882 # are visible in this namespace, otherwise the host only sees the empty
1883 # (not-mounted) directory.
1886 # Make sure $mp contains a correct size.
1887 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
1889 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
1891 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
1892 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
1893 chown($rootuid, $rootgid, $path);
1897 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname);
1901 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
1902 if defined($new_volid);