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