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];
130 my $clock_ticks = POSIX
::sysconf
(&POSIX
::_SC_CLK_TCK
);
132 my $unprivileged = {};
134 foreach my $vmid (keys %$list) {
135 my $d = $list->{$vmid};
137 eval { $d->{pid
} = find_lxc_pid
($vmid) if defined($active_hash->{$vmid}); };
138 warn $@ if $@; # ignore errors (consider them stopped)
140 $d->{status
} = $d->{pid
} ?
'running' : 'stopped';
142 my $cfspath = PVE
::LXC
::Config-
>cfs_config_path($vmid);
143 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
145 $unprivileged->{$vmid} = $conf->{unprivileged
};
147 $d->{name
} = $conf->{'hostname'} || "CT$vmid";
148 $d->{name
} =~ s/[\s]//g;
150 $d->{cpus
} = $conf->{cores
} || $conf->{cpulimit
};
151 $d->{cpus
} = $cpucount if !$d->{cpus
};
153 $d->{lock} = $conf->{lock} || '';
156 my $res = get_container_disk_usage
($vmid, $d->{pid
});
157 $d->{disk
} = $res->{used
};
158 $d->{maxdisk
} = $res->{total
};
161 # use 4GB by default ??
162 if (my $rootfs = $conf->{rootfs
}) {
163 my $rootinfo = PVE
::LXC
::Config-
>parse_ct_rootfs($rootfs);
164 $d->{maxdisk
} = $rootinfo->{size
} || (4*1024*1024*1024);
166 $d->{maxdisk
} = 4*1024*1024*1024;
172 $d->{maxmem
} = ($conf->{memory
}||512)*1024*1024;
173 $d->{maxswap
} = ($conf->{swap
}//0)*1024*1024;
184 $d->{template
} = PVE
::LXC
::Config-
>is_template($conf);
187 foreach my $vmid (keys %$list) {
188 my $d = $list->{$vmid};
191 next if !$pid; # skip stopped CTs
193 my $proc_pid_stat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
194 $d->{uptime
} = int(($uptime - $proc_pid_stat->{starttime
}) / $clock_ticks); # the method lxcfs uses
196 my $unpriv = $unprivileged->{$vmid};
198 my $memory_stat = read_cgroup_list
('memory', $vmid, $unpriv, 'memory.stat');
199 my $mem_usage_in_bytes = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
201 $d->{mem
} = $mem_usage_in_bytes - $memory_stat->{total_cache
};
202 $d->{swap
} = read_cgroup_value
('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
204 my $blkio_bytes = read_cgroup_value
('blkio', $vmid, $unpriv, 'blkio.throttle.io_service_bytes', 1);
205 my @bytes = split(/\n/, $blkio_bytes);
206 foreach my $byte (@bytes) {
207 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
208 $d->{diskread
} += $2 if $key eq 'Read';
209 $d->{diskwrite
} += $2 if $key eq 'Write';
213 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
215 my $used = $pstat->{utime} + $pstat->{stime
};
217 my $old = $last_proc_vmid_stat->{$vmid};
219 $last_proc_vmid_stat->{$vmid} = {
227 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
230 my $dutime = $used - $old->{used
};
232 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
233 $last_proc_vmid_stat->{$vmid} = {
239 $d->{cpu
} = $old->{cpu
};
243 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
245 foreach my $dev (keys %$netdev) {
246 next if $dev !~ m/^veth([1-9]\d*)i/;
248 my $d = $list->{$vmid};
252 $d->{netout
} += $netdev->{$dev}->{receive
};
253 $d->{netin
} += $netdev->{$dev}->{transmit
};
260 sub read_cgroup_list
($$$$) {
261 my ($group, $vmid, $unprivileged, $name) = @_;
263 my $content = read_cgroup_value
($group, $vmid, $unprivileged, $name, 1);
265 return { split(/\s+/, $content) };
268 sub read_cgroup_value
($$$$$) {
269 my ($group, $vmid, $unprivileged, $name, $full) = @_;
271 my $nsdir = $unprivileged ?
'' : 'ns/';
272 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
274 return PVE
::Tools
::file_get_contents
($path) if $full;
276 return PVE
::Tools
::file_read_firstline
($path);
279 sub write_cgroup_value
{
280 my ($group, $vmid, $name, $value) = @_;
282 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
283 PVE
::ProcFSTools
::write_proc_entry
($path, $value) if -e
$path;
287 sub find_lxc_console_pids
{
291 PVE
::Tools
::dir_glob_foreach
('/proc', '\d+', sub {
294 my $cmdline = PVE
::Tools
::file_read_firstline
("/proc/$pid/cmdline");
297 my @args = split(/\0/, $cmdline);
299 # search for lxc-console -n <vmid>
300 return if scalar(@args) != 3;
301 return if $args[1] ne '-n';
302 return if $args[2] !~ m/^\d+$/;
303 return if $args[0] !~ m
|^(/usr/bin
/)?lxc-console
$|;
307 push @{$res->{$vmid}}, $pid;
319 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
321 PVE
::Tools
::run_command
(['lxc-info', '-n', $vmid, '-p'], outfunc
=> $parser);
323 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
328 # Note: we cannot use Net:IP, because that only allows strict
330 sub parse_ipv4_cidr
{
331 my ($cidr, $noerr) = @_;
333 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
334 return { address
=> $1, netmask
=> $PVE::Network
::ipv4_reverse_mask-
>[$2] };
337 return undef if $noerr;
339 die "unable to parse ipv4 address/mask\n";
343 sub update_lxc_config
{
344 my ($vmid, $conf) = @_;
346 my $dir = "/var/lib/lxc/$vmid";
348 if ($conf->{template
}) {
350 unlink "$dir/config";
357 die "missing 'arch' - internal error" if !$conf->{arch
};
358 $raw .= "lxc.arch = $conf->{arch}\n";
360 my $unprivileged = $conf->{unprivileged
};
361 my $custom_idmap = grep { $_->[0] eq 'lxc.idmap' } @{$conf->{lxc
}};
363 my $ostype = $conf->{ostype
} || die "missing 'ostype' - internal error";
365 my $cfgpath = '/usr/share/lxc/config';
366 my $inc = "$cfgpath/$ostype.common.conf";
367 $inc ="$cfgpath/common.conf" if !-f
$inc;
368 $raw .= "lxc.include = $inc\n";
369 if ($unprivileged || $custom_idmap) {
370 $inc = "$cfgpath/$ostype.userns.conf";
371 $inc = "$cfgpath/userns.conf" if !-f
$inc;
372 $raw .= "lxc.include = $inc\n";
373 $raw .= "lxc.seccomp.profile = $cfgpath/pve-userns.seccomp\n";
376 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
377 # cannot be exposed to the container with r/w access (cgroup perms).
378 # When this is enabled mounts will still remain in the monitor's namespace
379 # after the container unmounted them and thus will not detach from their
380 # files while the container is running!
381 $raw .= "lxc.monitor.unshare = 1\n";
383 # Should we read them from /etc/subuid?
384 if ($unprivileged && !$custom_idmap) {
385 $raw .= "lxc.idmap = u 0 100000 65536\n";
386 $raw .= "lxc.idmap = g 0 100000 65536\n";
389 if (!PVE
::LXC
::Config-
>has_dev_console($conf)) {
390 $raw .= "lxc.console.path = none\n";
391 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
394 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
395 $raw .= "lxc.tty.max = $ttycount\n";
397 # some init scripts expect a linux terminal (turnkey).
398 $raw .= "lxc.environment = TERM=linux\n";
400 my $utsname = $conf->{hostname
} || "CT$vmid";
401 $raw .= "lxc.uts.name = $utsname\n";
403 my $memory = $conf->{memory
} || 512;
404 my $swap = $conf->{swap
} // 0;
406 my $lxcmem = int($memory*1024*1024);
407 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
409 my $lxcswap = int(($memory + $swap)*1024*1024);
410 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
412 if (my $cpulimit = $conf->{cpulimit
}) {
413 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
414 my $value = int(100000*$cpulimit);
415 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
418 my $shares = $conf->{cpuunits
} || 1024;
419 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
421 die "missing 'rootfs' configuration\n"
422 if !defined($conf->{rootfs
});
424 my $mountpoint = PVE
::LXC
::Config-
>parse_ct_rootfs($conf->{rootfs
});
426 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
428 foreach my $k (sort keys %$conf) {
429 next if $k !~ m/^net(\d+)$/;
431 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
432 $raw .= "lxc.net.$ind.type = veth\n";
433 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
434 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr
});
435 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name
});
436 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu
});
440 if (my $lxcconf = $conf->{lxc
}) {
441 foreach my $entry (@$lxcconf) {
442 my ($k, $v) = @$entry;
443 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
448 my $cores = $conf->{cores
};
449 if (!$had_cpuset && $cores) {
450 my $cpuset = eval { PVE
::CpuSet-
>new_from_cgroup('lxc', 'effective_cpus') };
451 $cpuset = PVE
::CpuSet-
>new_from_cgroup('', 'effective_cpus') if !$cpuset;
452 my @members = $cpuset->members();
453 while (scalar(@members) > $cores) {
454 my $randidx = int(rand(scalar(@members)));
455 $cpuset->delete($members[$randidx]);
456 splice(@members, $randidx, 1); # keep track of the changes
458 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
461 File
::Path
::mkpath
("$dir/rootfs");
463 PVE
::Tools
::file_set_contents
("$dir/config", $raw);
466 # verify and cleanup nameserver list (replace \0 with ' ')
467 sub verify_nameserver_list
{
468 my ($nameserver_list) = @_;
471 foreach my $server (PVE
::Tools
::split_list
($nameserver_list)) {
472 PVE
::JSONSchema
::pve_verify_ip
($server);
476 return join(' ', @list);
479 sub verify_searchdomain_list
{
480 my ($searchdomain_list) = @_;
483 foreach my $server (PVE
::Tools
::split_list
($searchdomain_list)) {
484 # todo: should we add checks for valid dns domains?
488 return join(' ', @list);
491 sub get_console_command
{
492 my ($vmid, $conf, $noescapechar) = @_;
494 my $cmode = PVE
::LXC
::Config-
>get_cmode($conf);
497 if ($cmode eq 'console') {
498 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
499 push @$cmd, '-e', -1 if $noescapechar;
500 } elsif ($cmode eq 'tty') {
501 push @$cmd, 'lxc-console', '-n', $vmid;
502 push @$cmd, '-e', -1 if $noescapechar;
503 } elsif ($cmode eq 'shell') {
504 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
506 die "internal error";
512 sub get_primary_ips
{
515 # return data from net0
517 return undef if !defined($conf->{net0
});
518 my $net = PVE
::LXC
::Config-
>parse_lxc_network($conf->{net0
});
520 my $ipv4 = $net->{ip
};
522 if ($ipv4 =~ /^(dhcp|manual)$/) {
528 my $ipv6 = $net->{ip6
};
530 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
537 return ($ipv4, $ipv6);
540 sub delete_mountpoint_volume
{
541 my ($storage_cfg, $vmid, $volume) = @_;
543 return if PVE
::LXC
::Config-
>classify_mountpoint($volume) ne 'volume';
545 my ($vtype, $name, $owner) = PVE
::Storage
::parse_volname
($storage_cfg, $volume);
546 PVE
::Storage
::vdisk_free
($storage_cfg, $volume) if $vmid == $owner;
549 sub destroy_lxc_container
{
550 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
552 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
553 my ($ms, $mountpoint) = @_;
554 delete_mountpoint_volume
($storage_cfg, $vmid, $mountpoint->{volume
});
557 rmdir "/var/lib/lxc/$vmid/rootfs";
558 unlink "/var/lib/lxc/$vmid/config";
559 rmdir "/var/lib/lxc/$vmid";
560 if (defined $replacement_conf) {
561 PVE
::LXC
::Config-
>write_config($vmid, $replacement_conf);
563 destroy_config
($vmid);
566 #my $cmd = ['lxc-destroy', '-n', $vmid ];
567 #PVE::Tools::run_command($cmd);
570 sub vm_stop_cleanup
{
571 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
576 my $vollist = PVE
::LXC
::Config-
>get_vm_volumes($conf);
577 PVE
::Storage
::deactivate_volumes
($storage_cfg, $vollist);
580 warn $@ if $@; # avoid errors - just warn
583 my $safe_num_ne = sub {
586 return 0 if !defined($a) && !defined($b);
587 return 1 if !defined($a);
588 return 1 if !defined($b);
593 my $safe_string_ne = sub {
596 return 0 if !defined($a) && !defined($b);
597 return 1 if !defined($a);
598 return 1 if !defined($b);
604 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
606 if ($newnet->{type
} ne 'veth') {
607 # for when there are physical interfaces
608 die "cannot update interface of type $newnet->{type}";
611 my $veth = "veth${vmid}i${netid}";
612 my $eth = $newnet->{name
};
614 if (my $oldnetcfg = $conf->{$opt}) {
615 my $oldnet = PVE
::LXC
::Config-
>parse_lxc_network($oldnetcfg);
617 if (&$safe_string_ne($oldnet->{hwaddr
}, $newnet->{hwaddr
}) ||
618 &$safe_string_ne($oldnet->{name
}, $newnet->{name
})) {
620 PVE
::Network
::veth_delete
($veth);
621 delete $conf->{$opt};
622 PVE
::LXC
::Config-
>write_config($vmid, $conf);
624 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
627 if (&$safe_string_ne($oldnet->{bridge
}, $newnet->{bridge
}) ||
628 &$safe_num_ne($oldnet->{tag
}, $newnet->{tag
}) ||
629 &$safe_num_ne($oldnet->{firewall
}, $newnet->{firewall
})) {
631 if ($oldnet->{bridge
}) {
632 PVE
::Network
::tap_unplug
($veth);
633 foreach (qw(bridge tag firewall)) {
634 delete $oldnet->{$_};
636 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
637 PVE
::LXC
::Config-
>write_config($vmid, $conf);
640 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
641 # This includes the rate:
642 foreach (qw(bridge tag firewall rate)) {
643 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
645 } elsif (&$safe_string_ne($oldnet->{rate
}, $newnet->{rate
})) {
646 # Rate can be applied on its own but any change above needs to
647 # include the rate in tap_plug since OVS resets everything.
648 PVE
::Network
::tap_rate_limit
($veth, $newnet->{rate
});
649 $oldnet->{rate
} = $newnet->{rate
}
651 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($oldnet);
652 PVE
::LXC
::Config-
>write_config($vmid, $conf);
655 hotplug_net
($vmid, $conf, $opt, $newnet, $netid);
658 update_ipconfig
($vmid, $conf, $opt, $eth, $newnet, $rootdir);
662 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
664 my $veth = "veth${vmid}i${netid}";
665 my $vethpeer = $veth . "p";
666 my $eth = $newnet->{name
};
668 PVE
::Network
::veth_create
($veth, $vethpeer, $newnet->{bridge
}, $newnet->{hwaddr
});
669 PVE
::Network
::tap_plug
($veth, $newnet->{bridge
}, $newnet->{tag
}, $newnet->{firewall
}, $newnet->{trunks
}, $newnet->{rate
});
671 # attach peer in container
672 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
673 PVE
::Tools
::run_command
($cmd);
675 # link up peer in container
676 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
677 PVE
::Tools
::run_command
($cmd);
679 my $done = { type
=> 'veth' };
680 foreach (qw(bridge tag firewall hwaddr name)) {
681 $done->{$_} = $newnet->{$_} if $newnet->{$_};
683 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($done);
685 PVE
::LXC
::Config-
>write_config($vmid, $conf);
688 sub update_ipconfig
{
689 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
691 my $lxc_setup = PVE
::LXC
::Setup-
>new($conf, $rootdir);
693 my $optdata = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$opt});
698 PVE
::Tools
::run_command
(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
700 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
702 my $change_ip_config = sub {
703 my ($ipversion) = @_;
705 my $family_opt = "-$ipversion";
706 my $suffix = $ipversion == 4 ?
'' : $ipversion;
710 my $newip = $newnet->{$ip};
711 my $newgw = $newnet->{$gw};
712 my $oldip = $optdata->{$ip};
714 my $change_ip = &$safe_string_ne($oldip, $newip);
715 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
717 return if !$change_ip && !$change_gw;
719 # step 1: add new IP, if this fails we cancel
720 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
721 if ($change_ip && $is_real_ip) {
722 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
729 # step 2: replace gateway
730 # If this fails we delete the added IP and cancel.
731 # If it succeeds we save the config and delete the old IP, ignoring
732 # errors. The config is then saved.
733 # Note: 'ip route replace' can add
737 if ($is_real_ip && !PVE
::Network
::is_ip_in_cidr
($newgw, $newip, $ipversion)) {
738 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
740 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
744 # the route was not replaced, the old IP is still available
745 # rollback (delete new IP) and cancel
747 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
748 warn $@ if $@; # no need to die here
753 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
754 # if the route was not deleted, the guest might have deleted it manually
760 # from this point on we save the configuration
761 # step 3: delete old IP ignoring errors
762 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
763 # We need to enable promote_secondaries, otherwise our newly added
764 # address will be removed along with the old one.
767 if ($ipversion == 4) {
768 &$nscmd({ outfunc
=> sub { $promote = int(shift) } },
769 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
770 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
772 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
774 warn $@ if $@; # no need to die here
776 if ($ipversion == 4) {
777 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
781 foreach my $property ($ip, $gw) {
782 if ($newnet->{$property}) {
783 $optdata->{$property} = $newnet->{$property};
785 delete $optdata->{$property};
788 $conf->{$opt} = PVE
::LXC
::Config-
>print_lxc_network($optdata);
789 PVE
::LXC
::Config-
>write_config($vmid, $conf);
790 $lxc_setup->setup_network($conf);
793 &$change_ip_config(4);
794 &$change_ip_config(6);
798 my $enter_namespace = sub {
799 my ($vmid, $pid, $which, $type) = @_;
800 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
801 or die "failed to open $which namespace of container $vmid: $!\n";
802 PVE
::Tools
::setns
(fileno($fd), $type)
803 or die "failed to enter $which namespace of container $vmid: $!\n";
807 my $do_syncfs = sub {
808 my ($vmid, $pid, $socket) = @_;
810 &$enter_namespace($vmid, $pid, 'mnt', PVE
::Tools
::CLONE_NEWNS
);
812 # Tell the parent process to start reading our /proc/mounts
813 print {$socket} "go\n";
816 # Receive /proc/self/mounts
817 my $mountdata = do { local $/ = undef; <$socket> };
820 # Now sync all mountpoints...
821 my $mounts = PVE
::ProcFSTools
::parse_mounts
($mountdata);
822 foreach my $mp (@$mounts) {
823 my ($what, $dir, $fs) = @$mp;
824 next if $fs eq 'fuse.lxcfs';
825 eval { PVE
::Tools
::sync_mountpoint
($dir); };
830 sub sync_container_namespace
{
832 my $pid = find_lxc_pid
($vmid);
834 # SOCK_DGRAM is nicer for barriers but cannot be slurped
835 socketpair my $pfd, my $cfd, AF_UNIX
, SOCK_STREAM
, PF_UNSPEC
836 or die "failed to create socketpair: $!\n";
839 die "fork failed: $!\n" if !defined($child);
844 &$do_syncfs($vmid, $pid, $cfd);
854 die "failed to enter container namespace\n" if $go ne "go\n";
856 open my $mounts, '<', "/proc/$child/mounts"
857 or die "failed to open container's /proc/mounts: $!\n";
858 my $mountdata = do { local $/ = undef; <$mounts> };
860 print {$pfd} $mountdata;
863 while (waitpid($child, 0) != $child) {}
864 die "failed to sync container namespace\n" if $? != 0;
867 sub template_create
{
868 my ($vmid, $conf) = @_;
870 my $storecfg = PVE
::Storage
::config
();
872 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
873 my ($ms, $mountpoint) = @_;
875 my $volid = $mountpoint->{volume
};
877 die "Template feature is not available for '$volid'\n"
878 if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
881 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
882 my ($ms, $mountpoint) = @_;
884 my $volid = $mountpoint->{volume
};
886 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
888 my $template_volid = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
889 $mountpoint->{volume
} = $template_volid;
890 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq "rootfs");
893 PVE
::LXC
::Config-
>write_config($vmid, $conf);
896 sub check_ct_modify_config_perm
{
897 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
899 return 1 if $authuser eq 'root@pam';
902 my ($opt, $delete) = @_;
903 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
904 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
905 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
906 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
908 my $data = $opt eq 'rootfs' ? PVE
::LXC
::Config-
>parse_ct_rootfs($newconf->{$opt})
909 : PVE
::LXC
::Config-
>parse_ct_mountpoint($newconf->{$opt});
910 raise_perm_exc
("mount point type $data->{type} is only allowed for root\@pam")
911 if $data->{type
} ne 'volume';
912 } elsif ($opt eq 'memory' || $opt eq 'swap') {
913 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
914 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
915 $opt eq 'searchdomain' || $opt eq 'hostname') {
916 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
918 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
922 foreach my $opt (keys %$newconf) {
925 foreach my $opt (@$delete) {
933 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
935 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
936 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
938 PVE
::LXC
::Config-
>foreach_mountpoint_reverse($conf, sub {
939 my ($ms, $mountpoint) = @_;
941 my $volid = $mountpoint->{volume
};
942 my $mount = $mountpoint->{mp
};
944 return if !$volid || !$mount;
946 my $mount_path = "$rootdir/$mount";
947 $mount_path =~ s!/+!/!g;
949 return if !PVE
::ProcFSTools
::is_mounted
($mount_path);
952 PVE
::Tools
::run_command
(['umount', '-d', $mount_path]);
965 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
967 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
968 File
::Path
::make_path
($rootdir);
970 my $volid_list = PVE
::LXC
::Config-
>get_vm_volumes($conf);
971 PVE
::Storage
::activate_volumes
($storage_cfg, $volid_list);
974 PVE
::LXC
::Config-
>foreach_mountpoint($conf, sub {
975 my ($ms, $mountpoint) = @_;
977 $mountpoint->{ro
} = 0 if $ignore_ro;
979 mountpoint_mount
($mountpoint, $rootdir, $storage_cfg);
983 warn "mounting container failed\n";
984 umount_all
($vmid, $storage_cfg, $conf, 1);
992 sub mountpoint_mount_path
{
993 my ($mountpoint, $storage_cfg, $snapname) = @_;
995 return mountpoint_mount
($mountpoint, undef, $storage_cfg, $snapname);
1003 if ($line =~ m
@^(/dev/loop\d
+):@) {
1007 my $cmd = ['losetup', '--associated', $path];
1008 PVE
::Tools
::run_command
($cmd, outfunc
=> $parser);
1012 # Run a function with a file attached to a loop device.
1013 # The loop device is always detached afterwards (or set to autoclear).
1014 # Returns the loop device.
1015 sub run_with_loopdev
{
1016 my ($func, $file) = @_;
1017 my $device = query_loopdev
($file);
1018 # Try to reuse an existing device
1020 # We assume that whoever setup the loop device is responsible for
1028 if ($line =~ m
@^(/dev/loop\d
+)$@) {
1032 PVE
::Tools
::run_command
(['losetup', '--show', '-f', $file], outfunc
=> $parser);
1033 die "failed to setup loop device for $file\n" if !$device;
1034 eval { &$func($device); };
1036 PVE
::Tools
::run_command
(['losetup', '-d', $device]);
1041 # In scalar mode: returns a file handle to the deepest directory node.
1042 # In list context: returns a list of:
1043 # * the deepest directory node
1044 # * the 2nd deepest directory (parent of the above)
1045 # * directory name of the last directory
1046 # So that the path $2/$3 should lead to $1 afterwards.
1047 sub walk_tree_nofollow
($$$) {
1048 my ($start, $subdir, $mkdir) = @_;
1050 # splitdir() returns '' for empty components including the leading /
1051 my @comps = grep { length($_)>0 } File
::Spec-
>splitdir($subdir);
1053 sysopen(my $fd, $start, O_PATH
| O_DIRECTORY
)
1054 or die "failed to open start directory $start: $!\n";
1057 my $last_component = undef;
1059 foreach my $component (@comps) {
1060 $dir .= "/$component";
1061 my $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1064 # failed, check for symlinks and try to create the path
1065 die "symlink encountered at: $dir\n" if $! == ELOOP
|| $! == ENOTDIR
;
1066 die "cannot open directory $dir: $!\n" if !$mkdir;
1068 # We don't check for errors on mkdirat() here and just try to
1069 # openat() again, since at least one error (EEXIST) is an
1070 # expected possibility if multiple containers start
1071 # simultaneously. If someone else injects a symlink now then
1072 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1073 PVE
::Tools
::mkdirat
(fileno($fd), $component, 0755);
1075 $next = PVE
::Tools
::openat
(fileno($fd), $component, O_NOFOLLOW
| O_DIRECTORY
);
1076 die "failed to create path: $dir: $!\n" if !$next;
1079 close $second if defined($last_component);
1080 $last_component = $component;
1085 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1086 close $second if defined($last_component);
1090 # To guard against symlink attack races against other currently running
1091 # containers with shared recursive bind mount hierarchies we prepare a
1092 # directory handle for the directory we're mounting over to verify the
1093 # mountpoint afterwards.
1094 sub __bindmount_prepare
{
1095 my ($hostroot, $dir) = @_;
1096 my $srcdh = walk_tree_nofollow
($hostroot, $dir, 0);
1100 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1101 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1102 # we intended to bind mount.
1103 sub __bindmount_verify
{
1104 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1107 # Open the mount point path coming from the parent directory since the
1108 # filehandle we would have gotten as first result of walk_tree_nofollow
1109 # earlier is still a handle to the underlying directory instead of the
1111 $destdh = PVE
::Tools
::openat
(fileno($parentfd), $last_dir, PVE
::Tools
::O_PATH
| O_NOFOLLOW
| O_DIRECTORY
);
1112 die "failed to open mount point: $!\n" if !$destdh;
1115 # no separate function because 99% of the time it's the wrong thing to use.
1116 if (syscall(PVE
::Syscall
::faccessat
, fileno($destdh), $dot, &POSIX
::W_OK
, 0) != -1) {
1117 die "failed to mark bind mount read only\n";
1119 die "read-only check failed: $!\n" if $! != EROFS
;
1122 # For the rootfs we don't have a parentfd so we open the path directly.
1123 # Note that this means bindmounting any prefix of the host's
1124 # /var/lib/lxc/$vmid path into another container is considered a grave
1126 sysopen $destdh, $last_dir, O_PATH
| O_DIRECTORY
;
1127 die "failed to open mount point: $!\n" if !$destdh;
1130 my ($srcdev, $srcinode) = stat($srcdh);
1131 my ($dstdev, $dstinode) = stat($destdh);
1135 return ($srcdev == $dstdev && $srcinode == $dstinode);
1138 # Perform the actual bind mounting:
1139 sub __bindmount_do
{
1140 my ($dir, $dest, $ro, @extra_opts) = @_;
1141 PVE
::Tools
::run_command
(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1143 eval { PVE
::Tools
::run_command
(['mount', '-o', 'bind,remount,ro', $dest]); };
1145 warn "bindmount error\n";
1146 # don't leave writable bind-mounts behind...
1147 PVE
::Tools
::run_command
(['umount', $dest]);
1154 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1156 my $srcdh = __bindmount_prepare
('/', $dir);
1158 __bindmount_do
($dir, $dest, $ro, @extra_opts);
1160 if (!__bindmount_verify
($srcdh, $parentfd, $last_dir, $ro)) {
1161 PVE
::Tools
::run_command
(['umount', $dest]);
1162 die "detected mount path change at: $dir\n";
1166 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1167 # from $rootdir and $mount and walk the path from $rootdir to the final
1168 # directory to check for symlinks.
1169 sub __mount_prepare_rootdir
{
1170 my ($rootdir, $mount) = @_;
1171 $rootdir =~ s!/+!/!g;
1172 $rootdir =~ s!/+$!!;
1173 my $mount_path = "$rootdir/$mount";
1174 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow
($rootdir, $mount, 1);
1175 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1178 # use $rootdir = undef to just return the corresponding mount path
1179 sub mountpoint_mount
{
1180 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1182 my $volid = $mountpoint->{volume
};
1183 my $mount = $mountpoint->{mp
};
1184 my $type = $mountpoint->{type
};
1185 my $quota = !$snapname && !$mountpoint->{ro
} && $mountpoint->{quota
};
1188 return if !$volid || !$mount;
1193 my ($mpfd, $parentfd, $last_dir);
1195 if (defined($rootdir)) {
1196 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1197 __mount_prepare_rootdir
($rootdir, $mount);
1200 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1202 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1205 my $acl = $mountpoint->{acl
};
1206 if (defined($acl)) {
1207 $optstring .= ($acl ?
'acl' : 'noacl');
1209 my $readonly = $mountpoint->{ro
};
1212 @extra_opts = ('-o', $optstring) if $optstring;
1216 my $scfg = PVE
::Storage
::storage_config
($storage_cfg, $storage);
1218 # early sanity checks:
1219 # we otherwise call realpath on the rbd url
1220 die "containers on rbd storage without krbd are not supported\n"
1221 if $scfg->{type
} eq 'rbd' && !$scfg->{krbd
};
1223 my $path = PVE
::Storage
::path
($storage_cfg, $volid, $snapname);
1225 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1226 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1228 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1230 if ($format eq 'subvol') {
1233 if ($scfg->{type
} eq 'zfspool') {
1234 my $path_arg = $path;
1235 $path_arg =~ s!^/+!!;
1236 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1238 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1241 if (defined($acl) && $scfg->{type
} eq 'zfspool') {
1242 my $acltype = ($acl ?
'acltype=posixacl' : 'acltype=noacl');
1243 my (undef, $name) = PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1244 $name .= "\@$snapname" if defined($snapname);
1245 PVE
::Tools
::run_command
(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1247 bindmount
($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1248 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1251 return wantarray ?
($path, 0, undef) : $path;
1252 } elsif ($format eq 'raw' || $format eq 'iso') {
1253 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1254 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1255 # Our autodev hook expects the /dev/dm-* device currently
1256 # and will create the /dev/mapper symlink accordingly
1257 $path = Cwd
::realpath
($path);
1258 die "failed to get device path\n" if !$path;
1259 ($path) = ($path =~ /^(.*)$/s); #untaint
1263 if ($format eq 'iso') {
1264 PVE
::Tools
::run_command
(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1265 } elsif ($isBase || defined($snapname)) {
1266 PVE
::Tools
::run_command
(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1269 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1271 push @extra_opts, '-o', 'ro' if $readonly;
1272 PVE
::Tools
::run_command
(['mount', @extra_opts, $path, $mount_path]);
1276 my $use_loopdev = 0;
1277 if ($scfg->{path
}) {
1278 $mounted_dev = run_with_loopdev
($domount, $path);
1280 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' ||
1281 $scfg->{type
} eq 'rbd' || $scfg->{type
} eq 'lvmthin') {
1282 $mounted_dev = $path;
1285 die "unsupported storage type '$scfg->{type}'\n";
1287 return wantarray ?
($path, $use_loopdev, $mounted_dev) : $path;
1289 die "unsupported image format '$format'\n";
1291 } elsif ($type eq 'device') {
1292 push @extra_opts, '-o', 'ro' if $readonly;
1293 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1294 # See the NOTE above about devicemapper canonicalization
1295 my ($devpath) = (Cwd
::realpath
($volid) =~ /^(.*)$/s); # realpath() taints
1296 PVE
::Tools
::run_command
(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1297 return wantarray ?
($volid, 0, $devpath) : $volid;
1298 } elsif ($type eq 'bind') {
1299 die "directory '$volid' does not exist\n" if ! -d
$volid;
1300 bindmount
($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1301 warn "cannot enable quota control for bind mounts\n" if $quota;
1302 return wantarray ?
($volid, 0, undef) : $volid;
1305 die "unsupported storage";
1309 my ($dev, $rootuid, $rootgid) = @_;
1311 PVE
::Tools
::run_command
(['mkfs.ext4', '-O', 'mmp',
1312 '-E', "root_owner=$rootuid:$rootgid",
1317 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1319 if ($volid =~ m!^/dev/.+!) {
1324 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1326 die "cannot format volume '$volid' with no storage\n" if !$storage;
1328 PVE
::Storage
::activate_volumes
($storage_cfg, [$volid]);
1330 my $path = PVE
::Storage
::path
($storage_cfg, $volid);
1332 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1333 PVE
::Storage
::parse_volname
($storage_cfg, $volid);
1335 die "cannot format volume '$volid' (format == $format)\n"
1336 if $format ne 'raw';
1338 mkfs
($path, $rootuid, $rootgid);
1342 my ($storecfg, $vollist) = @_;
1344 foreach my $volid (@$vollist) {
1345 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1351 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1353 my $needs_chown = 0;
1356 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storage);
1357 # fixme: use better naming ct-$vmid-disk-X.raw?
1361 if ($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'nfs' || $scfg->{type
} eq 'cifs' ) {
1363 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw',
1367 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1371 } elsif ($scfg->{type
} eq 'zfspool') {
1373 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'subvol',
1376 } elsif ($scfg->{type
} eq 'drbd' || $scfg->{type
} eq 'lvm' || $scfg->{type
} eq 'lvmthin') {
1378 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1381 } elsif ($scfg->{type
} eq 'rbd') {
1383 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd
};
1384 $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1387 die "unable to create containers on storage type '$scfg->{type}'\n";
1389 format_disk
($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1392 # in case formatting got interrupted:
1393 if (defined($volid)) {
1394 eval { PVE
::Storage
::vdisk_free
($storecfg, $volid); };
1400 return ($volid, $needs_chown);
1403 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1405 my ($storecfg, $vmid, $settings, $conf) = @_;
1410 my (undef, $rootuid, $rootgid) = PVE
::LXC
::parse_id_maps
($conf);
1411 my $chown_vollist = [];
1413 PVE
::LXC
::Config-
>foreach_mountpoint($settings, sub {
1414 my ($ms, $mountpoint) = @_;
1416 my $volid = $mountpoint->{volume
};
1417 my $mp = $mountpoint->{mp
};
1419 my ($storage, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1421 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1422 my ($storeid, $size_gb) = ($1, $2);
1424 my $size_kb = int(${size_gb
}*1024) * 1024;
1426 my $needs_chown = 0;
1427 ($volid, $needs_chown) = alloc_disk
($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1428 push @$chown_vollist, $volid if $needs_chown;
1429 push @$vollist, $volid;
1430 $mountpoint->{volume
} = $volid;
1431 $mountpoint->{size
} = $size_kb * 1024;
1432 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1434 # use specified/existing volid/dir/device
1435 $conf->{$ms} = PVE
::LXC
::Config-
>print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1439 PVE
::Storage
::activate_volumes
($storecfg, $chown_vollist, undef);
1440 foreach my $volid (@$chown_vollist) {
1441 my $path = PVE
::Storage
::path
($storecfg, $volid, undef);
1442 chown($rootuid, $rootgid, $path);
1444 PVE
::Storage
::deactivate_volumes
($storecfg, $chown_vollist, undef);
1446 # free allocated images on error
1448 destroy_disks
($storecfg, $vollist);
1454 # bash completion helper
1456 sub complete_os_templates
{
1457 my ($cmdname, $pname, $cvalue) = @_;
1459 my $cfg = PVE
::Storage
::config
();
1463 if ($cvalue =~ m/^([^:]+):/) {
1467 my $vtype = $cmdname eq 'restore' ?
'backup' : 'vztmpl';
1468 my $data = PVE
::Storage
::template_list
($cfg, $storeid, $vtype);
1471 foreach my $id (keys %$data) {
1472 foreach my $item (@{$data->{$id}}) {
1473 push @$res, $item->{volid
} if defined($item->{volid
});
1480 my $complete_ctid_full = sub {
1483 my $idlist = vmstatus
();
1485 my $active_hash = list_active_containers
();
1489 foreach my $id (keys %$idlist) {
1490 my $d = $idlist->{$id};
1491 if (defined($running)) {
1492 next if $d->{template
};
1493 next if $running && !$active_hash->{$id};
1494 next if !$running && $active_hash->{$id};
1503 return &$complete_ctid_full();
1506 sub complete_ctid_stopped
{
1507 return &$complete_ctid_full(0);
1510 sub complete_ctid_running
{
1511 return &$complete_ctid_full(1);
1521 my $lxc = $conf->{lxc
};
1522 foreach my $entry (@$lxc) {
1523 my ($key, $value) = @$entry;
1524 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1525 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
1526 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1527 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1528 push @$id_map, [$type, $ct, $host, $length];
1530 $rootuid = $host if $type eq 'u';
1531 $rootgid = $host if $type eq 'g';
1534 die "failed to parse idmap: $value\n";
1538 if (!@$id_map && $conf->{unprivileged
}) {
1539 # Should we read them from /etc/subuid?
1540 $id_map = [ ['u', '0', '100000', '65536'],
1541 ['g', '0', '100000', '65536'] ];
1542 $rootuid = $rootgid = 100000;
1545 return ($id_map, $rootuid, $rootgid);
1548 sub userns_command
{
1551 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1557 my ($vmid, $conf, $skiplock) = @_;
1559 update_lxc_config
($vmid, $conf);
1561 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1564 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1568 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1570 eval { PVE
::Tools
::run_command
($cmd); };
1572 unlink $skiplock_flag_fn;
1579 # Helper to stop a container completely and make sure it has stopped completely.
1580 # This is necessary because we want the post-stop hook to have completed its
1581 # unmount-all step, but post-stop happens after lxc puts the container into the
1584 my ($vmid, $kill, $shutdown_timeout, $exit_timeout) = @_;
1586 # Open the container's command socket.
1587 my $path = "\0/var/lib/lxc/$vmid/command";
1588 my $sock = IO
::Socket
::UNIX-
>new(
1589 Type
=> SOCK_STREAM
(),
1593 return if $! == ECONNREFUSED
; # The container is not running
1594 die "failed to open container ${vmid}'s command socket: $!\n";
1597 # Stop the container:
1599 my $cmd = ['lxc-stop', '-n', $vmid];
1602 push @$cmd, '--kill'; # doesn't allow timeouts
1603 } elsif (defined($shutdown_timeout)) {
1604 push @$cmd, '--timeout', $shutdown_timeout;
1605 # Give run_command 5 extra seconds
1606 $shutdown_timeout += 5;
1609 eval { PVE
::Tools
::run_command
($cmd, timeout
=> $shutdown_timeout) };
1615 my $wait = sub { $result = <$sock>; };
1616 if (defined($exit_timeout)) {
1617 PVE
::Tools
::run_with_timeout
($exit_timeout, $wait);
1622 return if !defined $result; # monitor is gone and the ct has stopped.
1623 die "container did not stop\n";
1629 return PVE
::Tools
::run_fork
(sub {
1630 # Unshare the mount namespace
1631 die "failed to unshare mount namespace: $!\n"
1632 if !PVE
::Tools
::unshare
(PVE
::Tools
::CLONE_NEWNS
);
1633 PVE
::Tools
::run_command
(['mount', '--make-rslave', '/']);
1638 my $copy_volume = sub {
1639 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname) = @_;
1641 my $src_mp = { volume
=> $src_volid, mp
=> '/' };
1642 $src_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($src_volid);
1644 my $dst_mp = { volume
=> $dst_volid, mp
=> '/' };
1645 $dst_mp->{type
} = PVE
::LXC
::Config-
>classify_mountpoint($dst_volid);
1651 mountpoint_mount
($src_mp, $src, $storage_cfg, $snapname);
1652 push @mounted, $src;
1654 mountpoint_mount
($dst_mp, $dest, $storage_cfg);
1655 push @mounted, $dest;
1657 PVE
::Tools
::run_command
(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
1658 '-aH', '--whole-file', '--sparse', '--one-file-system',
1662 foreach my $mount (reverse @mounted) {
1663 eval { PVE
::Tools
::run_command
(['/bin/umount', '--lazy', $mount], errfunc
=> sub{})};
1664 warn "Can't umount $mount\n" if $@;
1667 # If this fails they're used as mount points in a concurrent operation
1668 # (which should not happen but there's also no real need to get rid of them).
1675 # Should not be called after unsharing the mount namespace!
1677 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname) = @_;
1679 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type
} ne 'volume';
1680 File
::Path
::make_path
("/var/lib/lxc/$vmid");
1681 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
1682 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
1684 # get id's for unprivileged container
1685 my (undef, $rootuid, $rootgid) = parse_id_maps
($conf);
1687 # Allocate the disk before unsharing in order to make sure zfs subvolumes
1688 # are visible in this namespace, otherwise the host only sees the empty
1689 # (not-mounted) directory.
1692 # Make sure $mp contains a correct size.
1693 $mp->{size
} = PVE
::Storage
::volume_size_info
($storage_cfg, $mp->{volume
});
1695 ($new_volid, $needs_chown) = alloc_disk
($storage_cfg, $vmid, $storage, $mp->{size
}/1024, $rootuid, $rootgid);
1697 PVE
::Storage
::activate_volumes
($storage_cfg, [$new_volid], undef);
1698 my $path = PVE
::Storage
::path
($storage_cfg, $new_volid, undef);
1699 chown($rootuid, $rootgid, $path);
1703 $copy_volume->($mp->{volume
}, $src, $new_volid, $dest, $storage_cfg, $snapname);
1707 PVE
::Storage
::vdisk_free
($storage_cfg, $new_volid)
1708 if defined($new_volid);