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