]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC.pm
use Syscall module instead of raw syscall numbers
[pve-container.git] / src / PVE / LXC.pm
1 package PVE::LXC;
2
3 use strict;
4 use warnings;
5
6 use POSIX qw(EINTR);
7
8 use Socket;
9
10 use File::Path;
11 use File::Spec;
12 use Cwd qw();
13 use Fcntl qw(O_RDONLY O_NOFOLLOW O_DIRECTORY);
14 use Errno qw(ELOOP ENOTDIR EROFS);
15
16 use PVE::Exception qw(raise_perm_exc);
17 use PVE::Storage;
18 use PVE::SafeSyslog;
19 use PVE::INotify;
20 use PVE::Tools qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH);
21 use PVE::CpuSet;
22 use PVE::Network;
23 use PVE::AccessControl;
24 use PVE::ProcFSTools;
25 use PVE::Syscall;
26 use PVE::LXC::Config;
27 use Time::HiRes qw (gettimeofday);
28
29 use Data::Dumper;
30
31 my $nodename = PVE::INotify::nodename();
32
33 my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
34
35 our $COMMON_TAR_FLAGS = [ '--sparse', '--numeric-owner', '--acls',
36 '--xattrs',
37 '--xattrs-include=user.*',
38 '--xattrs-include=security.capability',
39 '--warning=no-xattr-write' ];
40
41 sub config_list {
42 my $vmlist = PVE::Cluster::get_vmlist();
43 my $res = {};
44 return $res if !$vmlist || !$vmlist->{ids};
45 my $ids = $vmlist->{ids};
46
47 foreach my $vmid (keys %$ids) {
48 next if !$vmid; # skip CT0
49 my $d = $ids->{$vmid};
50 next if !$d->{node} || $d->{node} ne $nodename;
51 next if !$d->{type} || $d->{type} ne 'lxc';
52 $res->{$vmid}->{type} = 'lxc';
53 }
54 return $res;
55 }
56
57 sub destroy_config {
58 my ($vmid) = @_;
59
60 unlink PVE::LXC::Config->config_file($vmid, $nodename);
61 }
62
63 # container status helpers
64
65 sub list_active_containers {
66
67 my $filename = "/proc/net/unix";
68
69 # similar test is used by lcxcontainers.c: list_active_containers
70 my $res = {};
71
72 my $fh = IO::File->new ($filename, "r");
73 return $res if !$fh;
74
75 while (defined(my $line = <$fh>)) {
76 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
77 my $path = $1;
78 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
79 $res->{$1} = 1;
80 }
81 }
82 }
83
84 close($fh);
85
86 return $res;
87 }
88
89 # warning: this is slow
90 sub check_running {
91 my ($vmid) = @_;
92
93 my $active_hash = list_active_containers();
94
95 return 1 if defined($active_hash->{$vmid});
96
97 return undef;
98 }
99
100 sub get_container_disk_usage {
101 my ($vmid, $pid) = @_;
102
103 return PVE::Tools::df("/proc/$pid/root/", 1);
104 }
105
106 my $last_proc_vmid_stat;
107
108 my $parse_cpuacct_stat = sub {
109 my ($vmid) = @_;
110
111 my $raw = read_cgroup_value('cpuacct', $vmid, 'cpuacct.stat', 1);
112
113 my $stat = {};
114
115 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
116
117 $stat->{utime} = $1;
118 $stat->{stime} = $2;
119
120 }
121
122 return $stat;
123 };
124
125 sub vmstatus {
126 my ($opt_vmid) = @_;
127
128 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc' }} : config_list();
129
130 my $active_hash = list_active_containers();
131
132 my $cpucount = $cpuinfo->{cpus} || 1;
133
134 my $cdtime = gettimeofday;
135
136 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
137
138 foreach my $vmid (keys %$list) {
139 my $d = $list->{$vmid};
140
141 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
142 warn $@ if $@; # ignore errors (consider them stopped)
143
144 $d->{status} = $d->{pid} ? 'running' : 'stopped';
145
146 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
147 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
148
149 $d->{name} = $conf->{'hostname'} || "CT$vmid";
150 $d->{name} =~ s/[\s]//g;
151
152 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
153 $d->{cpus} = $cpucount if !$d->{cpus};
154
155 $d->{lock} = $conf->{lock} || '';
156
157 if ($d->{pid}) {
158 my $res = get_container_disk_usage($vmid, $d->{pid});
159 $d->{disk} = $res->{used};
160 $d->{maxdisk} = $res->{total};
161 } else {
162 $d->{disk} = 0;
163 # use 4GB by default ??
164 if (my $rootfs = $conf->{rootfs}) {
165 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($rootfs);
166 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
167 } else {
168 $d->{maxdisk} = 4*1024*1024*1024;
169 }
170 }
171
172 $d->{mem} = 0;
173 $d->{swap} = 0;
174 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
175 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
176
177 $d->{uptime} = 0;
178 $d->{cpu} = 0;
179
180 $d->{netout} = 0;
181 $d->{netin} = 0;
182
183 $d->{diskread} = 0;
184 $d->{diskwrite} = 0;
185
186 $d->{template} = PVE::LXC::Config->is_template($conf);
187 }
188
189 foreach my $vmid (keys %$list) {
190 my $d = $list->{$vmid};
191 my $pid = $d->{pid};
192
193 next if !$pid; # skip stopped CTs
194
195 my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
196 $d->{uptime} = time - $ctime; # the method lxcfs uses
197
198 my $memory_stat = read_cgroup_list('memory', $vmid, 'memory.stat');
199 my $mem_usage_in_bytes = read_cgroup_value('memory', $vmid, 'memory.usage_in_bytes');
200
201 $d->{mem} = $mem_usage_in_bytes - $memory_stat->{total_cache};
202 $d->{swap} = read_cgroup_value('memory', $vmid, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
203
204 my $blkio_bytes = read_cgroup_value('blkio', $vmid, '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';
210 }
211 }
212
213 my $pstat = &$parse_cpuacct_stat($vmid);
214
215 my $used = $pstat->{utime} + $pstat->{stime};
216
217 my $old = $last_proc_vmid_stat->{$vmid};
218 if (!$old) {
219 $last_proc_vmid_stat->{$vmid} = {
220 time => $cdtime,
221 used => $used,
222 cpu => 0,
223 };
224 next;
225 }
226
227 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
228
229 if ($dtime > 1000) {
230 my $dutime = $used - $old->{used};
231
232 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
233 $last_proc_vmid_stat->{$vmid} = {
234 time => $cdtime,
235 used => $used,
236 cpu => $d->{cpu},
237 };
238 } else {
239 $d->{cpu} = $old->{cpu};
240 }
241 }
242
243 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
244
245 foreach my $dev (keys %$netdev) {
246 next if $dev !~ m/^veth([1-9]\d*)i/;
247 my $vmid = $1;
248 my $d = $list->{$vmid};
249
250 next if !$d;
251
252 $d->{netout} += $netdev->{$dev}->{receive};
253 $d->{netin} += $netdev->{$dev}->{transmit};
254
255 }
256
257 return $list;
258 }
259
260 sub read_cgroup_list {
261 my ($group, $vmid, $name) = @_;
262
263 my $content = read_cgroup_value($group, $vmid, $name, 1);
264
265 return { split(/\s+/, $content) };
266 }
267
268 sub read_cgroup_value {
269 my ($group, $vmid, $name, $full) = @_;
270
271 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
272
273 return PVE::Tools::file_get_contents($path) if $full;
274
275 return PVE::Tools::file_read_firstline($path);
276 }
277
278 sub write_cgroup_value {
279 my ($group, $vmid, $name, $value) = @_;
280
281 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
282 PVE::ProcFSTools::write_proc_entry($path, $value) if -e $path;
283
284 }
285
286 sub find_lxc_console_pids {
287
288 my $res = {};
289
290 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
291 my ($pid) = @_;
292
293 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
294 return if !$cmdline;
295
296 my @args = split(/\0/, $cmdline);
297
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$|;
303
304 my $vmid = $args[2];
305
306 push @{$res->{$vmid}}, $pid;
307 });
308
309 return $res;
310 }
311
312 sub find_lxc_pid {
313 my ($vmid) = @_;
314
315 my $pid = undef;
316 my $parser = sub {
317 my $line = shift;
318 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
319 };
320 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
321
322 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
323
324 return $pid;
325 }
326
327 # Note: we cannot use Net:IP, because that only allows strict
328 # CIDR networks
329 sub parse_ipv4_cidr {
330 my ($cidr, $noerr) = @_;
331
332 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
333 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
334 }
335
336 return undef if $noerr;
337
338 die "unable to parse ipv4 address/mask\n";
339 }
340
341
342 sub update_lxc_config {
343 my ($vmid, $conf) = @_;
344
345 my $dir = "/var/lib/lxc/$vmid";
346
347 if ($conf->{template}) {
348
349 unlink "$dir/config";
350
351 return;
352 }
353
354 my $raw = '';
355
356 die "missing 'arch' - internal error" if !$conf->{arch};
357 $raw .= "lxc.arch = $conf->{arch}\n";
358
359 my $unprivileged = $conf->{unprivileged};
360 my $custom_idmap = grep { $_->[0] eq 'lxc.id_map' } @{$conf->{lxc}};
361
362 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
363 if ($ostype =~ /^(?:debian | ubuntu | centos | fedora | opensuse | archlinux | alpine | gentoo | unmanaged)$/x) {
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"
371 }
372 } else {
373 die "implement me (ostype $ostype)";
374 }
375
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";
382
383 # Should we read them from /etc/subuid?
384 if ($unprivileged && !$custom_idmap) {
385 $raw .= "lxc.id_map = u 0 100000 65536\n";
386 $raw .= "lxc.id_map = g 0 100000 65536\n";
387 }
388
389 if (!PVE::LXC::Config->has_dev_console($conf)) {
390 $raw .= "lxc.console = none\n";
391 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
392 }
393
394 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
395 $raw .= "lxc.tty = $ttycount\n";
396
397 # some init scripts expect a linux terminal (turnkey).
398 $raw .= "lxc.environment = TERM=linux\n";
399
400 my $utsname = $conf->{hostname} || "CT$vmid";
401 $raw .= "lxc.utsname = $utsname\n";
402
403 my $memory = $conf->{memory} || 512;
404 my $swap = $conf->{swap} // 0;
405
406 my $lxcmem = int($memory*1024*1024);
407 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
408
409 my $lxcswap = int(($memory + $swap)*1024*1024);
410 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
411
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";
416 }
417
418 my $shares = $conf->{cpuunits} || 1024;
419 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
420
421 die "missing 'rootfs' configuration\n"
422 if !defined($conf->{rootfs});
423
424 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
425
426 $raw .= "lxc.rootfs = $dir/rootfs\n";
427
428 my $netcount = 0;
429 foreach my $k (sort keys %$conf) {
430 next if $k !~ m/^net(\d+)$/;
431 my $ind = $1;
432 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
433 $netcount++;
434 $raw .= "lxc.network.type = veth\n";
435 $raw .= "lxc.network.veth.pair = veth${vmid}i${ind}\n";
436 $raw .= "lxc.network.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
437 $raw .= "lxc.network.name = $d->{name}\n" if defined($d->{name});
438 $raw .= "lxc.network.mtu = $d->{mtu}\n" if defined($d->{mtu});
439 }
440
441 my $had_cpuset = 0;
442 if (my $lxcconf = $conf->{lxc}) {
443 foreach my $entry (@$lxcconf) {
444 my ($k, $v) = @$entry;
445 $netcount++ if $k eq 'lxc.network.type';
446 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
447 $raw .= "$k = $v\n";
448 }
449 }
450
451 $raw .= "lxc.network.type = empty\n" if !$netcount;
452
453 my $cores = $conf->{cores};
454 if (!$had_cpuset && $cores) {
455 my $cpuset = eval { PVE::CpuSet->new_from_cgroup('lxc', 'effective_cpus') };
456 $cpuset = PVE::CpuSet->new_from_cgroup('', 'effective_cpus') if !$cpuset;
457 my @members = $cpuset->members();
458 while (scalar(@members) > $cores) {
459 my $randidx = int(rand(scalar(@members)));
460 $cpuset->delete($members[$randidx]);
461 splice(@members, $randidx, 1); # keep track of the changes
462 }
463 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
464 }
465
466 File::Path::mkpath("$dir/rootfs");
467
468 PVE::Tools::file_set_contents("$dir/config", $raw);
469 }
470
471 # verify and cleanup nameserver list (replace \0 with ' ')
472 sub verify_nameserver_list {
473 my ($nameserver_list) = @_;
474
475 my @list = ();
476 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
477 PVE::JSONSchema::pve_verify_ip($server);
478 push @list, $server;
479 }
480
481 return join(' ', @list);
482 }
483
484 sub verify_searchdomain_list {
485 my ($searchdomain_list) = @_;
486
487 my @list = ();
488 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
489 # todo: should we add checks for valid dns domains?
490 push @list, $server;
491 }
492
493 return join(' ', @list);
494 }
495
496 sub get_console_command {
497 my ($vmid, $conf) = @_;
498
499 my $cmode = PVE::LXC::Config->get_cmode($conf);
500
501 if ($cmode eq 'console') {
502 return ['lxc-console', '-n', $vmid, '-t', 0];
503 } elsif ($cmode eq 'tty') {
504 return ['lxc-console', '-n', $vmid];
505 } elsif ($cmode eq 'shell') {
506 return ['lxc-attach', '--clear-env', '-n', $vmid];
507 } else {
508 die "internal error";
509 }
510 }
511
512 sub get_primary_ips {
513 my ($conf) = @_;
514
515 # return data from net0
516
517 return undef if !defined($conf->{net0});
518 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
519
520 my $ipv4 = $net->{ip};
521 if ($ipv4) {
522 if ($ipv4 =~ /^(dhcp|manual)$/) {
523 $ipv4 = undef
524 } else {
525 $ipv4 =~ s!/\d+$!!;
526 }
527 }
528 my $ipv6 = $net->{ip6};
529 if ($ipv6) {
530 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
531 $ipv6 = undef;
532 } else {
533 $ipv6 =~ s!/\d+$!!;
534 }
535 }
536
537 return ($ipv4, $ipv6);
538 }
539
540 sub delete_mountpoint_volume {
541 my ($storage_cfg, $vmid, $volume) = @_;
542
543 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
544
545 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
546 PVE::Storage::vdisk_free($storage_cfg, $volume) if $vmid == $owner;
547 }
548
549 sub destroy_lxc_container {
550 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
551
552 PVE::LXC::Config->foreach_mountpoint($conf, sub {
553 my ($ms, $mountpoint) = @_;
554 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
555 });
556
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);
562 } else {
563 destroy_config($vmid);
564 }
565
566 #my $cmd = ['lxc-destroy', '-n', $vmid ];
567 #PVE::Tools::run_command($cmd);
568 }
569
570 sub vm_stop_cleanup {
571 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
572
573 eval {
574 if (!$keepActive) {
575
576 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
577 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
578 }
579 };
580 warn $@ if $@; # avoid errors - just warn
581 }
582
583 my $safe_num_ne = sub {
584 my ($a, $b) = @_;
585
586 return 0 if !defined($a) && !defined($b);
587 return 1 if !defined($a);
588 return 1 if !defined($b);
589
590 return $a != $b;
591 };
592
593 my $safe_string_ne = sub {
594 my ($a, $b) = @_;
595
596 return 0 if !defined($a) && !defined($b);
597 return 1 if !defined($a);
598 return 1 if !defined($b);
599
600 return $a ne $b;
601 };
602
603 sub update_net {
604 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
605
606 if ($newnet->{type} ne 'veth') {
607 # for when there are physical interfaces
608 die "cannot update interface of type $newnet->{type}";
609 }
610
611 my $veth = "veth${vmid}i${netid}";
612 my $eth = $newnet->{name};
613
614 if (my $oldnetcfg = $conf->{$opt}) {
615 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
616
617 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
618 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
619
620 PVE::Network::veth_delete($veth);
621 delete $conf->{$opt};
622 PVE::LXC::Config->write_config($vmid, $conf);
623
624 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
625
626 } else {
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})) {
630
631 if ($oldnet->{bridge}) {
632 PVE::Network::tap_unplug($veth);
633 foreach (qw(bridge tag firewall)) {
634 delete $oldnet->{$_};
635 }
636 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
637 PVE::LXC::Config->write_config($vmid, $conf);
638 }
639
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->{$_};
644 }
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}
650 }
651 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
652 PVE::LXC::Config->write_config($vmid, $conf);
653 }
654 } else {
655 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
656 }
657
658 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
659 }
660
661 sub hotplug_net {
662 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
663
664 my $veth = "veth${vmid}i${netid}";
665 my $vethpeer = $veth . "p";
666 my $eth = $newnet->{name};
667
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});
670
671 # attach peer in container
672 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
673 PVE::Tools::run_command($cmd);
674
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);
678
679 my $done = { type => 'veth' };
680 foreach (qw(bridge tag firewall hwaddr name)) {
681 $done->{$_} = $newnet->{$_} if $newnet->{$_};
682 }
683 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
684
685 PVE::LXC::Config->write_config($vmid, $conf);
686 }
687
688 sub update_ipconfig {
689 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
690
691 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
692
693 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
694 my $deleted = [];
695 my $added = [];
696 my $nscmd = sub {
697 my $cmdargs = shift;
698 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
699 };
700 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
701
702 my $change_ip_config = sub {
703 my ($ipversion) = @_;
704
705 my $family_opt = "-$ipversion";
706 my $suffix = $ipversion == 4 ? '' : $ipversion;
707 my $gw= "gw$suffix";
708 my $ip= "ip$suffix";
709
710 my $newip = $newnet->{$ip};
711 my $newgw = $newnet->{$gw};
712 my $oldip = $optdata->{$ip};
713
714 my $change_ip = &$safe_string_ne($oldip, $newip);
715 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
716
717 return if !$change_ip && !$change_gw;
718
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); };
723 if (my $err = $@) {
724 warn $err;
725 return;
726 }
727 }
728
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
734 if ($change_gw) {
735 if ($newgw) {
736 eval {
737 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
738 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
739 }
740 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
741 };
742 if (my $err = $@) {
743 warn $err;
744 # the route was not replaced, the old IP is still available
745 # rollback (delete new IP) and cancel
746 if ($change_ip) {
747 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
748 warn $@ if $@; # no need to die here
749 }
750 return;
751 }
752 } else {
753 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
754 # if the route was not deleted, the guest might have deleted it manually
755 # warn and continue
756 warn $@ if $@;
757 }
758 }
759
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.
765 my $promote = 0;
766 eval {
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");
771 }
772 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
773 };
774 warn $@ if $@; # no need to die here
775
776 if ($ipversion == 4) {
777 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
778 }
779 }
780
781 foreach my $property ($ip, $gw) {
782 if ($newnet->{$property}) {
783 $optdata->{$property} = $newnet->{$property};
784 } else {
785 delete $optdata->{$property};
786 }
787 }
788 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
789 PVE::LXC::Config->write_config($vmid, $conf);
790 $lxc_setup->setup_network($conf);
791 };
792
793 &$change_ip_config(4);
794 &$change_ip_config(6);
795
796 }
797
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";
804 close $fd;
805 };
806
807 my $do_syncfs = sub {
808 my ($vmid, $pid, $socket) = @_;
809
810 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
811
812 # Tell the parent process to start reading our /proc/mounts
813 print {$socket} "go\n";
814 $socket->flush();
815
816 # Receive /proc/self/mounts
817 my $mountdata = do { local $/ = undef; <$socket> };
818 close $socket;
819
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); };
826 warn $@ if $@;
827 }
828 };
829
830 sub sync_container_namespace {
831 my ($vmid) = @_;
832 my $pid = find_lxc_pid($vmid);
833
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";
837
838 my $child = fork();
839 die "fork failed: $!\n" if !defined($child);
840
841 if (!$child) {
842 eval {
843 close $pfd;
844 &$do_syncfs($vmid, $pid, $cfd);
845 };
846 if (my $err = $@) {
847 warn $err;
848 POSIX::_exit(1);
849 }
850 POSIX::_exit(0);
851 }
852 close $cfd;
853 my $go = <$pfd>;
854 die "failed to enter container namespace\n" if $go ne "go\n";
855
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> };
859 close $mounts;
860 print {$pfd} $mountdata;
861 close $pfd;
862
863 while (waitpid($child, 0) != $child) {}
864 die "failed to sync container namespace\n" if $? != 0;
865 }
866
867 sub template_create {
868 my ($vmid, $conf) = @_;
869
870 my $storecfg = PVE::Storage::config();
871
872 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
873 my $volid = $rootinfo->{volume};
874
875 die "Template feature is not available for '$volid'\n"
876 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
877
878 PVE::Storage::activate_volumes($storecfg, [$volid]);
879
880 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
881 $rootinfo->{volume} = $template_volid;
882 $conf->{rootfs} = PVE::LXC::Config->print_ct_mountpoint($rootinfo, 1);
883
884 PVE::LXC::Config->write_config($vmid, $conf);
885 }
886
887 sub check_ct_modify_config_perm {
888 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
889
890 return 1 if $authuser eq 'root@pam';
891
892 my $check = sub {
893 my ($opt, $delete) = @_;
894 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
895 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
896 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
897 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
898 return if $delete;
899 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
900 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
901 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
902 if $data->{type} ne 'volume';
903 } elsif ($opt eq 'memory' || $opt eq 'swap') {
904 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
905 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
906 $opt eq 'searchdomain' || $opt eq 'hostname') {
907 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
908 } else {
909 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
910 }
911 };
912
913 foreach my $opt (keys %$newconf) {
914 &$check($opt, 0);
915 }
916 foreach my $opt (@$delete) {
917 &$check($opt, 1);
918 }
919
920 return 1;
921 }
922
923 sub umount_all {
924 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
925
926 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
927 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
928
929 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
930 my ($ms, $mountpoint) = @_;
931
932 my $volid = $mountpoint->{volume};
933 my $mount = $mountpoint->{mp};
934
935 return if !$volid || !$mount;
936
937 my $mount_path = "$rootdir/$mount";
938 $mount_path =~ s!/+!/!g;
939
940 return if !PVE::ProcFSTools::is_mounted($mount_path);
941
942 eval {
943 PVE::Tools::run_command(['umount', '-d', $mount_path]);
944 };
945 if (my $err = $@) {
946 if ($noerr) {
947 warn $err;
948 } else {
949 die $err;
950 }
951 }
952 });
953 }
954
955 sub mount_all {
956 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
957
958 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
959 File::Path::make_path($rootdir);
960
961 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
962 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
963
964 eval {
965 PVE::LXC::Config->foreach_mountpoint($conf, sub {
966 my ($ms, $mountpoint) = @_;
967
968 $mountpoint->{ro} = 0 if $ignore_ro;
969
970 mountpoint_mount($mountpoint, $rootdir, $storage_cfg);
971 });
972 };
973 if (my $err = $@) {
974 warn "mounting container failed\n";
975 umount_all($vmid, $storage_cfg, $conf, 1);
976 die $err;
977 }
978
979 return $rootdir;
980 }
981
982
983 sub mountpoint_mount_path {
984 my ($mountpoint, $storage_cfg, $snapname) = @_;
985
986 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
987 }
988
989 sub query_loopdev {
990 my ($path) = @_;
991 my $found;
992 my $parser = sub {
993 my $line = shift;
994 if ($line =~ m@^(/dev/loop\d+):@) {
995 $found = $1;
996 }
997 };
998 my $cmd = ['losetup', '--associated', $path];
999 PVE::Tools::run_command($cmd, outfunc => $parser);
1000 return $found;
1001 }
1002
1003 # Run a function with a file attached to a loop device.
1004 # The loop device is always detached afterwards (or set to autoclear).
1005 # Returns the loop device.
1006 sub run_with_loopdev {
1007 my ($func, $file) = @_;
1008 my $device = query_loopdev($file);
1009 # Try to reuse an existing device
1010 if ($device) {
1011 # We assume that whoever setup the loop device is responsible for
1012 # detaching it.
1013 &$func($device);
1014 return $device;
1015 }
1016
1017 my $parser = sub {
1018 my $line = shift;
1019 if ($line =~ m@^(/dev/loop\d+)$@) {
1020 $device = $1;
1021 }
1022 };
1023 PVE::Tools::run_command(['losetup', '--show', '-f', $file], outfunc => $parser);
1024 die "failed to setup loop device for $file\n" if !$device;
1025 eval { &$func($device); };
1026 my $err = $@;
1027 PVE::Tools::run_command(['losetup', '-d', $device]);
1028 die $err if $err;
1029 return $device;
1030 }
1031
1032 # In scalar mode: returns a file handle to the deepest directory node.
1033 # In list context: returns a list of:
1034 # * the deepest directory node
1035 # * the 2nd deepest directory (parent of the above)
1036 # * directory name of the last directory
1037 # So that the path $2/$3 should lead to $1 afterwards.
1038 sub walk_tree_nofollow($$$) {
1039 my ($start, $subdir, $mkdir) = @_;
1040
1041 # splitdir() returns '' for empty components including the leading /
1042 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1043
1044 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1045 or die "failed to open start directory $start: $!\n";
1046
1047 my $dir = $start;
1048 my $last_component = undef;
1049 my $second = $fd;
1050 foreach my $component (@comps) {
1051 $dir .= "/$component";
1052 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1053
1054 if (!$next) {
1055 # failed, check for symlinks and try to create the path
1056 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
1057 die "cannot open directory $dir: $!\n" if !$mkdir;
1058
1059 # We don't check for errors on mkdirat() here and just try to
1060 # openat() again, since at least one error (EEXIST) is an
1061 # expected possibility if multiple containers start
1062 # simultaneously. If someone else injects a symlink now then
1063 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1064 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1065
1066 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1067 die "failed to create path: $dir: $!\n" if !$next;
1068 }
1069
1070 close $second if defined($last_component);
1071 $last_component = $component;
1072 $second = $fd;
1073 $fd = $next;
1074 }
1075
1076 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1077 close $second if defined($last_component);
1078 return $fd;
1079 }
1080
1081 # To guard against symlink attack races against other currently running
1082 # containers with shared recursive bind mount hierarchies we prepare a
1083 # directory handle for the directory we're mounting over to verify the
1084 # mountpoint afterwards.
1085 sub __bindmount_prepare {
1086 my ($hostroot, $dir) = @_;
1087 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1088 return $srcdh;
1089 }
1090
1091 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1092 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1093 # we intended to bind mount.
1094 sub __bindmount_verify {
1095 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1096 my $destdh;
1097 if ($parentfd) {
1098 # Open the mount point path coming from the parent directory since the
1099 # filehandle we would have gotten as first result of walk_tree_nofollow
1100 # earlier is still a handle to the underlying directory instead of the
1101 # mounted path.
1102 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1103 die "failed to open mount point: $!\n" if !$destdh;
1104 if ($ro) {
1105 my $dot = '.';
1106 # no separate function because 99% of the time it's the wrong thing to use.
1107 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
1108 die "failed to mark bind mount read only\n";
1109 }
1110 die "read-only check failed: $!\n" if $! != EROFS;
1111 }
1112 } else {
1113 # For the rootfs we don't have a parentfd so we open the path directly.
1114 # Note that this means bindmounting any prefix of the host's
1115 # /var/lib/lxc/$vmid path into another container is considered a grave
1116 # security error.
1117 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
1118 die "failed to open mount point: $!\n" if !$destdh;
1119 }
1120
1121 my ($srcdev, $srcinode) = stat($srcdh);
1122 my ($dstdev, $dstinode) = stat($destdh);
1123 close $srcdh;
1124 close $destdh;
1125
1126 return ($srcdev == $dstdev && $srcinode == $dstinode);
1127 }
1128
1129 # Perform the actual bind mounting:
1130 sub __bindmount_do {
1131 my ($dir, $dest, $ro, @extra_opts) = @_;
1132 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1133 if ($ro) {
1134 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1135 if (my $err = $@) {
1136 warn "bindmount error\n";
1137 # don't leave writable bind-mounts behind...
1138 PVE::Tools::run_command(['umount', $dest]);
1139 die $err;
1140 }
1141 }
1142 }
1143
1144 sub bindmount {
1145 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1146
1147 my $srcdh = __bindmount_prepare('/', $dir);
1148
1149 __bindmount_do($dir, $dest, $ro, @extra_opts);
1150
1151 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
1152 PVE::Tools::run_command(['umount', $dest]);
1153 die "detected mount path change at: $dir\n";
1154 }
1155 }
1156
1157 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1158 # from $rootdir and $mount and walk the path from $rootdir to the final
1159 # directory to check for symlinks.
1160 sub __mount_prepare_rootdir {
1161 my ($rootdir, $mount) = @_;
1162 $rootdir =~ s!/+!/!g;
1163 $rootdir =~ s!/+$!!;
1164 my $mount_path = "$rootdir/$mount";
1165 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1);
1166 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1167 }
1168
1169 # use $rootdir = undef to just return the corresponding mount path
1170 sub mountpoint_mount {
1171 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1172
1173 my $volid = $mountpoint->{volume};
1174 my $mount = $mountpoint->{mp};
1175 my $type = $mountpoint->{type};
1176 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1177 my $mounted_dev;
1178
1179 return if !$volid || !$mount;
1180
1181 $mount =~ s!/+!/!g;
1182
1183 my $mount_path;
1184 my ($mpfd, $parentfd, $last_dir);
1185
1186 if (defined($rootdir)) {
1187 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1188 __mount_prepare_rootdir($rootdir, $mount);
1189 }
1190
1191 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1192
1193 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1194
1195 my $optstring = '';
1196 my $acl = $mountpoint->{acl};
1197 if (defined($acl)) {
1198 $optstring .= ($acl ? 'acl' : 'noacl');
1199 }
1200 my $readonly = $mountpoint->{ro};
1201
1202 my @extra_opts = ('-o', $optstring) if $optstring;
1203
1204 if ($storage) {
1205
1206 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1207
1208 # early sanity checks:
1209 # we otherwise call realpath on the rbd url
1210 die "containers on rbd storage without krbd are not supported\n"
1211 if $scfg->{type} eq 'rbd' && !$scfg->{krbd};
1212
1213 my $path = PVE::Storage::path($storage_cfg, $volid, $snapname);
1214
1215 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1216 PVE::Storage::parse_volname($storage_cfg, $volid);
1217
1218 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1219
1220 if ($format eq 'subvol') {
1221 if ($mount_path) {
1222 if ($snapname) {
1223 if ($scfg->{type} eq 'zfspool') {
1224 my $path_arg = $path;
1225 $path_arg =~ s!^/+!!;
1226 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1227 } else {
1228 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1229 }
1230 } else {
1231 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1232 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1233 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1234 $name .= "\@$snapname" if defined($snapname);
1235 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1236 }
1237 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1238 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1239 }
1240 }
1241 return wantarray ? ($path, 0, undef) : $path;
1242 } elsif ($format eq 'raw' || $format eq 'iso') {
1243 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1244 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1245 # Our autodev hook expects the /dev/dm-* device currently
1246 # and will create the /dev/mapper symlink accordingly
1247 $path = Cwd::realpath($path);
1248 die "failed to get device path\n" if !$path;
1249 ($path) = ($path =~ /^(.*)$/s); #untaint
1250 my $domount = sub {
1251 my ($path) = @_;
1252 if ($mount_path) {
1253 if ($format eq 'iso') {
1254 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1255 } elsif ($isBase || defined($snapname)) {
1256 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1257 } else {
1258 if ($quota) {
1259 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1260 }
1261 push @extra_opts, '-o', 'ro' if $readonly;
1262 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1263 }
1264 }
1265 };
1266 my $use_loopdev = 0;
1267 if ($scfg->{path}) {
1268 $mounted_dev = run_with_loopdev($domount, $path);
1269 $use_loopdev = 1;
1270 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1271 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
1272 $mounted_dev = $path;
1273 &$domount($path);
1274 } else {
1275 die "unsupported storage type '$scfg->{type}'\n";
1276 }
1277 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
1278 } else {
1279 die "unsupported image format '$format'\n";
1280 }
1281 } elsif ($type eq 'device') {
1282 push @extra_opts, '-o', 'ro' if $readonly;
1283 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1284 # See the NOTE above about devicemapper canonicalization
1285 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
1286 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1287 return wantarray ? ($volid, 0, $devpath) : $volid;
1288 } elsif ($type eq 'bind') {
1289 die "directory '$volid' does not exist\n" if ! -d $volid;
1290 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1291 warn "cannot enable quota control for bind mounts\n" if $quota;
1292 return wantarray ? ($volid, 0, undef) : $volid;
1293 }
1294
1295 die "unsupported storage";
1296 }
1297
1298 sub mkfs {
1299 my ($dev, $rootuid, $rootgid) = @_;
1300
1301 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1302 '-E', "root_owner=$rootuid:$rootgid",
1303 $dev]);
1304 }
1305
1306 sub format_disk {
1307 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1308
1309 if ($volid =~ m!^/dev/.+!) {
1310 mkfs($volid);
1311 return;
1312 }
1313
1314 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1315
1316 die "cannot format volume '$volid' with no storage\n" if !$storage;
1317
1318 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1319
1320 my $path = PVE::Storage::path($storage_cfg, $volid);
1321
1322 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1323 PVE::Storage::parse_volname($storage_cfg, $volid);
1324
1325 die "cannot format volume '$volid' (format == $format)\n"
1326 if $format ne 'raw';
1327
1328 mkfs($path, $rootuid, $rootgid);
1329 }
1330
1331 sub destroy_disks {
1332 my ($storecfg, $vollist) = @_;
1333
1334 foreach my $volid (@$vollist) {
1335 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1336 warn $@ if $@;
1337 }
1338 }
1339
1340 sub create_disks {
1341 my ($storecfg, $vmid, $settings, $conf) = @_;
1342
1343 my $vollist = [];
1344
1345 eval {
1346 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1347 my $chown_vollist = [];
1348
1349 PVE::LXC::Config->foreach_mountpoint($settings, sub {
1350 my ($ms, $mountpoint) = @_;
1351
1352 my $volid = $mountpoint->{volume};
1353 my $mp = $mountpoint->{mp};
1354
1355 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1356
1357 if ($storage && ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/)) {
1358 my ($storeid, $size_gb) = ($1, $2);
1359
1360 my $size_kb = int(${size_gb}*1024) * 1024;
1361
1362 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1363 # fixme: use better naming ct-$vmid-disk-X.raw?
1364
1365 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
1366 if ($size_kb > 0) {
1367 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1368 undef, $size_kb);
1369 format_disk($storecfg, $volid, $rootuid, $rootgid);
1370 } else {
1371 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1372 undef, 0);
1373 push @$chown_vollist, $volid;
1374 }
1375 } elsif ($scfg->{type} eq 'zfspool') {
1376
1377 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1378 undef, $size_kb);
1379 push @$chown_vollist, $volid;
1380 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1381
1382 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1383 format_disk($storecfg, $volid, $rootuid, $rootgid);
1384
1385 } elsif ($scfg->{type} eq 'rbd') {
1386
1387 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd};
1388 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1389 format_disk($storecfg, $volid, $rootuid, $rootgid);
1390 } else {
1391 die "unable to create containers on storage type '$scfg->{type}'\n";
1392 }
1393 push @$vollist, $volid;
1394 $mountpoint->{volume} = $volid;
1395 $mountpoint->{size} = $size_kb * 1024;
1396 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1397 } else {
1398 # use specified/existing volid/dir/device
1399 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1400 }
1401 });
1402
1403 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1404 foreach my $volid (@$chown_vollist) {
1405 my $path = PVE::Storage::path($storecfg, $volid, undef);
1406 chown($rootuid, $rootgid, $path);
1407 }
1408 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
1409 };
1410 # free allocated images on error
1411 if (my $err = $@) {
1412 destroy_disks($storecfg, $vollist);
1413 die $err;
1414 }
1415 return $vollist;
1416 }
1417
1418 # bash completion helper
1419
1420 sub complete_os_templates {
1421 my ($cmdname, $pname, $cvalue) = @_;
1422
1423 my $cfg = PVE::Storage::config();
1424
1425 my $storeid;
1426
1427 if ($cvalue =~ m/^([^:]+):/) {
1428 $storeid = $1;
1429 }
1430
1431 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1432 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1433
1434 my $res = [];
1435 foreach my $id (keys %$data) {
1436 foreach my $item (@{$data->{$id}}) {
1437 push @$res, $item->{volid} if defined($item->{volid});
1438 }
1439 }
1440
1441 return $res;
1442 }
1443
1444 my $complete_ctid_full = sub {
1445 my ($running) = @_;
1446
1447 my $idlist = vmstatus();
1448
1449 my $active_hash = list_active_containers();
1450
1451 my $res = [];
1452
1453 foreach my $id (keys %$idlist) {
1454 my $d = $idlist->{$id};
1455 if (defined($running)) {
1456 next if $d->{template};
1457 next if $running && !$active_hash->{$id};
1458 next if !$running && $active_hash->{$id};
1459 }
1460 push @$res, $id;
1461
1462 }
1463 return $res;
1464 };
1465
1466 sub complete_ctid {
1467 return &$complete_ctid_full();
1468 }
1469
1470 sub complete_ctid_stopped {
1471 return &$complete_ctid_full(0);
1472 }
1473
1474 sub complete_ctid_running {
1475 return &$complete_ctid_full(1);
1476 }
1477
1478 sub parse_id_maps {
1479 my ($conf) = @_;
1480
1481 my $id_map = [];
1482 my $rootuid = 0;
1483 my $rootgid = 0;
1484
1485 my $lxc = $conf->{lxc};
1486 foreach my $entry (@$lxc) {
1487 my ($key, $value) = @$entry;
1488 next if $key ne 'lxc.id_map';
1489 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1490 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1491 push @$id_map, [$type, $ct, $host, $length];
1492 if ($ct == 0) {
1493 $rootuid = $host if $type eq 'u';
1494 $rootgid = $host if $type eq 'g';
1495 }
1496 } else {
1497 die "failed to parse id_map: $value\n";
1498 }
1499 }
1500
1501 if (!@$id_map && $conf->{unprivileged}) {
1502 # Should we read them from /etc/subuid?
1503 $id_map = [ ['u', '0', '100000', '65536'],
1504 ['g', '0', '100000', '65536'] ];
1505 $rootuid = $rootgid = 100000;
1506 }
1507
1508 return ($id_map, $rootuid, $rootgid);
1509 }
1510
1511 sub userns_command {
1512 my ($id_map) = @_;
1513 if (@$id_map) {
1514 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1515 }
1516 return [];
1517 }
1518
1519
1520 1;