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