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