]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC.pm
0b57ae9f32ccf275e64cd85621dc02f62bce5f3c
[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 my $oldgw = $optdata->{$gw};
795
796 my $change_ip = &$safe_string_ne($oldip, $newip);
797 my $change_gw = &$safe_string_ne($oldgw, $newgw);
798
799 return if !$change_ip && !$change_gw;
800
801 # step 1: add new IP, if this fails we cancel
802 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
803 if ($change_ip && $is_real_ip) {
804 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
805 if (my $err = $@) {
806 warn $err;
807 return;
808 }
809 }
810
811 # step 2: replace gateway
812 # If this fails we delete the added IP and cancel.
813 # If it succeeds we save the config and delete the old IP, ignoring
814 # errors. The config is then saved.
815 # Note: 'ip route replace' can add
816 if ($change_gw) {
817 if ($newgw) {
818 eval {
819 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
820 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
821 }
822 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
823 };
824 if (my $err = $@) {
825 warn $err;
826 # the route was not replaced, the old IP is still available
827 # rollback (delete new IP) and cancel
828 if ($change_ip) {
829 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
830 warn $@ if $@; # no need to die here
831 }
832 return;
833 }
834 } else {
835 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
836 # if the route was not deleted, the guest might have deleted it manually
837 # warn and continue
838 warn $@ if $@;
839 }
840 if ($oldgw && $oldip && !PVE::Network::is_ip_in_cidr($oldgw, $oldip)) {
841 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
842 # warn if the route was deleted manually
843 warn $@ if $@;
844 }
845 }
846
847 # from this point on we save the configuration
848 # step 3: delete old IP ignoring errors
849 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
850 # We need to enable promote_secondaries, otherwise our newly added
851 # address will be removed along with the old one.
852 my $promote = 0;
853 eval {
854 if ($ipversion == 4) {
855 &$nscmd({ outfunc => sub { $promote = int(shift) } },
856 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
857 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
858 }
859 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
860 };
861 warn $@ if $@; # no need to die here
862
863 if ($ipversion == 4) {
864 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
865 }
866 }
867
868 foreach my $property ($ip, $gw) {
869 if ($newnet->{$property}) {
870 $optdata->{$property} = $newnet->{$property};
871 } else {
872 delete $optdata->{$property};
873 }
874 }
875 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
876 PVE::LXC::Config->write_config($vmid, $conf);
877 $lxc_setup->setup_network($conf);
878 };
879
880 &$change_ip_config(4);
881 &$change_ip_config(6);
882
883 }
884
885 my $enter_namespace = sub {
886 my ($vmid, $pid, $which, $type) = @_;
887 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
888 or die "failed to open $which namespace of container $vmid: $!\n";
889 PVE::Tools::setns(fileno($fd), $type)
890 or die "failed to enter $which namespace of container $vmid: $!\n";
891 close $fd;
892 };
893
894 my $do_syncfs = sub {
895 my ($vmid, $pid, $socket) = @_;
896
897 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
898
899 # Tell the parent process to start reading our /proc/mounts
900 print {$socket} "go\n";
901 $socket->flush();
902
903 # Receive /proc/self/mounts
904 my $mountdata = do { local $/ = undef; <$socket> };
905 close $socket;
906
907 # Now sync all mountpoints...
908 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
909 foreach my $mp (@$mounts) {
910 my ($what, $dir, $fs) = @$mp;
911 next if $fs eq 'fuse.lxcfs';
912 eval { PVE::Tools::sync_mountpoint($dir); };
913 warn $@ if $@;
914 }
915 };
916
917 sub sync_container_namespace {
918 my ($vmid) = @_;
919 my $pid = find_lxc_pid($vmid);
920
921 # SOCK_DGRAM is nicer for barriers but cannot be slurped
922 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
923 or die "failed to create socketpair: $!\n";
924
925 my $child = fork();
926 die "fork failed: $!\n" if !defined($child);
927
928 if (!$child) {
929 eval {
930 close $pfd;
931 &$do_syncfs($vmid, $pid, $cfd);
932 };
933 if (my $err = $@) {
934 warn $err;
935 POSIX::_exit(1);
936 }
937 POSIX::_exit(0);
938 }
939 close $cfd;
940 my $go = <$pfd>;
941 die "failed to enter container namespace\n" if $go ne "go\n";
942
943 open my $mounts, '<', "/proc/$child/mounts"
944 or die "failed to open container's /proc/mounts: $!\n";
945 my $mountdata = do { local $/ = undef; <$mounts> };
946 close $mounts;
947 print {$pfd} $mountdata;
948 close $pfd;
949
950 while (waitpid($child, 0) != $child) {}
951 die "failed to sync container namespace\n" if $? != 0;
952 }
953
954 sub template_create {
955 my ($vmid, $conf) = @_;
956
957 my $storecfg = PVE::Storage::config();
958
959 PVE::LXC::Config->foreach_mountpoint($conf, sub {
960 my ($ms, $mountpoint) = @_;
961
962 my $volid = $mountpoint->{volume};
963
964 die "Template feature is not available for '$volid'\n"
965 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
966 });
967
968 PVE::LXC::Config->foreach_mountpoint($conf, sub {
969 my ($ms, $mountpoint) = @_;
970
971 my $volid = $mountpoint->{volume};
972
973 PVE::Storage::activate_volumes($storecfg, [$volid]);
974
975 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
976 $mountpoint->{volume} = $template_volid;
977 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq "rootfs");
978 });
979
980 PVE::LXC::Config->write_config($vmid, $conf);
981 }
982
983 sub check_ct_modify_config_perm {
984 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
985
986 return 1 if $authuser eq 'root@pam';
987
988 my $check = sub {
989 my ($opt, $delete) = @_;
990 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
991 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
992 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
993 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
994 return if $delete;
995 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
996 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
997 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
998 if $data->{type} ne 'volume';
999 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1000 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1001 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1002 $opt eq 'searchdomain' || $opt eq 'hostname') {
1003 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1004 } else {
1005 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1006 }
1007 };
1008
1009 foreach my $opt (keys %$newconf) {
1010 &$check($opt, 0);
1011 }
1012 foreach my $opt (@$delete) {
1013 &$check($opt, 1);
1014 }
1015
1016 return 1;
1017 }
1018
1019 sub umount_all {
1020 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1021
1022 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1023 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1024
1025 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
1026 my ($ms, $mountpoint) = @_;
1027
1028 my $volid = $mountpoint->{volume};
1029 my $mount = $mountpoint->{mp};
1030
1031 return if !$volid || !$mount;
1032
1033 my $mount_path = "$rootdir/$mount";
1034 $mount_path =~ s!/+!/!g;
1035
1036 return if !PVE::ProcFSTools::is_mounted($mount_path);
1037
1038 eval {
1039 PVE::Tools::run_command(['umount', '-d', $mount_path]);
1040 };
1041 if (my $err = $@) {
1042 if ($noerr) {
1043 warn $err;
1044 } else {
1045 die $err;
1046 }
1047 }
1048 });
1049 }
1050
1051 sub mount_all {
1052 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1053
1054 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1055 File::Path::make_path($rootdir);
1056
1057 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1058 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
1059
1060 eval {
1061 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1062 my ($ms, $mountpoint) = @_;
1063
1064 $mountpoint->{ro} = 0 if $ignore_ro;
1065
1066 mountpoint_mount($mountpoint, $rootdir, $storage_cfg);
1067 });
1068 };
1069 if (my $err = $@) {
1070 warn "mounting container failed\n";
1071 umount_all($vmid, $storage_cfg, $conf, 1);
1072 die $err;
1073 }
1074
1075 return $rootdir;
1076 }
1077
1078
1079 sub mountpoint_mount_path {
1080 my ($mountpoint, $storage_cfg, $snapname) = @_;
1081
1082 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
1083 }
1084
1085 sub query_loopdev {
1086 my ($path) = @_;
1087 my $found;
1088 my $parser = sub {
1089 my $line = shift;
1090 if ($line =~ m@^(/dev/loop\d+):@) {
1091 $found = $1;
1092 }
1093 };
1094 my $cmd = ['losetup', '--associated', $path];
1095 PVE::Tools::run_command($cmd, outfunc => $parser);
1096 return $found;
1097 }
1098
1099 # Run a function with a file attached to a loop device.
1100 # The loop device is always detached afterwards (or set to autoclear).
1101 # Returns the loop device.
1102 sub run_with_loopdev {
1103 my ($func, $file) = @_;
1104 my $device = query_loopdev($file);
1105 # Try to reuse an existing device
1106 if ($device) {
1107 # We assume that whoever setup the loop device is responsible for
1108 # detaching it.
1109 &$func($device);
1110 return $device;
1111 }
1112
1113 my $parser = sub {
1114 my $line = shift;
1115 if ($line =~ m@^(/dev/loop\d+)$@) {
1116 $device = $1;
1117 }
1118 };
1119 PVE::Tools::run_command(['losetup', '--show', '-f', $file], outfunc => $parser);
1120 die "failed to setup loop device for $file\n" if !$device;
1121 eval { &$func($device); };
1122 my $err = $@;
1123 PVE::Tools::run_command(['losetup', '-d', $device]);
1124 die $err if $err;
1125 return $device;
1126 }
1127
1128 # In scalar mode: returns a file handle to the deepest directory node.
1129 # In list context: returns a list of:
1130 # * the deepest directory node
1131 # * the 2nd deepest directory (parent of the above)
1132 # * directory name of the last directory
1133 # So that the path $2/$3 should lead to $1 afterwards.
1134 sub walk_tree_nofollow($$$) {
1135 my ($start, $subdir, $mkdir) = @_;
1136
1137 # splitdir() returns '' for empty components including the leading /
1138 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1139
1140 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1141 or die "failed to open start directory $start: $!\n";
1142
1143 my $dir = $start;
1144 my $last_component = undef;
1145 my $second = $fd;
1146 foreach my $component (@comps) {
1147 $dir .= "/$component";
1148 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1149
1150 if (!$next) {
1151 # failed, check for symlinks and try to create the path
1152 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
1153 die "cannot open directory $dir: $!\n" if !$mkdir;
1154
1155 # We don't check for errors on mkdirat() here and just try to
1156 # openat() again, since at least one error (EEXIST) is an
1157 # expected possibility if multiple containers start
1158 # simultaneously. If someone else injects a symlink now then
1159 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1160 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1161
1162 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1163 die "failed to create path: $dir: $!\n" if !$next;
1164 }
1165
1166 close $second if defined($last_component);
1167 $last_component = $component;
1168 $second = $fd;
1169 $fd = $next;
1170 }
1171
1172 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1173 close $second if defined($last_component);
1174 return $fd;
1175 }
1176
1177 # To guard against symlink attack races against other currently running
1178 # containers with shared recursive bind mount hierarchies we prepare a
1179 # directory handle for the directory we're mounting over to verify the
1180 # mountpoint afterwards.
1181 sub __bindmount_prepare {
1182 my ($hostroot, $dir) = @_;
1183 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1184 return $srcdh;
1185 }
1186
1187 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1188 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1189 # we intended to bind mount.
1190 sub __bindmount_verify {
1191 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1192 my $destdh;
1193 if ($parentfd) {
1194 # Open the mount point path coming from the parent directory since the
1195 # filehandle we would have gotten as first result of walk_tree_nofollow
1196 # earlier is still a handle to the underlying directory instead of the
1197 # mounted path.
1198 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1199 die "failed to open mount point: $!\n" if !$destdh;
1200 if ($ro) {
1201 my $dot = '.';
1202 # no separate function because 99% of the time it's the wrong thing to use.
1203 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
1204 die "failed to mark bind mount read only\n";
1205 }
1206 die "read-only check failed: $!\n" if $! != EROFS;
1207 }
1208 } else {
1209 # For the rootfs we don't have a parentfd so we open the path directly.
1210 # Note that this means bindmounting any prefix of the host's
1211 # /var/lib/lxc/$vmid path into another container is considered a grave
1212 # security error.
1213 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
1214 die "failed to open mount point: $!\n" if !$destdh;
1215 }
1216
1217 my ($srcdev, $srcinode) = stat($srcdh);
1218 my ($dstdev, $dstinode) = stat($destdh);
1219 close $srcdh;
1220 close $destdh;
1221
1222 return ($srcdev == $dstdev && $srcinode == $dstinode);
1223 }
1224
1225 # Perform the actual bind mounting:
1226 sub __bindmount_do {
1227 my ($dir, $dest, $ro, @extra_opts) = @_;
1228 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1229 if ($ro) {
1230 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1231 if (my $err = $@) {
1232 warn "bindmount error\n";
1233 # don't leave writable bind-mounts behind...
1234 PVE::Tools::run_command(['umount', $dest]);
1235 die $err;
1236 }
1237 }
1238 }
1239
1240 sub bindmount {
1241 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1242
1243 my $srcdh = __bindmount_prepare('/', $dir);
1244
1245 __bindmount_do($dir, $dest, $ro, @extra_opts);
1246
1247 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
1248 PVE::Tools::run_command(['umount', $dest]);
1249 die "detected mount path change at: $dir\n";
1250 }
1251 }
1252
1253 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1254 # from $rootdir and $mount and walk the path from $rootdir to the final
1255 # directory to check for symlinks.
1256 sub __mount_prepare_rootdir {
1257 my ($rootdir, $mount) = @_;
1258 $rootdir =~ s!/+!/!g;
1259 $rootdir =~ s!/+$!!;
1260 my $mount_path = "$rootdir/$mount";
1261 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1);
1262 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1263 }
1264
1265 # use $rootdir = undef to just return the corresponding mount path
1266 sub mountpoint_mount {
1267 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
1268
1269 my $volid = $mountpoint->{volume};
1270 my $mount = $mountpoint->{mp};
1271 my $type = $mountpoint->{type};
1272 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1273 my $mounted_dev;
1274
1275 return if !$volid || !$mount;
1276
1277 $mount =~ s!/+!/!g;
1278
1279 my $mount_path;
1280 my ($mpfd, $parentfd, $last_dir);
1281
1282 if (defined($rootdir)) {
1283 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1284 __mount_prepare_rootdir($rootdir, $mount);
1285 }
1286
1287 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1288
1289 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1290
1291 my $optstring = '';
1292 my $acl = $mountpoint->{acl};
1293 if (defined($acl)) {
1294 $optstring .= ($acl ? 'acl' : 'noacl');
1295 }
1296 my $readonly = $mountpoint->{ro};
1297
1298 my @extra_opts;
1299 @extra_opts = ('-o', $optstring) if $optstring;
1300
1301 if ($storage) {
1302
1303 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1304
1305 # early sanity checks:
1306 # we otherwise call realpath on the rbd url
1307 die "containers on rbd storage without krbd are not supported\n"
1308 if $scfg->{type} eq 'rbd' && !$scfg->{krbd};
1309
1310 my $path = PVE::Storage::path($storage_cfg, $volid, $snapname);
1311
1312 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1313 PVE::Storage::parse_volname($storage_cfg, $volid);
1314
1315 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1316
1317 if ($format eq 'subvol') {
1318 if ($mount_path) {
1319 if ($snapname) {
1320 if ($scfg->{type} eq 'zfspool') {
1321 my $path_arg = $path;
1322 $path_arg =~ s!^/+!!;
1323 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
1324 } else {
1325 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1326 }
1327 } else {
1328 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1329 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1330 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1331 $name .= "\@$snapname" if defined($snapname);
1332 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1333 }
1334 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1335 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1336 }
1337 }
1338 return wantarray ? ($path, 0, undef) : $path;
1339 } elsif ($format eq 'raw' || $format eq 'iso') {
1340 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1341 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1342 # Our autodev hook expects the /dev/dm-* device currently
1343 # and will create the /dev/mapper symlink accordingly
1344 $path = Cwd::realpath($path);
1345 die "failed to get device path\n" if !$path;
1346 ($path) = ($path =~ /^(.*)$/s); #untaint
1347 my $domount = sub {
1348 my ($path) = @_;
1349 if ($mount_path) {
1350 if ($format eq 'iso') {
1351 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1352 } elsif ($isBase || defined($snapname)) {
1353 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1354 } else {
1355 if ($quota) {
1356 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1357 }
1358 push @extra_opts, '-o', 'ro' if $readonly;
1359 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1360 }
1361 }
1362 };
1363 my $use_loopdev = 0;
1364 if ($scfg->{path}) {
1365 $mounted_dev = run_with_loopdev($domount, $path);
1366 $use_loopdev = 1;
1367 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1368 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
1369 $mounted_dev = $path;
1370 &$domount($path);
1371 } else {
1372 die "unsupported storage type '$scfg->{type}'\n";
1373 }
1374 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
1375 } else {
1376 die "unsupported image format '$format'\n";
1377 }
1378 } elsif ($type eq 'device') {
1379 push @extra_opts, '-o', 'ro' if $readonly;
1380 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1381 # See the NOTE above about devicemapper canonicalization
1382 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
1383 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1384 return wantarray ? ($volid, 0, $devpath) : $volid;
1385 } elsif ($type eq 'bind') {
1386 die "directory '$volid' does not exist\n" if ! -d $volid;
1387 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1388 warn "cannot enable quota control for bind mounts\n" if $quota;
1389 return wantarray ? ($volid, 0, undef) : $volid;
1390 }
1391
1392 die "unsupported storage";
1393 }
1394
1395 sub mkfs {
1396 my ($dev, $rootuid, $rootgid) = @_;
1397
1398 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1399 '-E', "root_owner=$rootuid:$rootgid",
1400 $dev]);
1401 }
1402
1403 sub format_disk {
1404 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
1405
1406 if ($volid =~ m!^/dev/.+!) {
1407 mkfs($volid);
1408 return;
1409 }
1410
1411 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1412
1413 die "cannot format volume '$volid' with no storage\n" if !$storage;
1414
1415 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1416
1417 my $path = PVE::Storage::path($storage_cfg, $volid);
1418
1419 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1420 PVE::Storage::parse_volname($storage_cfg, $volid);
1421
1422 die "cannot format volume '$volid' (format == $format)\n"
1423 if $format ne 'raw';
1424
1425 mkfs($path, $rootuid, $rootgid);
1426 }
1427
1428 sub destroy_disks {
1429 my ($storecfg, $vollist) = @_;
1430
1431 foreach my $volid (@$vollist) {
1432 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1433 warn $@ if $@;
1434 }
1435 }
1436
1437 sub alloc_disk {
1438 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1439
1440 my $needs_chown = 0;
1441 my $volid;
1442
1443 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1444 # fixme: use better naming ct-$vmid-disk-X.raw?
1445
1446 eval {
1447 my $do_format = 0;
1448 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs' || $scfg->{type} eq 'cifs' ) {
1449 if ($size_kb > 0) {
1450 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1451 undef, $size_kb);
1452 $do_format = 1;
1453 } else {
1454 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1455 undef, 0);
1456 $needs_chown = 1;
1457 }
1458 } elsif ($scfg->{type} eq 'zfspool') {
1459
1460 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1461 undef, $size_kb);
1462 $needs_chown = 1;
1463 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1464
1465 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1466 $do_format = 1;
1467
1468 } elsif ($scfg->{type} eq 'rbd') {
1469
1470 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd};
1471 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1472 $do_format = 1;
1473 } else {
1474 die "unable to create containers on storage type '$scfg->{type}'\n";
1475 }
1476 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1477 };
1478 if (my $err = $@) {
1479 # in case formatting got interrupted:
1480 if (defined($volid)) {
1481 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1482 warn $@ if $@;
1483 }
1484 die $err;
1485 }
1486
1487 return ($volid, $needs_chown);
1488 }
1489
1490 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
1491 sub create_disks {
1492 my ($storecfg, $vmid, $settings, $conf) = @_;
1493
1494 my $vollist = [];
1495
1496 eval {
1497 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1498 my $chown_vollist = [];
1499
1500 PVE::LXC::Config->foreach_mountpoint($settings, sub {
1501 my ($ms, $mountpoint) = @_;
1502
1503 my $volid = $mountpoint->{volume};
1504 my $mp = $mountpoint->{mp};
1505
1506 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1507
1508 if ($storage && ($volid =~ $NEW_DISK_RE)) {
1509 my ($storeid, $size_gb) = ($1, $2);
1510
1511 my $size_kb = int(${size_gb}*1024) * 1024;
1512
1513 my $needs_chown = 0;
1514 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1515 push @$chown_vollist, $volid if $needs_chown;
1516 push @$vollist, $volid;
1517 $mountpoint->{volume} = $volid;
1518 $mountpoint->{size} = $size_kb * 1024;
1519 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1520 } else {
1521 # use specified/existing volid/dir/device
1522 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1523 }
1524 });
1525
1526 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1527 foreach my $volid (@$chown_vollist) {
1528 my $path = PVE::Storage::path($storecfg, $volid, undef);
1529 chown($rootuid, $rootgid, $path);
1530 }
1531 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
1532 };
1533 # free allocated images on error
1534 if (my $err = $@) {
1535 destroy_disks($storecfg, $vollist);
1536 die $err;
1537 }
1538 return $vollist;
1539 }
1540
1541 # bash completion helper
1542
1543 sub complete_os_templates {
1544 my ($cmdname, $pname, $cvalue) = @_;
1545
1546 my $cfg = PVE::Storage::config();
1547
1548 my $storeid;
1549
1550 if ($cvalue =~ m/^([^:]+):/) {
1551 $storeid = $1;
1552 }
1553
1554 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1555 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1556
1557 my $res = [];
1558 foreach my $id (keys %$data) {
1559 foreach my $item (@{$data->{$id}}) {
1560 push @$res, $item->{volid} if defined($item->{volid});
1561 }
1562 }
1563
1564 return $res;
1565 }
1566
1567 my $complete_ctid_full = sub {
1568 my ($running) = @_;
1569
1570 my $idlist = vmstatus();
1571
1572 my $active_hash = list_active_containers();
1573
1574 my $res = [];
1575
1576 foreach my $id (keys %$idlist) {
1577 my $d = $idlist->{$id};
1578 if (defined($running)) {
1579 next if $d->{template};
1580 next if $running && !$active_hash->{$id};
1581 next if !$running && $active_hash->{$id};
1582 }
1583 push @$res, $id;
1584
1585 }
1586 return $res;
1587 };
1588
1589 sub complete_ctid {
1590 return &$complete_ctid_full();
1591 }
1592
1593 sub complete_ctid_stopped {
1594 return &$complete_ctid_full(0);
1595 }
1596
1597 sub complete_ctid_running {
1598 return &$complete_ctid_full(1);
1599 }
1600
1601 sub parse_id_maps {
1602 my ($conf) = @_;
1603
1604 my $id_map = [];
1605 my $rootuid = 0;
1606 my $rootgid = 0;
1607
1608 my $lxc = $conf->{lxc};
1609 foreach my $entry (@$lxc) {
1610 my ($key, $value) = @$entry;
1611 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
1612 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
1613 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1614 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1615 push @$id_map, [$type, $ct, $host, $length];
1616 if ($ct == 0) {
1617 $rootuid = $host if $type eq 'u';
1618 $rootgid = $host if $type eq 'g';
1619 }
1620 } else {
1621 die "failed to parse idmap: $value\n";
1622 }
1623 }
1624
1625 if (!@$id_map && $conf->{unprivileged}) {
1626 # Should we read them from /etc/subuid?
1627 $id_map = [ ['u', '0', '100000', '65536'],
1628 ['g', '0', '100000', '65536'] ];
1629 $rootuid = $rootgid = 100000;
1630 }
1631
1632 return ($id_map, $rootuid, $rootgid);
1633 }
1634
1635 sub userns_command {
1636 my ($id_map) = @_;
1637 if (@$id_map) {
1638 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1639 }
1640 return [];
1641 }
1642
1643 sub vm_start {
1644 my ($vmid, $conf, $skiplock) = @_;
1645
1646 update_lxc_config($vmid, $conf);
1647
1648 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
1649
1650 if ($skiplock) {
1651 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
1652 close($fh);
1653 }
1654
1655 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
1656
1657 eval { PVE::Tools::run_command($cmd); };
1658 if (my $err = $@) {
1659 unlink $skiplock_flag_fn;
1660 die $err;
1661 }
1662
1663 return;
1664 }
1665
1666 # Helper to stop a container completely and make sure it has stopped completely.
1667 # This is necessary because we want the post-stop hook to have completed its
1668 # unmount-all step, but post-stop happens after lxc puts the container into the
1669 # STOPPED state.
1670 sub vm_stop {
1671 my ($vmid, $kill, $shutdown_timeout, $exit_timeout) = @_;
1672
1673 # Open the container's command socket.
1674 my $path = "\0/var/lib/lxc/$vmid/command";
1675 my $sock = IO::Socket::UNIX->new(
1676 Type => SOCK_STREAM(),
1677 Peer => $path,
1678 );
1679 if (!$sock) {
1680 return if $! == ECONNREFUSED; # The container is not running
1681 die "failed to open container ${vmid}'s command socket: $!\n";
1682 }
1683
1684 # Stop the container:
1685
1686 my $cmd = ['lxc-stop', '-n', $vmid];
1687
1688 if ($kill) {
1689 push @$cmd, '--kill'; # doesn't allow timeouts
1690 } elsif (defined($shutdown_timeout)) {
1691 push @$cmd, '--timeout', $shutdown_timeout;
1692 # Give run_command 5 extra seconds
1693 $shutdown_timeout += 5;
1694 }
1695
1696 eval { PVE::Tools::run_command($cmd, timeout => $shutdown_timeout) };
1697 if (my $err = $@) {
1698 warn $@ if $@;
1699 }
1700
1701 my $result = 1;
1702 my $wait = sub { $result = <$sock>; };
1703 if (defined($exit_timeout)) {
1704 PVE::Tools::run_with_timeout($exit_timeout, $wait);
1705 } else {
1706 $wait->();
1707 }
1708
1709 return if !defined $result; # monitor is gone and the ct has stopped.
1710 die "container did not stop\n";
1711 }
1712
1713 sub run_unshared {
1714 my ($code) = @_;
1715
1716 return PVE::Tools::run_fork(sub {
1717 # Unshare the mount namespace
1718 die "failed to unshare mount namespace: $!\n"
1719 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
1720 PVE::Tools::run_command(['mount', '--make-rslave', '/']);
1721 return $code->();
1722 });
1723 }
1724
1725 my $copy_volume = sub {
1726 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname) = @_;
1727
1728 my $src_mp = { volume => $src_volid, mp => '/' };
1729 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
1730
1731 my $dst_mp = { volume => $dst_volid, mp => '/' };
1732 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
1733
1734 my @mounted;
1735 eval {
1736 # mount and copy
1737 mkdir $src;
1738 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname);
1739 push @mounted, $src;
1740 mkdir $dest;
1741 mountpoint_mount($dst_mp, $dest, $storage_cfg);
1742 push @mounted, $dest;
1743
1744 PVE::Tools::run_command(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
1745 '-aH', '--whole-file', '--sparse', '--one-file-system',
1746 "$src/", $dest]);
1747 };
1748 my $err = $@;
1749 foreach my $mount (reverse @mounted) {
1750 eval { PVE::Tools::run_command(['/bin/umount', '--lazy', $mount], errfunc => sub{})};
1751 warn "Can't umount $mount\n" if $@;
1752 }
1753
1754 # If this fails they're used as mount points in a concurrent operation
1755 # (which should not happen but there's also no real need to get rid of them).
1756 rmdir $dest;
1757 rmdir $src;
1758
1759 die $err if $err;
1760 };
1761
1762 # Should not be called after unsharing the mount namespace!
1763 sub copy_volume {
1764 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname) = @_;
1765
1766 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
1767 File::Path::make_path("/var/lib/lxc/$vmid");
1768 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
1769 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
1770
1771 # get id's for unprivileged container
1772 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1773
1774 # Allocate the disk before unsharing in order to make sure zfs subvolumes
1775 # are visible in this namespace, otherwise the host only sees the empty
1776 # (not-mounted) directory.
1777 my $new_volid;
1778 eval {
1779 # Make sure $mp contains a correct size.
1780 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
1781 my $needs_chown;
1782 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
1783 if ($needs_chown) {
1784 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
1785 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
1786 chown($rootuid, $rootgid, $path);
1787 }
1788
1789 run_unshared(sub {
1790 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname);
1791 });
1792 };
1793 if (my $err = $@) {
1794 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
1795 if defined($new_volid);
1796 die $err;
1797 }
1798
1799 return $new_volid;
1800 }
1801
1802 1;