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
::Tools
qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH);
24 use PVE
::AccessControl
;
28 use Time
::HiRes qw
(gettimeofday
);
30 my $nodename = PVE
::INotify
::nodename
();
32 my $cpuinfo= PVE
::ProcFSTools
::read_cpuinfo
();
35 my $vmlist = PVE
::Cluster
::get_vmlist
();
37 return $res if !$vmlist || !$vmlist->{ids
};
38 my $ids = $vmlist->{ids
};
40 foreach my $vmid (keys %$ids) {
41 next if !$vmid; # skip CT0
42 my $d = $ids->{$vmid};
43 next if !$d->{node
} || $d->{node
} ne $nodename;
44 next if !$d->{type
} || $d->{type
} ne 'lxc';
45 $res->{$vmid}->{type
} = 'lxc';
53 unlink PVE
::LXC
::Config-
>config_file($vmid, $nodename);
56 # container status helpers
58 sub list_active_containers
{
60 my $filename = "/proc/net/unix";
62 # similar test is used by lcxcontainers.c: list_active_containers
65 my $fh = IO
::File-
>new ($filename, "r");
68 while (defined(my $line = <$fh>)) {
69 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
71 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
82 # warning: this is slow
86 my $active_hash = list_active_containers
();
88 return 1 if defined($active_hash->{$vmid});
93 sub get_container_disk_usage
{
94 my ($vmid, $pid) = @_;
96 return PVE
::Tools
::df
("/proc/$pid/root/", 1);
99 my $last_proc_vmid_stat;
101 my $parse_cpuacct_stat = sub {
102 my ($vmid, $unprivileged) = @_;
104 my $raw = read_cgroup_value
('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
108 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
121 my $list = $opt_vmid ?
{ $opt_vmid => { type
=> 'lxc' }} : config_list
();
123 my $active_hash = list_active_containers
();
125 my $cpucount = $cpuinfo->{cpus
} || 1;
127 my $cdtime = gettimeofday
;
129 my $uptime = (PVE
::ProcFSTools
::read_proc_uptime
(1))[0];
131 my $unprivileged = {};
133 foreach my $vmid (keys %$list) {
134 my $d = $list->{$vmid};
136 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
137 warn $@ if $@; # ignore errors (consider them stopped)
139 $d->{status
} = $d->{pid
} ?
'running' : 'stopped';
141 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
142 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
144 $unprivileged->{$vmid} = $conf->{unprivileged
};
146 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
147 $d->{name
} =~ s/[\s]//g;
149 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
150 $d->{cpus
} = $cpucount if !$d->{cpus
};
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 my $unpriv = $unprivileged->{$vmid};
197 my $memory_stat = read_cgroup_list
('memory', $vmid, $unpriv, 'memory.stat');
198 my $mem_usage_in_bytes = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
200 $d->{mem
} = $mem_usage_in_bytes - $memory_stat->{total_cache
};
201 $d->{swap
} = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
203 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, $unpriv, 'blkio.throttle.io_service_bytes', 1);
204 my @bytes = split(/\n/, $blkio_bytes);
205 foreach my $byte (@bytes) {
206 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
207 $d->{diskread
} += $2 if $key eq 'Read';
208 $d->{diskwrite
} += $2 if $key eq 'Write';
212 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
214 my $used = $pstat->{utime} + $pstat->{stime
};
216 my $old = $last_proc_vmid_stat->{$vmid};
218 $last_proc_vmid_stat->{$vmid} = {
226 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
229 my $dutime = $used - $old->{used
};
231 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
232 $last_proc_vmid_stat->{$vmid} = {
238 $d->{cpu
} = $old->{cpu
};
242 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
244 foreach my $dev (keys %$netdev) {
245 next if $dev !~ m/^veth([1-9]\d*)i/;
247 my $d = $list->{$vmid};
251 $d->{netout
} += $netdev->{$dev}->{receive
};
252 $d->{netin
} += $netdev->{$dev}->{transmit
};
259 sub read_cgroup_list
($$$$) {
260 my ($group, $vmid, $unprivileged, $name) = @_;
262 my $content = read_cgroup_value
($group, $vmid, $unprivileged, $name, 1);
264 return { split(/\s+/, $content) };
267 sub read_cgroup_value
($$$$$) {
268 my ($group, $vmid, $unprivileged, $name, $full) = @_;
270 my $nsdir = $unprivileged ?
'' : 'ns/';
271 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
273 return PVE
::Tools
::file_get_contents
($path) if $full;
275 return PVE
::Tools
::file_read_firstline
($path);
278 sub write_cgroup_value
{
279 my ($group, $vmid, $name, $value) = @_;
281 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
282 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
286 sub find_lxc_console_pids
{
290 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
293 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
296 my @args = split(/\0/, $cmdline);
298 # search for lxc-console -n <vmid>
299 return if scalar(@args) != 3;
300 return if $args[1] ne '-n';
301 return if $args[2] !~ m/^\d+$/;
302 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
306 push @{$res->{$vmid}}, $pid;
318 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
320 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
322 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
327 # Note: we cannot use Net:IP, because that only allows strict
329 sub parse_ipv4_cidr
{
330 my ($cidr, $noerr) = @_;
332 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
333 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
336 return undef if $noerr;
338 die "unable to parse ipv4 address/mask\n";
342 sub update_lxc_config
{
343 my ($vmid, $conf) = @_;
345 my $dir = "/var/lib/lxc/$vmid";
347 if ($conf->{template
}) {
349 unlink "$dir/config";
356 die "missing 'arch' - internal error" if !$conf->{arch
};
357 $raw .= "lxc.arch = $conf->{arch}\n";
359 my $unprivileged = $conf->{unprivileged
};
360 my $custom_idmap = grep { $_->[0] eq 'lxc.idmap' } @{$conf->{lxc
}};
362 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
364 my $inc ="/usr/share/lxc/config/$ostype.common.conf";
365 $inc ="/usr/share/lxc/config/common.conf" if !-f
$inc;
366 $raw .= "lxc.include = $inc\n";
367 if ($unprivileged || $custom_idmap) {
368 $inc = "/usr/share/lxc/config/$ostype.userns.conf";
369 $inc = "/usr/share/lxc/config/userns.conf" if !-f
$inc;
370 $raw .= "lxc.include = $inc\n"
373 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
374 # cannot be exposed to the container with r/w access (cgroup perms).
375 # When this is enabled mounts will still remain in the monitor's namespace
376 # after the container unmounted them and thus will not detach from their
377 # files while the container is running!
378 $raw .= "lxc.monitor.unshare = 1\n";
380 # Should we read them from /etc/subuid?
381 if ($unprivileged && !$custom_idmap) {
382 $raw .= "lxc.idmap = u 0 100000 65536\n";
383 $raw .= "lxc.idmap = g 0 100000 65536\n";
386 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
387 $raw .= "lxc.console.path = none\n";
388 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
391 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
392 $raw .= "lxc.tty.max = $ttycount\n";
394 # some init scripts expect a linux terminal (turnkey).
395 $raw .= "lxc.environment = TERM=linux\n";
397 my $utsname = $conf->{hostname
} || "CT$vmid";
398 $raw .= "lxc.uts.name = $utsname\n";
400 my $memory = $conf->{memory
} || 512;
401 my $swap = $conf->{swap
} // 0;
403 my $lxcmem = int($memory*1024*1024);
404 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
406 my $lxcswap = int(($memory + $swap)*1024*1024);
407 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
409 if (my $cpulimit = $conf->{cpulimit
}) {
410 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
411 my $value = int(100000*$cpulimit);
412 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
415 my $shares = $conf->{cpuunits
} || 1024;
416 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
418 die "missing 'rootfs' configuration\n"
419 if !defined($conf->{rootfs
});
421 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
423 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
425 foreach my $k (sort keys %$conf) {
426 next if $k !~ m/^net(\d+)$/;
428 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
429 $raw .= "lxc.net.$ind.type = veth\n";
430 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
431 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
432 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
433 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu
});
437 if (my $lxcconf = $conf->{lxc
}) {
438 foreach my $entry (@$lxcconf) {
439 my ($k, $v) = @$entry;
440 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
445 my $cores = $conf->{cores
};
446 if (!$had_cpuset && $cores) {
447 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup('lxc', 'effective_cpus') };
448 $cpuset = PVE
::CpuSet-
>new_from_cgroup('', 'effective_cpus') if !$cpuset;
449 my @members = $cpuset->members();
450 while (scalar(@members) > $cores) {
451 my $randidx = int(rand(scalar(@members)));
452 $cpuset->delete($members[$randidx]);
453 splice(@members, $randidx, 1); # keep track of the changes
455 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
458 File
::Path
::mkpath
("$dir/rootfs");
460 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
463 # verify and cleanup nameserver list (replace \0 with ' ')
464 sub verify_nameserver_list
{
465 my ($nameserver_list) = @_;
468 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
469 PVE
::JSONSchema
::pve_verify_ip
($server);
473 return join(' ', @list);
476 sub verify_searchdomain_list
{
477 my ($searchdomain_list) = @_;
480 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
481 # todo: should we add checks for valid dns domains?
485 return join(' ', @list);
488 sub get_console_command
{
489 my ($vmid, $conf, $noescapechar) = @_;
491 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
494 if ($cmode eq 'console') {
495 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
496 push @$cmd, '-e', -1 if $noescapechar;
497 } elsif ($cmode eq 'tty') {
498 push @$cmd, 'lxc-console', '-n', $vmid;
499 push @$cmd, '-e', -1 if $noescapechar;
500 } elsif ($cmode eq 'shell') {
501 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
503 die "internal error";
509 sub get_primary_ips
{
512 # return data from net0
514 return undef if !defined($conf->{net0
});
515 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
517 my $ipv4 = $net->{ip
};
519 if ($ipv4 =~ /^(dhcp|manual)$/) {
525 my $ipv6 = $net->{ip6
};
527 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
534 return ($ipv4, $ipv6);
537 sub delete_mountpoint_volume
{
538 my ($storage_cfg, $vmid, $volume) = @_;
540 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
542 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
543 PVE
::Storage
::vdisk_free
($storage_cfg, $volume) if $vmid == $owner;
546 sub destroy_lxc_container
{
547 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
549 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
550 my ($ms, $mountpoint) = @_;
551 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
554 rmdir "/var/lib/lxc/$vmid/rootfs";
555 unlink "/var/lib/lxc/$vmid/config";
556 rmdir "/var/lib/lxc/$vmid";
557 if (defined $replacement_conf) {
558 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
560 destroy_config
($vmid);
563 #my $cmd = ['lxc-destroy', '-n', $vmid ];
564 #PVE::Tools::run_command($cmd);
567 sub vm_stop_cleanup
{
568 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
573 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
574 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
577 warn $@ if $@; # avoid errors - just warn
580 my $safe_num_ne = sub {
583 return 0 if !defined($a) && !defined($b);
584 return 1 if !defined($a);
585 return 1 if !defined($b);
590 my $safe_string_ne = sub {
593 return 0 if !defined($a) && !defined($b);
594 return 1 if !defined($a);
595 return 1 if !defined($b);
601 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
603 if ($newnet->{type
} ne 'veth') {
604 # for when there are physical interfaces
605 die "cannot update interface of type $newnet->{type}";
608 my $veth = "veth${vmid}i${netid}";
609 my $eth = $newnet->{name
};
611 if (my $oldnetcfg = $conf->{$opt}) {
612 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
614 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
615 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
617 PVE
::Network
::veth_delete
($veth);
618 delete $conf->{$opt};
619 PVE
::LXC
::Config-
>write_config($vmid, $conf);
621 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
624 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
625 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
626 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
628 if ($oldnet->{bridge
}) {
629 PVE
::Network
::tap_unplug
($veth);
630 foreach (qw(bridge tag firewall)) {
631 delete $oldnet->{$_};
633 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
634 PVE
::LXC
::Config-
>write_config($vmid, $conf);
637 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
638 # This includes the rate:
639 foreach (qw(bridge tag firewall rate)) {
640 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
642 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
643 # Rate can be applied on its own but any change above needs to
644 # include the rate in tap_plug since OVS resets everything.
645 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
646 $oldnet->{rate
} = $newnet->{rate
}
648 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
649 PVE
::LXC
::Config-
>write_config($vmid, $conf);
652 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
655 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
659 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
661 my $veth = "veth${vmid}i${netid}";
662 my $vethpeer = $veth . "p";
663 my $eth = $newnet->{name
};
665 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
666 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
668 # attach peer in container
669 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
670 PVE
::Tools
::run_command
($cmd);
672 # link up peer in container
673 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
674 PVE
::Tools
::run_command
($cmd);
676 my $done = { type
=> 'veth' };
677 foreach (qw(bridge tag firewall hwaddr name)) {
678 $done->{$_} = $newnet->{$_} if $newnet->{$_};
680 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
682 PVE
::LXC
::Config-
>write_config($vmid, $conf);
685 sub update_ipconfig
{
686 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
688 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
690 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
695 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
697 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
699 my $change_ip_config = sub {
700 my ($ipversion) = @_;
702 my $family_opt = "-$ipversion";
703 my $suffix = $ipversion == 4 ?
'' : $ipversion;
707 my $newip = $newnet->{$ip};
708 my $newgw = $newnet->{$gw};
709 my $oldip = $optdata->{$ip};
711 my $change_ip = &$safe_string_ne($oldip, $newip);
712 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
714 return if !$change_ip && !$change_gw;
716 # step 1: add new IP, if this fails we cancel
717 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
718 if ($change_ip && $is_real_ip) {
719 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
726 # step 2: replace gateway
727 # If this fails we delete the added IP and cancel.
728 # If it succeeds we save the config and delete the old IP, ignoring
729 # errors. The config is then saved.
730 # Note: 'ip route replace' can add
734 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
735 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
737 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
741 # the route was not replaced, the old IP is still available
742 # rollback (delete new IP) and cancel
744 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
745 warn $@ if $@; # no need to die here
750 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
751 # if the route was not deleted, the guest might have deleted it manually
757 # from this point on we save the configuration
758 # step 3: delete old IP ignoring errors
759 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
760 # We need to enable promote_secondaries, otherwise our newly added
761 # address will be removed along with the old one.
764 if ($ipversion == 4) {
765 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
766 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
767 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
769 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
771 warn $@ if $@; # no need to die here
773 if ($ipversion == 4) {
774 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
778 foreach my $property ($ip, $gw) {
779 if ($newnet->{$property}) {
780 $optdata->{$property} = $newnet->{$property};
782 delete $optdata->{$property};
785 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
786 PVE
::LXC
::Config-
>write_config($vmid, $conf);
787 $lxc_setup->setup_network($conf);
790 &$change_ip_config(4);
791 &$change_ip_config(6);
795 my $enter_namespace = sub {
796 my ($vmid, $pid, $which, $type) = @_;
797 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
798 or die "failed to open $which namespace of container $vmid: $!\n";
799 PVE
::Tools
::setns
(fileno($fd), $type)
800 or die "failed to enter $which namespace of container $vmid: $!\n";
804 my $do_syncfs = sub {
805 my ($vmid, $pid, $socket) = @_;
807 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
809 # Tell the parent process to start reading our /proc/mounts
810 print {$socket} "go\n";
813 # Receive /proc/self/mounts
814 my $mountdata = do { local $/ = undef; <$socket> };
817 # Now sync all mountpoints...
818 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
819 foreach my $mp (@$mounts) {
820 my ($what, $dir, $fs) = @$mp;
821 next if $fs eq 'fuse.lxcfs';
822 eval { PVE
::Tools
::sync_mountpoint
($dir); };
827 sub sync_container_namespace
{
829 my $pid = find_lxc_pid
($vmid);
831 # SOCK_DGRAM is nicer for barriers but cannot be slurped
832 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
833 or die "failed to create socketpair: $!\n";
836 die "fork failed: $!\n" if !defined($child);
841 &$do_syncfs($vmid, $pid, $cfd);
851 die "failed to enter container namespace\n" if $go ne "go\n";
853 open my $mounts, '<', "/proc/$child/mounts"
854 or die "failed to open container's /proc/mounts: $!\n";
855 my $mountdata = do { local $/ = undef; <$mounts> };
857 print {$pfd} $mountdata;
860 while (waitpid($child, 0) != $child) {}
861 die "failed to sync container namespace\n" if $? != 0;
864 sub template_create
{
865 my ($vmid, $conf) = @_;
867 my $storecfg = PVE
::Storage
::config
();
869 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
870 my $volid = $rootinfo->{volume
};
872 die "Template feature is not available for '$volid'\n"
873 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
875 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
877 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
878 $rootinfo->{volume
} = $template_volid;
879 $conf->{rootfs
} = PVE
::LXC
::Config-
>print_ct_mountpoint($rootinfo, 1);
881 PVE
::LXC
::Config-
>write_config($vmid, $conf);
884 sub check_ct_modify_config_perm
{
885 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
887 return 1 if $authuser eq 'root@pam';
890 my ($opt, $delete) = @_;
891 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
892 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
893 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
894 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
896 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
897 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
898 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
899 if $data->{type
} ne 'volume';
900 } elsif ($opt eq 'memory' || $opt eq 'swap') {
901 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
902 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
903 $opt eq 'searchdomain' || $opt eq 'hostname') {
904 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
906 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
910 foreach my $opt (keys %$newconf) {
913 foreach my $opt (@$delete) {
921 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
923 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
924 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
926 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
927 my ($ms, $mountpoint) = @_;
929 my $volid = $mountpoint->{volume
};
930 my $mount = $mountpoint->{mp
};
932 return if !$volid || !$mount;
934 my $mount_path = "$rootdir/$mount";
935 $mount_path =~ s!/+!/!g;
937 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
940 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
953 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
955 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
956 File
::Path
::make_path
($rootdir);
958 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
959 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
962 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
963 my ($ms, $mountpoint) = @_;
965 $mountpoint->{ro
} = 0 if $ignore_ro;
967 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg);
971 warn "mounting container failed\n";
972 umount_all
($vmid, $storage_cfg, $conf, 1);
980 sub mountpoint_mount_path
{
981 my ($mountpoint, $storage_cfg, $snapname) = @_;
983 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
991 if ($line =~ m
@^(/dev/loop\d
+):@) {
995 my $cmd = ['losetup', '--associated', $path];
996 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1000 # Run a function with a file attached to a loop device.
1001 # The loop device is always detached afterwards (or set to autoclear).
1002 # Returns the loop device.
1003 sub run_with_loopdev
{
1004 my ($func, $file) = @_;
1005 my $device = query_loopdev
($file);
1006 # Try to reuse an existing device
1008 # We assume that whoever setup the loop device is responsible for
1016 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1020 PVE
::Tools
::run_command
(['losetup', '--show', '-f', $file], outfunc
=> $parser);
1021 die "failed to setup loop device for $file\n" if !$device;
1022 eval { &$func($device); };
1024 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1029 # In scalar mode: returns a file handle to the deepest directory node.
1030 # In list context: returns a list of:
1031 # * the deepest directory node
1032 # * the 2nd deepest directory (parent of the above)
1033 # * directory name of the last directory
1034 # So that the path $2/$3 should lead to $1 afterwards.
1035 sub walk_tree_nofollow
($$$) {
1036 my ($start, $subdir, $mkdir) = @_;
1038 # splitdir() returns '' for empty components including the leading /
1039 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1041 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1042 or die "failed to open start directory $start: $!\n";
1045 my $last_component = undef;
1047 foreach my $component (@comps) {
1048 $dir .= "/$component";
1049 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1052 # failed, check for symlinks and try to create the path
1053 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1054 die "cannot open directory $dir: $!\n" if !$mkdir;
1056 # We don't check for errors on mkdirat() here and just try to
1057 # openat() again, since at least one error (EEXIST) is an
1058 # expected possibility if multiple containers start
1059 # simultaneously. If someone else injects a symlink now then
1060 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1061 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1063 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1064 die "failed to create path: $dir: $!\n" if !$next;
1067 close $second if defined($last_component);
1068 $last_component = $component;
1073 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1074 close $second if defined($last_component);
1078 # To guard against symlink attack races against other currently running
1079 # containers with shared recursive bind mount hierarchies we prepare a
1080 # directory handle for the directory we're mounting over to verify the
1081 # mountpoint afterwards.
1082 sub __bindmount_prepare
{
1083 my ($hostroot, $dir) = @_;
1084 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1088 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1089 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1090 # we intended to bind mount.
1091 sub __bindmount_verify
{
1092 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1095 # Open the mount point path coming from the parent directory since the
1096 # filehandle we would have gotten as first result of walk_tree_nofollow
1097 # earlier is still a handle to the underlying directory instead of the
1099 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1100 die "failed to open mount point: $!\n" if !$destdh;
1103 # no separate function because 99% of the time it's the wrong thing to use.
1104 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1105 die "failed to mark bind mount read only\n";
1107 die "read-only check failed: $!\n" if $! != EROFS
;
1110 # For the rootfs we don't have a parentfd so we open the path directly.
1111 # Note that this means bindmounting any prefix of the host's
1112 # /var/lib/lxc/$vmid path into another container is considered a grave
1114 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1115 die "failed to open mount point: $!\n" if !$destdh;
1118 my ($srcdev, $srcinode) = stat($srcdh);
1119 my ($dstdev, $dstinode) = stat($destdh);
1123 return ($srcdev == $dstdev && $srcinode == $dstinode);
1126 # Perform the actual bind mounting:
1127 sub __bindmount_do
{
1128 my ($dir, $dest, $ro, @extra_opts) = @_;
1129 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1131 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1133 warn "bindmount error\n";
1134 # don't leave writable bind-mounts behind...
1135 PVE
::Tools
::run_command
(['umount', $dest]);
1142 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1144 my $srcdh = __bindmount_prepare
('/', $dir);
1146 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1148 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1149 PVE
::Tools
::run_command
(['umount', $dest]);
1150 die "detected mount path change at: $dir\n";
1154 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1155 # from $rootdir and $mount and walk the path from $rootdir to the final
1156 # directory to check for symlinks.
1157 sub __mount_prepare_rootdir
{
1158 my ($rootdir, $mount) = @_;
1159 $rootdir =~ s!/+!/!g;
1160 $rootdir =~ s!/+$!!;
1161 my $mount_path = "$rootdir/$mount";
1162 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1);
1163 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1166 # use $rootdir = undef to just return the corresponding mount path
1167 sub mountpoint_mount
{
1168 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1170 my $volid = $mountpoint->{volume
};
1171 my $mount = $mountpoint->{mp
};
1172 my $type = $mountpoint->{type
};
1173 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1176 return if !$volid || !$mount;
1181 my ($mpfd, $parentfd, $last_dir);
1183 if (defined($rootdir)) {
1184 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1185 __mount_prepare_rootdir
($rootdir, $mount);
1188 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1190 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1193 my $acl = $mountpoint->{acl
};
1194 if (defined($acl)) {
1195 $optstring .= ($acl ?
'acl' : 'noacl');
1197 my $readonly = $mountpoint->{ro
};
1199 my @extra_opts = ('-o', $optstring) if $optstring;
1203 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1205 # early sanity checks:
1206 # we otherwise call realpath on the rbd url
1207 die "containers on rbd storage without krbd are not supported\n"
1208 if $scfg->{type
} eq 'rbd' && !$scfg->{krbd
};
1210 my $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname);
1212 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1213 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1215 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1217 if ($format eq 'subvol') {
1220 if ($scfg->{type
} eq 'zfspool') {
1221 my $path_arg = $path;
1222 $path_arg =~ s!^/+!!;
1223 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1225 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1228 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1229 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1230 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1231 $name .= "\@$snapname" if defined($snapname);
1232 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1234 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1235 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1238 return wantarray ?
($path, 0, undef) : $path;
1239 } elsif ($format eq 'raw' || $format eq 'iso') {
1240 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1241 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1242 # Our autodev hook expects the /dev/dm-* device currently
1243 # and will create the /dev/mapper symlink accordingly
1244 $path = Cwd
::realpath
($path);
1245 die "failed to get device path\n" if !$path;
1246 ($path) = ($path =~ /^(.*)$/s); #untaint
1250 if ($format eq 'iso') {
1251 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1252 } elsif ($isBase || defined($snapname)) {
1253 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1256 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1258 push @extra_opts, '-o', 'ro' if $readonly;
1259 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1263 my $use_loopdev = 0;
1264 if ($scfg->{path
}) {
1265 $mounted_dev = run_with_loopdev
($domount, $path);
1267 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1268 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1269 $mounted_dev = $path;
1272 die "unsupported storage type '$scfg->{type}'\n";
1274 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1276 die "unsupported image format '$format'\n";
1278 } elsif ($type eq 'device') {
1279 push @extra_opts, '-o', 'ro' if $readonly;
1280 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1281 # See the NOTE above about devicemapper canonicalization
1282 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1283 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1284 return wantarray ?
($volid, 0, $devpath) : $volid;
1285 } elsif ($type eq 'bind') {
1286 die "directory '$volid' does not exist\n" if ! -d
$volid;
1287 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1288 warn "cannot enable quota control for bind mounts\n" if $quota;
1289 return wantarray ?
($volid, 0, undef) : $volid;
1292 die "unsupported storage";
1296 my ($dev, $rootuid, $rootgid) = @_;
1298 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1299 '-E', "root_owner=$rootuid:$rootgid",
1304 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1306 if ($volid =~ m!^/dev/.+!) {
1311 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1313 die "cannot format volume '$volid' with no storage\n" if !$storage;
1315 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1317 my $path = PVE
::Storage
::path
($storage_cfg, $volid);
1319 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1320 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1322 die "cannot format volume '$volid' (format == $format)\n"
1323 if $format ne 'raw';
1325 mkfs
($path, $rootuid, $rootgid);
1329 my ($storecfg, $vollist) = @_;
1331 foreach my $volid (@$vollist) {
1332 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1338 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1340 my $needs_chown = 0;
1343 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1344 # fixme: use better naming ct-$vmid-disk-X.raw?
1348 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs') {
1350 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1354 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1358 } elsif ($scfg->{type
} eq 'zfspool') {
1360 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1363 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1365 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1368 } elsif ($scfg->{type
} eq 'rbd') {
1370 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd
};
1371 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1374 die "unable to create containers on storage type '$scfg->{type}'\n";
1376 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1379 # in case formatting got interrupted:
1380 if (defined($volid)) {
1381 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1387 return ($volid, $needs_chown);
1390 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1392 my ($storecfg, $vmid, $settings, $conf) = @_;
1397 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1398 my $chown_vollist = [];
1400 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1401 my ($ms, $mountpoint) = @_;
1403 my $volid = $mountpoint->{volume
};
1404 my $mp = $mountpoint->{mp
};
1406 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1408 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1409 my ($storeid, $size_gb) = ($1, $2);
1411 my $size_kb = int(${size_gb
}*1024) * 1024;
1413 my $needs_chown = 0;
1414 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1415 push @$chown_vollist, $volid if $needs_chown;
1416 push @$vollist, $volid;
1417 $mountpoint->{volume
} = $volid;
1418 $mountpoint->{size
} = $size_kb * 1024;
1419 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1421 # use specified/existing volid/dir/device
1422 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1426 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1427 foreach my $volid (@$chown_vollist) {
1428 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1429 chown($rootuid, $rootgid, $path);
1431 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1433 # free allocated images on error
1435 destroy_disks
($storecfg, $vollist);
1441 # bash completion helper
1443 sub complete_os_templates
{
1444 my ($cmdname, $pname, $cvalue) = @_;
1446 my $cfg = PVE
::Storage
::config
();
1450 if ($cvalue =~ m/^([^:]+):/) {
1454 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
1455 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
1458 foreach my $id (keys %$data) {
1459 foreach my $item (@{$data->{$id}}) {
1460 push @$res, $item->{volid
} if defined($item->{volid
});
1467 my $complete_ctid_full = sub {
1470 my $idlist = vmstatus
();
1472 my $active_hash = list_active_containers
();
1476 foreach my $id (keys %$idlist) {
1477 my $d = $idlist->{$id};
1478 if (defined($running)) {
1479 next if $d->{template
};
1480 next if $running && !$active_hash->{$id};
1481 next if !$running && $active_hash->{$id};
1490 return &$complete_ctid_full();
1493 sub complete_ctid_stopped
{
1494 return &$complete_ctid_full(0);
1497 sub complete_ctid_running
{
1498 return &$complete_ctid_full(1);
1508 my $lxc = $conf->{lxc
};
1509 foreach my $entry (@$lxc) {
1510 my ($key, $value) = @$entry;
1511 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1512 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
1513 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1514 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1515 push @$id_map, [$type, $ct, $host, $length];
1517 $rootuid = $host if $type eq 'u';
1518 $rootgid = $host if $type eq 'g';
1521 die "failed to parse idmap: $value\n";
1525 if (!@$id_map && $conf->{unprivileged
}) {
1526 # Should we read them from /etc/subuid?
1527 $id_map = [ ['u', '0', '100000', '65536'],
1528 ['g', '0', '100000', '65536'] ];
1529 $rootuid = $rootgid = 100000;
1532 return ($id_map, $rootuid, $rootgid);
1535 sub userns_command
{
1538 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1544 my ($vmid, $conf, $skiplock) = @_;
1546 update_lxc_config
($vmid, $conf);
1548 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1551 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1555 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1557 eval { PVE
::Tools
::run_command
($cmd); };
1559 unlink $skiplock_flag_fn;
1566 # Helper to stop a container completely and make sure it has stopped completely.
1567 # This is necessary because we want the post-stop hook to have completed its
1568 # unmount-all step, but post-stop happens after lxc puts the container into the
1571 my ($vmid, $kill, $shutdown_timeout, $exit_timeout) = @_;
1573 # Open the container's command socket.
1574 my $path = "\0/var/lib/lxc/$vmid/command";
1575 my $sock = IO
::Socket
::UNIX-
>new(
1576 Type
=> SOCK_STREAM
(),
1580 return if $! == ECONNREFUSED
; # The container is not running
1581 die "failed to open container ${vmid}'s command socket: $!\n";
1584 # Stop the container:
1586 my $cmd = ['lxc-stop', '-n', $vmid];
1589 push @$cmd, '--kill'; # doesn't allow timeouts
1590 } elsif (defined($shutdown_timeout)) {
1591 push @$cmd, '--timeout', $shutdown_timeout;
1592 # Give run_command 5 extra seconds
1593 $shutdown_timeout += 5;
1596 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
1602 my $wait = sub { $result = <$sock>; };
1603 if (defined($exit_timeout)) {
1604 PVE
::Tools
::run_with_timeout
($exit_timeout, $wait);
1609 return if !defined $result; # monitor is gone and the ct has stopped.
1610 die "container did not stop\n";
1616 return PVE
::Tools
::run_fork
(sub {
1617 # Unshare the mount namespace
1618 die "failed to unshare mount namespace: $!\n"
1619 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
1620 PVE
::Tools
::run_command
(['mount', '--make-rslave', '/']);
1625 my $copy_volume = sub {
1626 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname) = @_;
1628 my $src_mp = { volume
=> $src_volid, mp
=> '/' };
1629 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
1631 my $dst_mp = { volume
=> $dst_volid, mp
=> '/' };
1632 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
1638 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname);
1639 push @mounted, $src;
1641 mountpoint_mount
($dst_mp, $dest, $storage_cfg);
1642 push @mounted, $dest;
1644 PVE
::Tools
::run_command
(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
1645 '-aH', '--whole-file', '--sparse', '--one-file-system',
1649 foreach my $mount (reverse @mounted) {
1650 eval { PVE
::Tools
::run_command
(['/bin/umount', '--lazy', $mount], errfunc
=> sub{})};
1651 warn "Can't umount $mount\n" if $@;
1654 # If this fails they're used as mount points in a concurrent operation
1655 # (which should not happen but there's also no real need to get rid of them).
1662 # Should not be called after unsharing the mount namespace!
1664 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname) = @_;
1666 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
1667 File
::Path
::make_path
("/var/lib/lxc/$vmid");
1668 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
1669 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
1671 # get id's for unprivileged container
1672 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1674 # Allocate the disk before unsharing in order to make sure zfs subvolumes
1675 # are visible in this namespace, otherwise the host only sees the empty
1676 # (not-mounted) directory.
1680 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
1682 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
1683 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
1684 chown($rootuid, $rootgid, $path);
1688 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname);
1692 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
1693 if defined($new_volid);