13 use Fcntl
qw(O_RDONLY);
15 use PVE
::Exception
qw(raise_perm_exc);
19 use PVE
::Tools
qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full);
21 use PVE
::AccessControl
;
24 use Time
::HiRes qw
(gettimeofday
);
28 my $nodename = PVE
::INotify
::nodename
();
30 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
32 our $COMMON_TAR_FLAGS = [ '--sparse', '--numeric-owner', '--acls',
34 '--xattrs-include=user.*',
35 '--xattrs-include=security.capability',
36 '--warning=no-xattr-write' ];
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';
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 {
108 my $raw = read_cgroup_value
('cpuacct', $vmid, 'cpuacct.stat', 1);
112 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
125 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc' }} : config_list
();
127 my $active_hash = list_active_containers
();
129 my $cpucount = $cpuinfo->{cpus
} || 1;
131 my $cdtime = gettimeofday
;
133 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
135 foreach my $vmid (keys %$list) {
136 my $d = $list->{$vmid};
138 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
139 warn $@ if $@; # ignore errors (consider them stopped)
141 $d->{status
} = $d->{pid
} ?
'running' : 'stopped';
143 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
144 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
146 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
147 $d->{name
} =~ s/[\s]//g;
149 $d->{cpus
} = $conf->{cpulimit
} || $cpucount;
151 $d->{lock} = $conf->{lock} || '';
154 my $res = get_container_disk_usage
($vmid, $d->{pid
});
155 $d->{disk
} = $res->{used
};
156 $d->{maxdisk
} = $res->{total
};
159 # use 4GB by default ??
160 if (my $rootfs = $conf->{rootfs
}) {
161 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($rootfs);
162 $d->{maxdisk
} = int(($rootinfo->{size
} || 4)*1024*1024)*1024;
164 $d->{maxdisk
} = 4*1024*1024*1024;
170 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
171 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
182 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
185 foreach my $vmid (keys %$list) {
186 my $d = $list->{$vmid};
189 next if !$pid; # skip stopped CTs
191 my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
192 $d->{uptime
} = time - $ctime; # the method lxcfs uses
194 $d->{mem
} = read_cgroup_value
('memory', $vmid, 'memory.usage_in_bytes');
195 $d->{swap
} = read_cgroup_value
('memory', $vmid, 'memory.memsw.usage_in_bytes') - $d->{mem
};
197 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, 'blkio.throttle.io_service_bytes', 1);
198 my @bytes = split(/\n/, $blkio_bytes);
199 foreach my $byte (@bytes) {
200 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
201 $d->{diskread
} = $2 if $key eq 'Read';
202 $d->{diskwrite
} = $2 if $key eq 'Write';
206 my $pstat = &$parse_cpuacct_stat($vmid);
208 my $used = $pstat->{utime} + $pstat->{stime
};
210 my $old = $last_proc_vmid_stat->{$vmid};
212 $last_proc_vmid_stat->{$vmid} = {
220 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
223 my $dutime = $used - $old->{used
};
225 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
226 $last_proc_vmid_stat->{$vmid} = {
232 $d->{cpu
} = $old->{cpu
};
236 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
238 foreach my $dev (keys %$netdev) {
239 next if $dev !~ m/^veth([1-9]\d*)i/;
241 my $d = $list->{$vmid};
245 $d->{netout
} += $netdev->{$dev}->{receive
};
246 $d->{netin
} += $netdev->{$dev}->{transmit
};
253 sub read_cgroup_value
{
254 my ($group, $vmid, $name, $full) = @_;
256 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
258 return PVE
::Tools
::file_get_contents
($path) if $full;
260 return PVE
::Tools
::file_read_firstline
($path);
263 sub write_cgroup_value
{
264 my ($group, $vmid, $name, $value) = @_;
266 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
267 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
271 sub find_lxc_console_pids
{
275 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
278 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
281 my @args = split(/\0/, $cmdline);
283 # search for lxc-console -n <vmid>
284 return if scalar(@args) != 3;
285 return if $args[1] ne '-n';
286 return if $args[2] !~ m/^\d+$/;
287 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
291 push @{$res->{$vmid}}, $pid;
303 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
305 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
307 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
312 # Note: we cannot use Net:IP, because that only allows strict
314 sub parse_ipv4_cidr
{
315 my ($cidr, $noerr) = @_;
317 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
318 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
321 return undef if $noerr;
323 die "unable to parse ipv4 address/mask\n";
327 sub update_lxc_config
{
328 my ($storage_cfg, $vmid, $conf) = @_;
330 my $dir = "/var/lib/lxc/$vmid";
332 if ($conf->{template
}) {
334 unlink "$dir/config";
341 die "missing 'arch' - internal error" if !$conf->{arch
};
342 $raw .= "lxc.arch = $conf->{arch}\n";
344 my $unprivileged = $conf->{unprivileged
};
345 my $custom_idmap = grep { $_->[0] eq 'lxc.id_map' } @{$conf->{lxc
}};
347 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
348 if ($ostype =~ /^(?:debian | ubuntu | centos | fedora | opensuse | archlinux | alpine | unmanaged)$/x) {
349 my $inc ="/usr/share/lxc/config/$ostype.common.conf";
350 $inc ="/usr/share/lxc/config/common.conf" if !-f
$inc;
351 $raw .= "lxc.include = $inc\n";
352 if ($unprivileged || $custom_idmap) {
353 $inc = "/usr/share/lxc/config/$ostype.userns.conf";
354 $inc = "/usr/share/lxc/config/userns.conf" if !-f
$inc;
355 $raw .= "lxc.include = $inc\n"
358 die "implement me (ostype $ostype)";
361 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
362 # cannot be exposed to the container with r/w access (cgroup perms).
363 # When this is enabled mounts will still remain in the monitor's namespace
364 # after the container unmounted them and thus will not detach from their
365 # files while the container is running!
366 $raw .= "lxc.monitor.unshare = 1\n";
368 # Should we read them from /etc/subuid?
369 if ($unprivileged && !$custom_idmap) {
370 $raw .= "lxc.id_map = u 0 100000 65536\n";
371 $raw .= "lxc.id_map = g 0 100000 65536\n";
374 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
375 $raw .= "lxc.console = none\n";
376 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
379 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
380 $raw .= "lxc.tty = $ttycount\n";
382 # some init scripts expect a linux terminal (turnkey).
383 $raw .= "lxc.environment = TERM=linux\n";
385 my $utsname = $conf->{hostname
} || "CT$vmid";
386 $raw .= "lxc.utsname = $utsname\n";
388 my $memory = $conf->{memory
} || 512;
389 my $swap = $conf->{swap
} // 0;
391 my $lxcmem = int($memory*1024*1024);
392 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
394 my $lxcswap = int(($memory + $swap)*1024*1024);
395 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
397 if (my $cpulimit = $conf->{cpulimit
}) {
398 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
399 my $value = int(100000*$cpulimit);
400 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
403 my $shares = $conf->{cpuunits
} || 1024;
404 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
406 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
408 $raw .= "lxc.rootfs = $dir/rootfs\n";
411 foreach my $k (keys %$conf) {
412 next if $k !~ m/^net(\d+)$/;
414 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
416 $raw .= "lxc.network.type = veth\n";
417 $raw .= "lxc.network.veth.pair = veth${vmid}i${ind}\n";
418 $raw .= "lxc.network.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
419 $raw .= "lxc.network.name = $d->{name}\n" if defined($d->{name
});
420 $raw .= "lxc.network.mtu = $d->{mtu}\n" if defined($d->{mtu
});
423 if (my $lxcconf = $conf->{lxc
}) {
424 foreach my $entry (@$lxcconf) {
425 my ($k, $v) = @$entry;
426 $netcount++ if $k eq 'lxc.network.type';
431 $raw .= "lxc.network.type = empty\n" if !$netcount;
433 File
::Path
::mkpath
("$dir/rootfs");
435 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
438 # verify and cleanup nameserver list (replace \0 with ' ')
439 sub verify_nameserver_list
{
440 my ($nameserver_list) = @_;
443 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
444 PVE
::JSONSchema
::pve_verify_ip
($server);
448 return join(' ', @list);
451 sub verify_searchdomain_list
{
452 my ($searchdomain_list) = @_;
455 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
456 # todo: should we add checks for valid dns domains?
460 return join(' ', @list);
463 sub get_console_command
{
464 my ($vmid, $conf) = @_;
466 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
468 if ($cmode eq 'console') {
469 return ['lxc-console', '-n', $vmid, '-t', 0];
470 } elsif ($cmode eq 'tty') {
471 return ['lxc-console', '-n', $vmid];
472 } elsif ($cmode eq 'shell') {
473 return ['lxc-attach', '--clear-env', '-n', $vmid];
475 die "internal error";
479 sub get_primary_ips
{
482 # return data from net0
484 return undef if !defined($conf->{net0
});
485 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
487 my $ipv4 = $net->{ip
};
489 if ($ipv4 =~ /^(dhcp|manual)$/) {
495 my $ipv6 = $net->{ip6
};
497 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
504 return ($ipv4, $ipv6);
507 sub delete_mountpoint_volume
{
508 my ($storage_cfg, $vmid, $volume) = @_;
510 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
512 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
513 PVE
::Storage
::vdisk_free
($storage_cfg, $volume) if $vmid == $owner;
516 sub destroy_lxc_container
{
517 my ($storage_cfg, $vmid, $conf) = @_;
519 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
520 my ($ms, $mountpoint) = @_;
521 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
524 rmdir "/var/lib/lxc/$vmid/rootfs";
525 unlink "/var/lib/lxc/$vmid/config";
526 rmdir "/var/lib/lxc/$vmid";
527 destroy_config
($vmid);
529 #my $cmd = ['lxc-destroy', '-n', $vmid ];
530 #PVE::Tools::run_command($cmd);
533 sub vm_stop_cleanup
{
534 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
539 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
540 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
543 warn $@ if $@; # avoid errors - just warn
546 my $safe_num_ne = sub {
549 return 0 if !defined($a) && !defined($b);
550 return 1 if !defined($a);
551 return 1 if !defined($b);
556 my $safe_string_ne = sub {
559 return 0 if !defined($a) && !defined($b);
560 return 1 if !defined($a);
561 return 1 if !defined($b);
567 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
569 if ($newnet->{type
} ne 'veth') {
570 # for when there are physical interfaces
571 die "cannot update interface of type $newnet->{type}";
574 my $veth = "veth${vmid}i${netid}";
575 my $eth = $newnet->{name
};
577 if (my $oldnetcfg = $conf->{$opt}) {
578 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
580 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
581 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
583 PVE
::Network
::veth_delete
($veth);
584 delete $conf->{$opt};
585 PVE
::LXC
::Config-
>write_config($vmid, $conf);
587 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
589 } elsif (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
590 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
591 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
593 if ($oldnet->{bridge
}) {
594 PVE
::Network
::tap_unplug
($veth);
595 foreach (qw(bridge tag firewall)) {
596 delete $oldnet->{$_};
598 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
599 PVE
::LXC
::Config-
>write_config($vmid, $conf);
602 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
});
603 foreach (qw(bridge tag firewall)) {
604 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
606 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
607 PVE
::LXC
::Config-
>write_config($vmid, $conf);
610 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
613 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
617 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
619 my $veth = "veth${vmid}i${netid}";
620 my $vethpeer = $veth . "p";
621 my $eth = $newnet->{name
};
623 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
624 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
});
626 # attach peer in container
627 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
628 PVE
::Tools
::run_command
($cmd);
630 # link up peer in container
631 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
632 PVE
::Tools
::run_command
($cmd);
634 my $done = { type
=> 'veth' };
635 foreach (qw(bridge tag firewall hwaddr name)) {
636 $done->{$_} = $newnet->{$_} if $newnet->{$_};
638 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
640 PVE
::LXC
::Config-
>write_config($vmid, $conf);
643 sub update_ipconfig
{
644 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
646 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
648 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
653 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
655 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
657 my $change_ip_config = sub {
658 my ($ipversion) = @_;
660 my $family_opt = "-$ipversion";
661 my $suffix = $ipversion == 4 ?
'' : $ipversion;
665 my $newip = $newnet->{$ip};
666 my $newgw = $newnet->{$gw};
667 my $oldip = $optdata->{$ip};
669 my $change_ip = &$safe_string_ne($oldip, $newip);
670 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
672 return if !$change_ip && !$change_gw;
674 # step 1: add new IP, if this fails we cancel
675 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
676 if ($change_ip && $is_real_ip) {
677 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
684 # step 2: replace gateway
685 # If this fails we delete the added IP and cancel.
686 # If it succeeds we save the config and delete the old IP, ignoring
687 # errors. The config is then saved.
688 # Note: 'ip route replace' can add
692 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
693 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
695 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
699 # the route was not replaced, the old IP is still available
700 # rollback (delete new IP) and cancel
702 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
703 warn $@ if $@; # no need to die here
708 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
709 # if the route was not deleted, the guest might have deleted it manually
715 # from this point on we save the configuration
716 # step 3: delete old IP ignoring errors
717 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
718 # We need to enable promote_secondaries, otherwise our newly added
719 # address will be removed along with the old one.
722 if ($ipversion == 4) {
723 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
724 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
725 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
727 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
729 warn $@ if $@; # no need to die here
731 if ($ipversion == 4) {
732 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
736 foreach my $property ($ip, $gw) {
737 if ($newnet->{$property}) {
738 $optdata->{$property} = $newnet->{$property};
740 delete $optdata->{$property};
743 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
744 PVE
::LXC
::Config-
>write_config($vmid, $conf);
745 $lxc_setup->setup_network($conf);
748 &$change_ip_config(4);
749 &$change_ip_config(6);
753 my $enter_namespace = sub {
754 my ($vmid, $pid, $which, $type) = @_;
755 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
756 or die "failed to open $which namespace of container $vmid: $!\n";
757 PVE
::Tools
::setns
(fileno($fd), $type)
758 or die "failed to enter $which namespace of container $vmid: $!\n";
762 my $do_syncfs = sub {
763 my ($vmid, $pid, $socket) = @_;
765 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
767 # Tell the parent process to start reading our /proc/mounts
768 print {$socket} "go\n";
771 # Receive /proc/self/mounts
772 my $mountdata = do { local $/ = undef; <$socket> };
775 # Now sync all mountpoints...
776 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
777 foreach my $mp (@$mounts) {
778 my ($what, $dir, $fs) = @$mp;
779 next if $fs eq 'fuse.lxcfs';
780 eval { PVE
::Tools
::sync_mountpoint
($dir); };
785 sub sync_container_namespace
{
787 my $pid = find_lxc_pid
($vmid);
789 # SOCK_DGRAM is nicer for barriers but cannot be slurped
790 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
791 or die "failed to create socketpair: $!\n";
794 die "fork failed: $!\n" if !defined($child);
799 &$do_syncfs($vmid, $pid, $cfd);
809 die "failed to enter container namespace\n" if $go ne "go\n";
811 open my $mounts, '<', "/proc/$child/mounts"
812 or die "failed to open container's /proc/mounts: $!\n";
813 my $mountdata = do { local $/ = undef; <$mounts> };
815 print {$pfd} $mountdata;
818 while (waitpid($child, 0) != $child) {}
819 die "failed to sync container namespace\n" if $? != 0;
822 sub template_create
{
823 my ($vmid, $conf) = @_;
825 my $storecfg = PVE
::Storage
::config
();
827 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
828 my $volid = $rootinfo->{volume
};
830 die "Template feature is not available for '$volid'\n"
831 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
833 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
835 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
836 $rootinfo->{volume
} = $template_volid;
837 $conf->{rootfs
} = PVE
::LXC
::Config-
>print_ct_mountpoint($rootinfo, 1);
839 PVE
::LXC
::Config-
>write_config($vmid, $conf);
842 sub check_ct_modify_config_perm
{
843 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
845 return 1 if $authuser eq 'root@pam';
848 my ($opt, $delete) = @_;
849 if ($opt eq 'cpus' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
850 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
851 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
852 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
854 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
855 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
856 raise_perm_exc
("mountpoint type $data->{type}") if $data->{type
} ne 'volume';
857 } elsif ($opt eq 'memory' || $opt eq 'swap') {
858 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
859 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
860 $opt eq 'searchdomain' || $opt eq 'hostname') {
861 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
863 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
867 foreach my $opt (keys %$newconf) {
870 foreach my $opt (@$delete) {
878 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
880 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
881 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
883 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
884 my ($ms, $mountpoint) = @_;
886 my $volid = $mountpoint->{volume
};
887 my $mount = $mountpoint->{mp
};
889 return if !$volid || !$mount;
891 my $mount_path = "$rootdir/$mount";
892 $mount_path =~ s!/+!/!g;
894 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
897 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
910 my ($vmid, $storage_cfg, $conf) = @_;
912 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
913 File
::Path
::make_path
($rootdir);
915 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
916 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
919 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
920 my ($ms, $mountpoint) = @_;
922 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg);
926 warn "mounting container failed\n";
927 umount_all
($vmid, $storage_cfg, $conf, 1);
935 sub mountpoint_mount_path
{
936 my ($mountpoint, $storage_cfg, $snapname) = @_;
938 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
941 my $check_mount_path = sub {
943 $path = File
::Spec-
>canonpath($path);
944 my $real = Cwd
::realpath
($path);
945 if ($real ne $path) {
946 die "mount path modified by symlink: $path != $real";
955 if ($line =~ m
@^(/dev/loop\d
+):@) {
959 my $cmd = ['losetup', '--associated', $path];
960 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
964 # Run a function with a file attached to a loop device.
965 # The loop device is always detached afterwards (or set to autoclear).
966 # Returns the loop device.
967 sub run_with_loopdev
{
968 my ($func, $file) = @_;
969 my $device = query_loopdev
($file);
970 # Try to reuse an existing device
972 # We assume that whoever setup the loop device is responsible for
980 if ($line =~ m
@^(/dev/loop\d
+)$@) {
984 PVE
::Tools
::run_command
(['losetup', '--show', '-f', $file], outfunc
=> $parser);
985 die "failed to setup loop device for $file\n" if !$device;
986 eval { &$func($device); };
988 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
994 my ($dir, $dest, $ro, @extra_opts) = @_;
995 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
997 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
999 warn "bindmount error\n";
1000 # don't leave writable bind-mounts behind...
1001 PVE
::Tools
::run_command
(['umount', $dest]);
1007 # use $rootdir = undef to just return the corresponding mount path
1008 sub mountpoint_mount
{
1009 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1011 my $volid = $mountpoint->{volume
};
1012 my $mount = $mountpoint->{mp
};
1013 my $type = $mountpoint->{type
};
1014 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1017 return if !$volid || !$mount;
1021 if (defined($rootdir)) {
1022 $rootdir =~ s!/+$!!;
1023 $mount_path = "$rootdir/$mount";
1024 $mount_path =~ s!/+!/!g;
1025 &$check_mount_path($mount_path);
1026 File
::Path
::mkpath
($mount_path);
1029 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1031 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1034 if (defined($mountpoint->{acl
})) {
1035 $optstring .= ($mountpoint->{acl
} ?
'acl' : 'noacl');
1037 my $readonly = $mountpoint->{ro
};
1039 my @extra_opts = ('-o', $optstring);
1043 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1044 my $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname);
1046 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1047 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1049 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1051 if ($format eq 'subvol') {
1054 if ($scfg->{type
} eq 'zfspool') {
1055 my $path_arg = $path;
1056 $path_arg =~ s!^/+!!;
1057 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1059 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1062 bindmount
($path, $mount_path, $readonly, @extra_opts);
1063 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1066 return wantarray ?
($path, 0, $mounted_dev) : $path;
1067 } elsif ($format eq 'raw' || $format eq 'iso') {
1071 if ($format eq 'iso') {
1072 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1073 } elsif ($isBase || defined($snapname)) {
1074 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1077 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1079 push @extra_opts, '-o', 'ro' if $readonly;
1080 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1084 my $use_loopdev = 0;
1085 if ($scfg->{path
}) {
1086 $mounted_dev = run_with_loopdev
($domount, $path);
1088 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1089 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1090 $mounted_dev = $path;
1093 die "unsupported storage type '$scfg->{type}'\n";
1095 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1097 die "unsupported image format '$format'\n";
1099 } elsif ($type eq 'device') {
1100 push @extra_opts, '-o', 'ro' if $readonly;
1101 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1102 return wantarray ?
($volid, 0, $volid) : $volid;
1103 } elsif ($type eq 'bind') {
1104 die "directory '$volid' does not exist\n" if ! -d
$volid;
1105 &$check_mount_path($volid);
1106 bindmount
($volid, $mount_path, $readonly, @extra_opts) if $mount_path;
1107 warn "cannot enable quota control for bind mounts\n" if $quota;
1108 return wantarray ?
($volid, 0, undef) : $volid;
1111 die "unsupported storage";
1115 my ($dev, $rootuid, $rootgid) = @_;
1117 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1118 '-E', "root_owner=$rootuid:$rootgid",
1123 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1125 if ($volid =~ m!^/dev/.+!) {
1130 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1132 die "cannot format volume '$volid' with no storage\n" if !$storage;
1134 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1136 my $path = PVE
::Storage
::path
($storage_cfg, $volid);
1138 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1139 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1141 die "cannot format volume '$volid' (format == $format)\n"
1142 if $format ne 'raw';
1144 mkfs
($path, $rootuid, $rootgid);
1148 my ($storecfg, $vollist) = @_;
1150 foreach my $volid (@$vollist) {
1151 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1157 my ($storecfg, $vmid, $settings, $conf) = @_;
1162 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1163 my $chown_vollist = [];
1165 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1166 my ($ms, $mountpoint) = @_;
1168 my $volid = $mountpoint->{volume
};
1169 my $mp = $mountpoint->{mp
};
1171 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1173 if ($storage && ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/)) {
1174 my ($storeid, $size_gb) = ($1, $2);
1176 my $size_kb = int(${size_gb
}*1024) * 1024;
1178 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1179 # fixme: use better naming ct-$vmid-disk-X.raw?
1181 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs') {
1183 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1185 format_disk
($storecfg, $volid, $rootuid, $rootgid);
1187 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1189 push @$chown_vollist, $volid;
1191 } elsif ($scfg->{type
} eq 'zfspool') {
1193 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1195 push @$chown_vollist, $volid;
1196 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1198 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1199 format_disk
($storecfg, $volid, $rootuid, $rootgid);
1201 } elsif ($scfg->{type
} eq 'rbd') {
1203 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd
};
1204 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1205 format_disk
($storecfg, $volid, $rootuid, $rootgid);
1207 die "unable to create containers on storage type '$scfg->{type}'\n";
1209 push @$vollist, $volid;
1210 $mountpoint->{volume
} = $volid;
1211 $mountpoint->{size
} = $size_kb * 1024;
1212 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1214 # use specified/existing volid/dir/device
1215 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1219 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1220 foreach my $volid (@$chown_vollist) {
1221 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1222 chown($rootuid, $rootgid, $path);
1224 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1226 # free allocated images on error
1228 destroy_disks
($storecfg, $vollist);
1234 # bash completion helper
1236 sub complete_os_templates
{
1237 my ($cmdname, $pname, $cvalue) = @_;
1239 my $cfg = PVE
::Storage
::config
();
1243 if ($cvalue =~ m/^([^:]+):/) {
1247 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
1248 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
1251 foreach my $id (keys %$data) {
1252 foreach my $item (@{$data->{$id}}) {
1253 push @$res, $item->{volid
} if defined($item->{volid
});
1260 my $complete_ctid_full = sub {
1263 my $idlist = vmstatus
();
1265 my $active_hash = list_active_containers
();
1269 foreach my $id (keys %$idlist) {
1270 my $d = $idlist->{$id};
1271 if (defined($running)) {
1272 next if $d->{template
};
1273 next if $running && !$active_hash->{$id};
1274 next if !$running && $active_hash->{$id};
1283 return &$complete_ctid_full();
1286 sub complete_ctid_stopped
{
1287 return &$complete_ctid_full(0);
1290 sub complete_ctid_running
{
1291 return &$complete_ctid_full(1);
1301 my $lxc = $conf->{lxc
};
1302 foreach my $entry (@$lxc) {
1303 my ($key, $value) = @$entry;
1304 next if $key ne 'lxc.id_map';
1305 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1306 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1307 push @$id_map, [$type, $ct, $host, $length];
1309 $rootuid = $host if $type eq 'u';
1310 $rootgid = $host if $type eq 'g';
1313 die "failed to parse id_map: $value\n";
1317 if (!@$id_map && $conf->{unprivileged
}) {
1318 # Should we read them from /etc/subuid?
1319 $id_map = [ ['u', '0', '100000', '65536'],
1320 ['g', '0', '100000', '65536'] ];
1321 $rootuid = $rootgid = 100000;
1324 return ($id_map, $rootuid, $rootgid);
1327 sub userns_command
{
1330 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];