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