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