13 use Fcntl
qw(O_RDONLY O_NOFOLLOW O_DIRECTORY);
16 use PVE
::Exception
qw(raise_perm_exc);
20 use PVE
::Tools
qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH);
22 use PVE
::AccessControl
;
25 use Time
::HiRes qw
(gettimeofday
);
29 my $nodename = PVE
::INotify
::nodename
();
31 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
33 our $COMMON_TAR_FLAGS = [ '--sparse', '--numeric-owner', '--acls',
35 '--xattrs-include=user.*',
36 '--xattrs-include=security.capability',
37 '--warning=no-xattr-write' ];
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';
58 unlink PVE
::LXC
::Config-
>config_file($vmid, $nodename);
61 # container status helpers
63 sub list_active_containers
{
65 my $filename = "/proc/net/unix";
67 # similar test is used by lcxcontainers.c: list_active_containers
70 my $fh = IO
::File-
>new ($filename, "r");
73 while (defined(my $line = <$fh>)) {
74 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
76 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
87 # warning: this is slow
91 my $active_hash = list_active_containers
();
93 return 1 if defined($active_hash->{$vmid});
98 sub get_container_disk_usage
{
99 my ($vmid, $pid) = @_;
101 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
104 my $last_proc_vmid_stat;
106 my $parse_cpuacct_stat = sub {
109 my $raw = read_cgroup_value
('cpuacct', $vmid, 'cpuacct.stat', 1);
113 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
126 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc' }} : config_list
();
128 my $active_hash = list_active_containers
();
130 my $cpucount = $cpuinfo->{cpus
} || 1;
132 my $cdtime = gettimeofday
;
134 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
136 foreach my $vmid (keys %$list) {
137 my $d = $list->{$vmid};
139 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
140 warn $@ if $@; # ignore errors (consider them stopped)
142 $d->{status
} = $d->{pid
} ?
'running' : 'stopped';
144 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
145 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
147 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
148 $d->{name
} =~ s/[\s]//g;
150 $d->{cpus
} = $conf->{cpulimit
} || $cpucount;
152 $d->{lock} = $conf->{lock} || '';
155 my $res = get_container_disk_usage
($vmid, $d->{pid
});
156 $d->{disk
} = $res->{used
};
157 $d->{maxdisk
} = $res->{total
};
160 # use 4GB by default ??
161 if (my $rootfs = $conf->{rootfs
}) {
162 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($rootfs);
163 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
165 $d->{maxdisk
} = 4*1024*1024*1024;
171 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
172 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
183 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
186 foreach my $vmid (keys %$list) {
187 my $d = $list->{$vmid};
190 next if !$pid; # skip stopped CTs
192 my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
193 $d->{uptime
} = time - $ctime; # the method lxcfs uses
195 $d->{mem
} = read_cgroup_value
('memory', $vmid, 'memory.usage_in_bytes');
196 $d->{swap
} = read_cgroup_value
('memory', $vmid, 'memory.memsw.usage_in_bytes') - $d->{mem
};
198 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, 'blkio.throttle.io_service_bytes', 1);
199 my @bytes = split(/\n/, $blkio_bytes);
200 foreach my $byte (@bytes) {
201 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
202 $d->{diskread
} = $2 if $key eq 'Read';
203 $d->{diskwrite
} = $2 if $key eq 'Write';
207 my $pstat = &$parse_cpuacct_stat($vmid);
209 my $used = $pstat->{utime} + $pstat->{stime
};
211 my $old = $last_proc_vmid_stat->{$vmid};
213 $last_proc_vmid_stat->{$vmid} = {
221 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
224 my $dutime = $used - $old->{used
};
226 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
227 $last_proc_vmid_stat->{$vmid} = {
233 $d->{cpu
} = $old->{cpu
};
237 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
239 foreach my $dev (keys %$netdev) {
240 next if $dev !~ m/^veth([1-9]\d*)i/;
242 my $d = $list->{$vmid};
246 $d->{netout
} += $netdev->{$dev}->{receive
};
247 $d->{netin
} += $netdev->{$dev}->{transmit
};
254 sub read_cgroup_value
{
255 my ($group, $vmid, $name, $full) = @_;
257 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
259 return PVE
::Tools
::file_get_contents
($path) if $full;
261 return PVE
::Tools
::file_read_firstline
($path);
264 sub write_cgroup_value
{
265 my ($group, $vmid, $name, $value) = @_;
267 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
268 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
272 sub find_lxc_console_pids
{
276 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
279 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
282 my @args = split(/\0/, $cmdline);
284 # search for lxc-console -n <vmid>
285 return if scalar(@args) != 3;
286 return if $args[1] ne '-n';
287 return if $args[2] !~ m/^\d+$/;
288 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
292 push @{$res->{$vmid}}, $pid;
304 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
306 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
308 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
313 # Note: we cannot use Net:IP, because that only allows strict
315 sub parse_ipv4_cidr
{
316 my ($cidr, $noerr) = @_;
318 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
319 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
322 return undef if $noerr;
324 die "unable to parse ipv4 address/mask\n";
328 sub update_lxc_config
{
329 my ($storage_cfg, $vmid, $conf) = @_;
331 my $dir = "/var/lib/lxc/$vmid";
333 if ($conf->{template
}) {
335 unlink "$dir/config";
342 die "missing 'arch' - internal error" if !$conf->{arch
};
343 $raw .= "lxc.arch = $conf->{arch}\n";
345 my $unprivileged = $conf->{unprivileged
};
346 my $custom_idmap = grep { $_->[0] eq 'lxc.id_map' } @{$conf->{lxc
}};
348 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
349 if ($ostype =~ /^(?:debian | ubuntu | centos | fedora | opensuse | archlinux | alpine | gentoo | unmanaged)$/x) {
350 my $inc ="/usr/share/lxc/config/$ostype.common.conf";
351 $inc ="/usr/share/lxc/config/common.conf" if !-f
$inc;
352 $raw .= "lxc.include = $inc\n";
353 if ($unprivileged || $custom_idmap) {
354 $inc = "/usr/share/lxc/config/$ostype.userns.conf";
355 $inc = "/usr/share/lxc/config/userns.conf" if !-f
$inc;
356 $raw .= "lxc.include = $inc\n"
359 die "implement me (ostype $ostype)";
362 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
363 # cannot be exposed to the container with r/w access (cgroup perms).
364 # When this is enabled mounts will still remain in the monitor's namespace
365 # after the container unmounted them and thus will not detach from their
366 # files while the container is running!
367 $raw .= "lxc.monitor.unshare = 1\n";
369 # Should we read them from /etc/subuid?
370 if ($unprivileged && !$custom_idmap) {
371 $raw .= "lxc.id_map = u 0 100000 65536\n";
372 $raw .= "lxc.id_map = g 0 100000 65536\n";
375 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
376 $raw .= "lxc.console = none\n";
377 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
380 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
381 $raw .= "lxc.tty = $ttycount\n";
383 # some init scripts expect a linux terminal (turnkey).
384 $raw .= "lxc.environment = TERM=linux\n";
386 my $utsname = $conf->{hostname
} || "CT$vmid";
387 $raw .= "lxc.utsname = $utsname\n";
389 my $memory = $conf->{memory
} || 512;
390 my $swap = $conf->{swap
} // 0;
392 my $lxcmem = int($memory*1024*1024);
393 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
395 my $lxcswap = int(($memory + $swap)*1024*1024);
396 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
398 if (my $cpulimit = $conf->{cpulimit
}) {
399 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
400 my $value = int(100000*$cpulimit);
401 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
404 my $shares = $conf->{cpuunits
} || 1024;
405 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
407 die "missing 'rootfs' configuration\n"
408 if !defined($conf->{rootfs
});
410 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
412 $raw .= "lxc.rootfs = $dir/rootfs\n";
415 foreach my $k (keys %$conf) {
416 next if $k !~ m/^net(\d+)$/;
418 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
420 $raw .= "lxc.network.type = veth\n";
421 $raw .= "lxc.network.veth.pair = veth${vmid}i${ind}\n";
422 $raw .= "lxc.network.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
423 $raw .= "lxc.network.name = $d->{name}\n" if defined($d->{name
});
424 $raw .= "lxc.network.mtu = $d->{mtu}\n" if defined($d->{mtu
});
427 if (my $lxcconf = $conf->{lxc
}) {
428 foreach my $entry (@$lxcconf) {
429 my ($k, $v) = @$entry;
430 $netcount++ if $k eq 'lxc.network.type';
435 $raw .= "lxc.network.type = empty\n" if !$netcount;
437 File
::Path
::mkpath
("$dir/rootfs");
439 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
442 # verify and cleanup nameserver list (replace \0 with ' ')
443 sub verify_nameserver_list
{
444 my ($nameserver_list) = @_;
447 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
448 PVE
::JSONSchema
::pve_verify_ip
($server);
452 return join(' ', @list);
455 sub verify_searchdomain_list
{
456 my ($searchdomain_list) = @_;
459 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
460 # todo: should we add checks for valid dns domains?
464 return join(' ', @list);
467 sub get_console_command
{
468 my ($vmid, $conf) = @_;
470 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
472 if ($cmode eq 'console') {
473 return ['lxc-console', '-n', $vmid, '-t', 0];
474 } elsif ($cmode eq 'tty') {
475 return ['lxc-console', '-n', $vmid];
476 } elsif ($cmode eq 'shell') {
477 return ['lxc-attach', '--clear-env', '-n', $vmid];
479 die "internal error";
483 sub get_primary_ips
{
486 # return data from net0
488 return undef if !defined($conf->{net0
});
489 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
491 my $ipv4 = $net->{ip
};
493 if ($ipv4 =~ /^(dhcp|manual)$/) {
499 my $ipv6 = $net->{ip6
};
501 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
508 return ($ipv4, $ipv6);
511 sub delete_mountpoint_volume
{
512 my ($storage_cfg, $vmid, $volume) = @_;
514 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
516 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
517 PVE
::Storage
::vdisk_free
($storage_cfg, $volume) if $vmid == $owner;
520 sub destroy_lxc_container
{
521 my ($storage_cfg, $vmid, $conf) = @_;
523 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
524 my ($ms, $mountpoint) = @_;
525 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
528 rmdir "/var/lib/lxc/$vmid/rootfs";
529 unlink "/var/lib/lxc/$vmid/config";
530 rmdir "/var/lib/lxc/$vmid";
531 destroy_config
($vmid);
533 #my $cmd = ['lxc-destroy', '-n', $vmid ];
534 #PVE::Tools::run_command($cmd);
537 sub vm_stop_cleanup
{
538 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
543 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
544 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
547 warn $@ if $@; # avoid errors - just warn
550 my $safe_num_ne = sub {
553 return 0 if !defined($a) && !defined($b);
554 return 1 if !defined($a);
555 return 1 if !defined($b);
560 my $safe_string_ne = sub {
563 return 0 if !defined($a) && !defined($b);
564 return 1 if !defined($a);
565 return 1 if !defined($b);
571 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
573 if ($newnet->{type
} ne 'veth') {
574 # for when there are physical interfaces
575 die "cannot update interface of type $newnet->{type}";
578 my $veth = "veth${vmid}i${netid}";
579 my $eth = $newnet->{name
};
581 if (my $oldnetcfg = $conf->{$opt}) {
582 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
584 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
585 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
587 PVE
::Network
::veth_delete
($veth);
588 delete $conf->{$opt};
589 PVE
::LXC
::Config-
>write_config($vmid, $conf);
591 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
594 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
595 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
596 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
598 if ($oldnet->{bridge
}) {
599 PVE
::Network
::tap_unplug
($veth);
600 foreach (qw(bridge tag firewall)) {
601 delete $oldnet->{$_};
603 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
604 PVE
::LXC
::Config-
>write_config($vmid, $conf);
607 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
608 # This includes the rate:
609 foreach (qw(bridge tag firewall rate)) {
610 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
612 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
613 # Rate can be applied on its own but any change above needs to
614 # include the rate in tap_plug since OVS resets everything.
615 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
616 $oldnet->{rate
} = $newnet->{rate
}
618 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
619 PVE
::LXC
::Config-
>write_config($vmid, $conf);
622 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
625 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
629 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
631 my $veth = "veth${vmid}i${netid}";
632 my $vethpeer = $veth . "p";
633 my $eth = $newnet->{name
};
635 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
636 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
638 # attach peer in container
639 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
640 PVE
::Tools
::run_command
($cmd);
642 # link up peer in container
643 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
644 PVE
::Tools
::run_command
($cmd);
646 my $done = { type
=> 'veth' };
647 foreach (qw(bridge tag firewall hwaddr name)) {
648 $done->{$_} = $newnet->{$_} if $newnet->{$_};
650 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
652 PVE
::LXC
::Config-
>write_config($vmid, $conf);
655 sub update_ipconfig
{
656 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
658 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
660 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
665 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
667 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
669 my $change_ip_config = sub {
670 my ($ipversion) = @_;
672 my $family_opt = "-$ipversion";
673 my $suffix = $ipversion == 4 ?
'' : $ipversion;
677 my $newip = $newnet->{$ip};
678 my $newgw = $newnet->{$gw};
679 my $oldip = $optdata->{$ip};
681 my $change_ip = &$safe_string_ne($oldip, $newip);
682 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
684 return if !$change_ip && !$change_gw;
686 # step 1: add new IP, if this fails we cancel
687 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
688 if ($change_ip && $is_real_ip) {
689 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
696 # step 2: replace gateway
697 # If this fails we delete the added IP and cancel.
698 # If it succeeds we save the config and delete the old IP, ignoring
699 # errors. The config is then saved.
700 # Note: 'ip route replace' can add
704 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
705 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
707 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
711 # the route was not replaced, the old IP is still available
712 # rollback (delete new IP) and cancel
714 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
715 warn $@ if $@; # no need to die here
720 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
721 # if the route was not deleted, the guest might have deleted it manually
727 # from this point on we save the configuration
728 # step 3: delete old IP ignoring errors
729 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
730 # We need to enable promote_secondaries, otherwise our newly added
731 # address will be removed along with the old one.
734 if ($ipversion == 4) {
735 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
736 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
737 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
739 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
741 warn $@ if $@; # no need to die here
743 if ($ipversion == 4) {
744 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
748 foreach my $property ($ip, $gw) {
749 if ($newnet->{$property}) {
750 $optdata->{$property} = $newnet->{$property};
752 delete $optdata->{$property};
755 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
756 PVE
::LXC
::Config-
>write_config($vmid, $conf);
757 $lxc_setup->setup_network($conf);
760 &$change_ip_config(4);
761 &$change_ip_config(6);
765 my $enter_namespace = sub {
766 my ($vmid, $pid, $which, $type) = @_;
767 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
768 or die "failed to open $which namespace of container $vmid: $!\n";
769 PVE
::Tools
::setns
(fileno($fd), $type)
770 or die "failed to enter $which namespace of container $vmid: $!\n";
774 my $do_syncfs = sub {
775 my ($vmid, $pid, $socket) = @_;
777 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
779 # Tell the parent process to start reading our /proc/mounts
780 print {$socket} "go\n";
783 # Receive /proc/self/mounts
784 my $mountdata = do { local $/ = undef; <$socket> };
787 # Now sync all mountpoints...
788 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
789 foreach my $mp (@$mounts) {
790 my ($what, $dir, $fs) = @$mp;
791 next if $fs eq 'fuse.lxcfs';
792 eval { PVE
::Tools
::sync_mountpoint
($dir); };
797 sub sync_container_namespace
{
799 my $pid = find_lxc_pid
($vmid);
801 # SOCK_DGRAM is nicer for barriers but cannot be slurped
802 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
803 or die "failed to create socketpair: $!\n";
806 die "fork failed: $!\n" if !defined($child);
811 &$do_syncfs($vmid, $pid, $cfd);
821 die "failed to enter container namespace\n" if $go ne "go\n";
823 open my $mounts, '<', "/proc/$child/mounts"
824 or die "failed to open container's /proc/mounts: $!\n";
825 my $mountdata = do { local $/ = undef; <$mounts> };
827 print {$pfd} $mountdata;
830 while (waitpid($child, 0) != $child) {}
831 die "failed to sync container namespace\n" if $? != 0;
834 sub template_create
{
835 my ($vmid, $conf) = @_;
837 my $storecfg = PVE
::Storage
::config
();
839 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
840 my $volid = $rootinfo->{volume
};
842 die "Template feature is not available for '$volid'\n"
843 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
845 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
847 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
848 $rootinfo->{volume
} = $template_volid;
849 $conf->{rootfs
} = PVE
::LXC
::Config-
>print_ct_mountpoint($rootinfo, 1);
851 PVE
::LXC
::Config-
>write_config($vmid, $conf);
854 sub check_ct_modify_config_perm
{
855 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
857 return 1 if $authuser eq 'root@pam';
860 my ($opt, $delete) = @_;
861 if ($opt eq 'cpus' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
862 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
863 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
864 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
866 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
867 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
868 raise_perm_exc
("mountpoint type $data->{type}") if $data->{type
} ne 'volume';
869 } elsif ($opt eq 'memory' || $opt eq 'swap') {
870 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
871 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
872 $opt eq 'searchdomain' || $opt eq 'hostname') {
873 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
875 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
879 foreach my $opt (keys %$newconf) {
882 foreach my $opt (@$delete) {
890 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
892 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
893 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
895 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
896 my ($ms, $mountpoint) = @_;
898 my $volid = $mountpoint->{volume
};
899 my $mount = $mountpoint->{mp
};
901 return if !$volid || !$mount;
903 my $mount_path = "$rootdir/$mount";
904 $mount_path =~ s!/+!/!g;
906 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
909 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
922 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
924 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
925 File
::Path
::make_path
($rootdir);
927 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
928 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
931 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
932 my ($ms, $mountpoint) = @_;
934 $mountpoint->{ro
} = 0 if $ignore_ro;
936 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg);
940 warn "mounting container failed\n";
941 umount_all
($vmid, $storage_cfg, $conf, 1);
949 sub mountpoint_mount_path
{
950 my ($mountpoint, $storage_cfg, $snapname) = @_;
952 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
960 if ($line =~ m
@^(/dev/loop\d
+):@) {
964 my $cmd = ['losetup', '--associated', $path];
965 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
969 # Run a function with a file attached to a loop device.
970 # The loop device is always detached afterwards (or set to autoclear).
971 # Returns the loop device.
972 sub run_with_loopdev
{
973 my ($func, $file) = @_;
974 my $device = query_loopdev
($file);
975 # Try to reuse an existing device
977 # We assume that whoever setup the loop device is responsible for
985 if ($line =~ m
@^(/dev/loop\d
+)$@) {
989 PVE
::Tools
::run_command
(['losetup', '--show', '-f', $file], outfunc
=> $parser);
990 die "failed to setup loop device for $file\n" if !$device;
991 eval { &$func($device); };
993 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
998 # In scalar mode: returns a file handle to the deepest directory node.
999 # In list context: returns a list of:
1000 # * the deepest directory node
1001 # * the 2nd deepest directory (parent of the above)
1002 # * directory name of the last directory
1003 # So that the path $2/$3 should lead to $1 afterwards.
1004 sub walk_tree_nofollow
($$$) {
1005 my ($start, $subdir, $mkdir) = @_;
1007 # splitdir() returns '' for empty components including the leading /
1008 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1010 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1011 or die "failed to open start directory $start: $!\n";
1014 my $last_component = undef;
1016 foreach my $component (@comps) {
1017 $dir .= "/$component";
1018 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1021 # failed, check for symlinks and try to create the path
1022 die "symlink encountered at: $dir\n" if $! == ELOOP
;
1023 die "cannot open directory $dir: $!\n" if !$mkdir;
1025 # We don't check for errors on mkdirat() here and just try to
1026 # openat() again, since at least one error (EEXIST) is an
1027 # expected possibility if multiple containers start
1028 # simultaneously. If someone else injects a symlink now then
1029 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1030 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1032 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1033 die "failed to create path: $dir: $!\n" if !$next;
1036 close $second if defined($last_component);
1037 $last_component = $component;
1042 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1043 close $second if defined($last_component);
1048 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1050 my $srcdh = walk_tree_nofollow
('/', $dir, 0);
1052 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1054 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1056 warn "bindmount error\n";
1057 # don't leave writable bind-mounts behind...
1058 PVE
::Tools
::run_command
(['umount', $dest]);
1065 # Open the mount point path coming from the parent directory since the
1066 # filehandle we would have gotten as first result of walk_tree_nofollow
1067 # earlier is still a handle to the underlying directory instead of the
1069 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
)
1071 # For the rootfs we don't have a parentfd so we open the path directly.
1072 # Note that this means bindmounting any prefix of the host's
1073 # /var/lib/lxc/$vmid path into another container is considered a grave
1075 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1077 die "failed to open directory $dir: $!\n" if !$destdh;
1079 my ($srcdev, $srcinode) = stat($srcdh);
1080 my ($dstdev, $dstinode) = stat($destdh);
1084 if ($srcdev != $dstdev || $srcinode != $dstinode) {
1085 PVE
::Tools
::run_command
(['umount', $dest]);
1086 die "detected mount path change at: $dir\n";
1090 # use $rootdir = undef to just return the corresponding mount path
1091 sub mountpoint_mount
{
1092 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1094 my $volid = $mountpoint->{volume
};
1095 my $mount = $mountpoint->{mp
};
1096 my $type = $mountpoint->{type
};
1097 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1100 return if !$volid || !$mount;
1105 my ($mpfd, $parentfd, $last_dir);
1107 if (defined($rootdir)) {
1108 $rootdir =~ s!/+!/!g;
1109 $rootdir =~ s!/+$!!;
1110 $mount_path = "$rootdir/$mount";
1111 ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1);
1114 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1116 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1119 my $acl = $mountpoint->{acl
};
1120 if (defined($acl)) {
1121 $optstring .= ($acl ?
'acl' : 'noacl');
1123 my $readonly = $mountpoint->{ro
};
1125 my @extra_opts = ('-o', $optstring) if $optstring;
1129 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1130 my $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname);
1132 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1133 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1135 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1137 if ($format eq 'subvol') {
1140 if ($scfg->{type
} eq 'zfspool') {
1141 my $path_arg = $path;
1142 $path_arg =~ s!^/+!!;
1143 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1145 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1148 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1149 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1150 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1151 $name .= "\@$snapname" if defined($snapname);
1152 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1154 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1155 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1158 return wantarray ?
($path, 0, undef) : $path;
1159 } elsif ($format eq 'raw' || $format eq 'iso') {
1160 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1161 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1162 # Our autodev hook expects the /dev/dm-* device currently
1163 # and will create the /dev/mapper symlink accordingly
1164 ($path) = (Cwd
::realpath
($path) =~ /^(.*)$/s); # realpath() taints
1168 if ($format eq 'iso') {
1169 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1170 } elsif ($isBase || defined($snapname)) {
1171 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1174 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1176 push @extra_opts, '-o', 'ro' if $readonly;
1177 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1181 my $use_loopdev = 0;
1182 if ($scfg->{path
}) {
1183 $mounted_dev = run_with_loopdev
($domount, $path);
1185 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1186 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1187 $mounted_dev = $path;
1190 die "unsupported storage type '$scfg->{type}'\n";
1192 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1194 die "unsupported image format '$format'\n";
1196 } elsif ($type eq 'device') {
1197 push @extra_opts, '-o', 'ro' if $readonly;
1198 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1199 # See the NOTE above about devicemapper canonicalization
1200 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1201 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1202 return wantarray ?
($volid, 0, $devpath) : $volid;
1203 } elsif ($type eq 'bind') {
1204 die "directory '$volid' does not exist\n" if ! -d
$volid;
1205 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1206 warn "cannot enable quota control for bind mounts\n" if $quota;
1207 return wantarray ?
($volid, 0, undef) : $volid;
1210 die "unsupported storage";
1214 my ($dev, $rootuid, $rootgid) = @_;
1216 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1217 '-E', "root_owner=$rootuid:$rootgid",
1222 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1224 if ($volid =~ m!^/dev/.+!) {
1229 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1231 die "cannot format volume '$volid' with no storage\n" if !$storage;
1233 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1235 my $path = PVE
::Storage
::path
($storage_cfg, $volid);
1237 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1238 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1240 die "cannot format volume '$volid' (format == $format)\n"
1241 if $format ne 'raw';
1243 mkfs
($path, $rootuid, $rootgid);
1247 my ($storecfg, $vollist) = @_;
1249 foreach my $volid (@$vollist) {
1250 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1256 my ($storecfg, $vmid, $settings, $conf) = @_;
1261 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1262 my $chown_vollist = [];
1264 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1265 my ($ms, $mountpoint) = @_;
1267 my $volid = $mountpoint->{volume
};
1268 my $mp = $mountpoint->{mp
};
1270 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1272 if ($storage && ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/)) {
1273 my ($storeid, $size_gb) = ($1, $2);
1275 my $size_kb = int(${size_gb
}*1024) * 1024;
1277 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1278 # fixme: use better naming ct-$vmid-disk-X.raw?
1280 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs') {
1282 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1284 format_disk
($storecfg, $volid, $rootuid, $rootgid);
1286 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1288 push @$chown_vollist, $volid;
1290 } elsif ($scfg->{type
} eq 'zfspool') {
1292 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1294 push @$chown_vollist, $volid;
1295 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1297 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1298 format_disk
($storecfg, $volid, $rootuid, $rootgid);
1300 } elsif ($scfg->{type
} eq 'rbd') {
1302 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd
};
1303 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1304 format_disk
($storecfg, $volid, $rootuid, $rootgid);
1306 die "unable to create containers on storage type '$scfg->{type}'\n";
1308 push @$vollist, $volid;
1309 $mountpoint->{volume
} = $volid;
1310 $mountpoint->{size
} = $size_kb * 1024;
1311 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1313 # use specified/existing volid/dir/device
1314 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1318 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1319 foreach my $volid (@$chown_vollist) {
1320 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1321 chown($rootuid, $rootgid, $path);
1323 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1325 # free allocated images on error
1327 destroy_disks
($storecfg, $vollist);
1333 # bash completion helper
1335 sub complete_os_templates
{
1336 my ($cmdname, $pname, $cvalue) = @_;
1338 my $cfg = PVE
::Storage
::config
();
1342 if ($cvalue =~ m/^([^:]+):/) {
1346 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
1347 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
1350 foreach my $id (keys %$data) {
1351 foreach my $item (@{$data->{$id}}) {
1352 push @$res, $item->{volid
} if defined($item->{volid
});
1359 my $complete_ctid_full = sub {
1362 my $idlist = vmstatus
();
1364 my $active_hash = list_active_containers
();
1368 foreach my $id (keys %$idlist) {
1369 my $d = $idlist->{$id};
1370 if (defined($running)) {
1371 next if $d->{template
};
1372 next if $running && !$active_hash->{$id};
1373 next if !$running && $active_hash->{$id};
1382 return &$complete_ctid_full();
1385 sub complete_ctid_stopped
{
1386 return &$complete_ctid_full(0);
1389 sub complete_ctid_running
{
1390 return &$complete_ctid_full(1);
1400 my $lxc = $conf->{lxc
};
1401 foreach my $entry (@$lxc) {
1402 my ($key, $value) = @$entry;
1403 next if $key ne 'lxc.id_map';
1404 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1405 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1406 push @$id_map, [$type, $ct, $host, $length];
1408 $rootuid = $host if $type eq 'u';
1409 $rootgid = $host if $type eq 'g';
1412 die "failed to parse id_map: $value\n";
1416 if (!@$id_map && $conf->{unprivileged
}) {
1417 # Should we read them from /etc/subuid?
1418 $id_map = [ ['u', '0', '100000', '65536'],
1419 ['g', '0', '100000', '65536'] ];
1420 $rootuid = $rootgid = 100000;
1423 return ($id_map, $rootuid, $rootgid);
1426 sub userns_command
{
1429 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];