]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC.pm
list_active_containers: fix regex
[pve-container.git] / src / PVE / LXC.pm
CommitLineData
f76a2828
DM
1package PVE::LXC;
2
3use strict;
4use warnings;
67afe46e 5
d14a9a1b 6use POSIX qw(EINTR);
f76a2828 7
34fdb3d7
WB
8use Socket;
9
f76a2828 10use File::Path;
2cfae16e
WB
11use File::Spec;
12use Cwd qw();
3cc56749 13use Fcntl qw(O_RDONLY);
f76a2828 14
f1ba1a4b 15use PVE::Exception qw(raise_perm_exc);
c65e0a6d 16use PVE::Storage;
f76a2828
DM
17use PVE::SafeSyslog;
18use PVE::INotify;
1bfe8728 19use PVE::Tools qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full);
68fba17b 20use PVE::Network;
52389a07 21use PVE::AccessControl;
228a5a1d 22use PVE::ProcFSTools;
67afe46e 23use PVE::LXC::Config;
688afc63 24use Time::HiRes qw (gettimeofday);
f76a2828
DM
25
26use Data::Dumper;
27
27916659
DM
28my $nodename = PVE::INotify::nodename();
29
688afc63
WL
30my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
31
f9897acd 32our $COMMON_TAR_FLAGS = [ '--sparse', '--numeric-owner', '--acls',
fc4e132e
WB
33 '--xattrs',
34 '--xattrs-include=user.*',
4132377b
WB
35 '--xattrs-include=security.capability',
36 '--warning=no-xattr-write' ];
fc4e132e 37
f76a2828
DM
38sub 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
5b4657d0
DM
54sub destroy_config {
55 my ($vmid) = @_;
56
67afe46e 57 unlink PVE::LXC::Config->config_file($vmid, $nodename);
3cc56749
FG
58}
59
822de0c3
DM
60# container status helpers
61
62sub list_active_containers {
cbb03fea 63
822de0c3
DM
64 my $filename = "/proc/net/unix";
65
66 # similar test is used by lcxcontainers.c: list_active_containers
67 my $res = {};
cbb03fea 68
822de0c3
DM
69 my $fh = IO::File->new ($filename, "r");
70 return $res if !$fh;
71
72 while (defined(my $line = <$fh>)) {
28df2cde 73 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
822de0c3 74 my $path = $1;
27916659 75 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
822de0c3
DM
76 $res->{$1} = 1;
77 }
78 }
79 }
80
81 close($fh);
cbb03fea 82
822de0c3
DM
83 return $res;
84}
f76a2828 85
5c752bbf
DM
86# warning: this is slow
87sub check_running {
88 my ($vmid) = @_;
89
90 my $active_hash = list_active_containers();
91
92 return 1 if defined($active_hash->{$vmid});
cbb03fea 93
5c752bbf
DM
94 return undef;
95}
96
10fc3ba5 97sub get_container_disk_usage {
73e03cb7 98 my ($vmid, $pid) = @_;
10fc3ba5 99
73e03cb7 100 return PVE::Tools::df("/proc/$pid/root/", 1);
10fc3ba5
DM
101}
102
688afc63
WL
103my $last_proc_vmid_stat;
104
105my $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
f76a2828
DM
122sub vmstatus {
123 my ($opt_vmid) = @_;
124
125 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc' }} : config_list();
126
822de0c3 127 my $active_hash = list_active_containers();
cbb03fea 128
688afc63
WL
129 my $cpucount = $cpuinfo->{cpus} || 1;
130
131 my $cdtime = gettimeofday;
132
133 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
134
f76a2828 135 foreach my $vmid (keys %$list) {
f76a2828 136 my $d = $list->{$vmid};
10fc3ba5 137
d5588ee3
DM
138 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
139 warn $@ if $@; # ignore errors (consider them stopped)
cbb03fea 140
d5588ee3 141 $d->{status} = $d->{pid} ? 'running' : 'stopped';
f76a2828 142
67afe46e 143 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
238a56cb 144 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
cbb03fea 145
27916659 146 $d->{name} = $conf->{'hostname'} || "CT$vmid";
238a56cb 147 $d->{name} =~ s/[\s]//g;
cbb03fea 148
9db5687d 149 $d->{cpus} = $conf->{cpulimit} || $cpucount;
44da0641 150
d0226204
WB
151 $d->{lock} = $conf->{lock} || '';
152
d5588ee3
DM
153 if ($d->{pid}) {
154 my $res = get_container_disk_usage($vmid, $d->{pid});
27916659
DM
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}) {
1b4cf758 161 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($rootfs);
27916659
DM
162 $d->{maxdisk} = int(($rootinfo->{size} || 4)*1024*1024)*1024;
163 } else {
164 $d->{maxdisk} = 4*1024*1024*1024;
10fc3ba5 165 }
238a56cb 166 }
cbb03fea 167
238a56cb
DM
168 $d->{mem} = 0;
169 $d->{swap} = 0;
95df9a12
DM
170 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
171 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
e901d418 172
238a56cb
DM
173 $d->{uptime} = 0;
174 $d->{cpu} = 0;
e901d418 175
238a56cb
DM
176 $d->{netout} = 0;
177 $d->{netin} = 0;
f76a2828 178
238a56cb
DM
179 $d->{diskread} = 0;
180 $d->{diskwrite} = 0;
bb1ac2de 181
67afe46e 182 $d->{template} = PVE::LXC::Config->is_template($conf);
f76a2828 183 }
cbb03fea 184
238a56cb
DM
185 foreach my $vmid (keys %$list) {
186 my $d = $list->{$vmid};
d5588ee3
DM
187 my $pid = $d->{pid};
188
189 next if !$pid; # skip stopped CTs
f76a2828 190
88a8696b
TL
191 my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
192 $d->{uptime} = time - $ctime; # the method lxcfs uses
22a77285 193
238a56cb
DM
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};
b5289322
AD
196
197 my $blkio_bytes = read_cgroup_value('blkio', $vmid, 'blkio.throttle.io_service_bytes', 1);
1e647c7c 198 my @bytes = split(/\n/, $blkio_bytes);
b5289322 199 foreach my $byte (@bytes) {
1e647c7c
DM
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 }
b5289322 204 }
688afc63
WL
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 }
238a56cb 234 }
cbb03fea 235
68b8f4d1
WL
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
f76a2828
DM
250 return $list;
251}
252
238a56cb
DM
253sub 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
bf0b8c43
AD
263sub 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
52f1d76b
DM
271sub 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
c31ad455 283 # search for lxc-console -n <vmid>
cbb03fea 284 return if scalar(@args) != 3;
52f1d76b
DM
285 return if $args[1] ne '-n';
286 return if $args[2] !~ m/^\d+$/;
287 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
cbb03fea 288
52f1d76b 289 my $vmid = $args[2];
cbb03fea 290
52f1d76b
DM
291 push @{$res->{$vmid}}, $pid;
292 });
293
294 return $res;
295}
296
bedeaaf1
AD
297sub find_lxc_pid {
298 my ($vmid) = @_;
299
300 my $pid = undef;
301 my $parser = sub {
302 my $line = shift;
8b25977f 303 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
bedeaaf1 304 };
c39aa40a 305 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
bedeaaf1 306
8b25977f 307 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
cbb03fea 308
8b25977f 309 return $pid;
bedeaaf1
AD
310}
311
cbb03fea 312# Note: we cannot use Net:IP, because that only allows strict
55fa4e09
DM
313# CIDR networks
314sub parse_ipv4_cidr {
315 my ($cidr, $noerr) = @_;
316
f7a7b413
WB
317 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
318 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
55fa4e09 319 }
cbb03fea 320
55fa4e09 321 return undef if $noerr;
cbb03fea 322
55fa4e09
DM
323 die "unable to parse ipv4 address/mask\n";
324}
93285df8 325
e22af68f 326
27916659 327sub update_lxc_config {
c628ffa1 328 my ($storage_cfg, $vmid, $conf) = @_;
b80dd50a 329
bb1ac2de
DM
330 my $dir = "/var/lib/lxc/$vmid";
331
332 if ($conf->{template}) {
333
334 unlink "$dir/config";
335
336 return;
337 }
338
27916659 339 my $raw = '';
b80dd50a 340
27916659
DM
341 die "missing 'arch' - internal error" if !$conf->{arch};
342 $raw .= "lxc.arch = $conf->{arch}\n";
b80dd50a 343
425b62cb
WB
344 my $unprivileged = $conf->{unprivileged};
345 my $custom_idmap = grep { $_->[0] eq 'lxc.id_map' } @{$conf->{lxc}};
346
27916659 347 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
238b7e3e 348 if ($ostype =~ /^(?:debian | ubuntu | centos | fedora | opensuse | archlinux | alpine | unmanaged)$/x) {
c34f7efe
WB
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";
425b62cb 352 if ($unprivileged || $custom_idmap) {
c34f7efe
WB
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"
425b62cb 356 }
27916659 357 } else {
9a7a910b 358 die "implement me (ostype $ostype)";
27916659 359 }
b80dd50a 360
50df544c
WB
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!
c16b8890 366 $raw .= "lxc.monitor.unshare = 1\n";
58cc92a9 367
425b62cb
WB
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
d250604f 374 if (!PVE::LXC::Config->has_dev_console($conf)) {
eeaea429
DM
375 $raw .= "lxc.console = none\n";
376 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
377 }
4f958489 378
1b4cf758 379 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
27916659 380 $raw .= "lxc.tty = $ttycount\n";
cbb03fea 381
c31ad455 382 # some init scripts expect a linux terminal (turnkey).
a691a5a3
DM
383 $raw .= "lxc.environment = TERM=linux\n";
384
27916659
DM
385 my $utsname = $conf->{hostname} || "CT$vmid";
386 $raw .= "lxc.utsname = $utsname\n";
cbb03fea 387
27916659
DM
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";
a12a36e0 393
27916659
DM
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";
a12a36e0
WL
401 }
402
27916659
DM
403 my $shares = $conf->{cpuunits} || 1024;
404 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
405
1b4cf758 406 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
a3076d81 407
c9a5774b 408 $raw .= "lxc.rootfs = $dir/rootfs\n";
27916659
DM
409
410 my $netcount = 0;
411 foreach my $k (keys %$conf) {
412 next if $k !~ m/^net(\d+)$/;
413 my $ind = $1;
1b4cf758 414 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
27916659
DM
415 $netcount++;
416 $raw .= "lxc.network.type = veth\n";
18862537 417 $raw .= "lxc.network.veth.pair = veth${vmid}i${ind}\n";
27916659
DM
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});
a12a36e0
WL
421 }
422
e576f689
DM
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 }
27916659 430
e576f689
DM
431 $raw .= "lxc.network.type = empty\n" if !$netcount;
432
27916659
DM
433 File::Path::mkpath("$dir/rootfs");
434
435 PVE::Tools::file_set_contents("$dir/config", $raw);
b80dd50a
DM
436}
437
117636e5
DM
438# verify and cleanup nameserver list (replace \0 with ' ')
439sub 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
451sub 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
aca816ad
DM
463sub get_console_command {
464 my ($vmid, $conf) = @_;
465
1b4cf758 466 my $cmode = PVE::LXC::Config->get_cmode($conf);
aca816ad
DM
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
c325b32f
DM
479sub get_primary_ips {
480 my ($conf) = @_;
481
482 # return data from net0
cbb03fea 483
27916659 484 return undef if !defined($conf->{net0});
1b4cf758 485 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
c325b32f
DM
486
487 my $ipv4 = $net->{ip};
db78a181
WB
488 if ($ipv4) {
489 if ($ipv4 =~ /^(dhcp|manual)$/) {
490 $ipv4 = undef
491 } else {
492 $ipv4 =~ s!/\d+$!!;
493 }
494 }
65e5eaa3 495 my $ipv6 = $net->{ip6};
db78a181 496 if ($ipv6) {
5f291c7d 497 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
db78a181
WB
498 $ipv6 = undef;
499 } else {
500 $ipv6 =~ s!/\d+$!!;
501 }
502 }
cbb03fea 503
c325b32f
DM
504 return ($ipv4, $ipv6);
505}
148d1cb4 506
b407293b
WB
507sub delete_mountpoint_volume {
508 my ($storage_cfg, $vmid, $volume) = @_;
509
d250604f 510 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
b407293b
WB
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}
ef241384 515
27916659 516sub destroy_lxc_container {
148d1cb4
DM
517 my ($storage_cfg, $vmid, $conf) = @_;
518
d250604f 519 PVE::LXC::Config->foreach_mountpoint($conf, sub {
db8989e1 520 my ($ms, $mountpoint) = @_;
b407293b 521 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
db8989e1
WB
522 });
523
27916659
DM
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);
148d1cb4 531}
68fba17b 532
ef241384 533sub vm_stop_cleanup {
5fa890f0 534 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
ef241384
DM
535
536 eval {
537 if (!$keepActive) {
bf9d912c 538
d250604f 539 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
a8b6b8a7 540 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
ef241384
DM
541 }
542 };
543 warn $@ if $@; # avoid errors - just warn
544}
545
93cdbbfb
AD
546my $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
556my $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
566sub update_net {
bedeaaf1 567 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
93cdbbfb 568
18862537
WB
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}";
93cdbbfb
AD
575 my $eth = $newnet->{name};
576
18862537 577 if (my $oldnetcfg = $conf->{$opt}) {
1b4cf758 578 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
18862537
WB
579
580 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
581 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
93cdbbfb 582
18862537 583 PVE::Network::veth_delete($veth);
bedeaaf1 584 delete $conf->{$opt};
67afe46e 585 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb 586
18862537 587 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
bedeaaf1 588
18862537
WB
589 } elsif (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
590 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
591 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
bedeaaf1 592
18862537 593 if ($oldnet->{bridge}) {
bedeaaf1 594 PVE::Network::tap_unplug($veth);
18862537
WB
595 foreach (qw(bridge tag firewall)) {
596 delete $oldnet->{$_};
597 }
1b4cf758 598 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
67afe46e 599 PVE::LXC::Config->write_config($vmid, $conf);
bedeaaf1 600 }
93cdbbfb 601
23eb2244 602 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks});
18862537
WB
603 foreach (qw(bridge tag firewall)) {
604 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
605 }
1b4cf758 606 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
67afe46e 607 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
608 }
609 } else {
18862537 610 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
93cdbbfb
AD
611 }
612
bedeaaf1 613 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
93cdbbfb
AD
614}
615
616sub hotplug_net {
18862537 617 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
93cdbbfb 618
18862537 619 my $veth = "veth${vmid}i${netid}";
cbb03fea 620 my $vethpeer = $veth . "p";
93cdbbfb
AD
621 my $eth = $newnet->{name};
622
623 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
23eb2244 624 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks});
93cdbbfb 625
cbb03fea 626 # attach peer in container
93cdbbfb
AD
627 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
628 PVE::Tools::run_command($cmd);
629
cbb03fea 630 # link up peer in container
93cdbbfb
AD
631 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
632 PVE::Tools::run_command($cmd);
bedeaaf1 633
18862537
WB
634 my $done = { type => 'veth' };
635 foreach (qw(bridge tag firewall hwaddr name)) {
636 $done->{$_} = $newnet->{$_} if $newnet->{$_};
637 }
1b4cf758 638 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
bedeaaf1 639
67afe46e 640 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
641}
642
68a05bb3 643sub update_ipconfig {
bedeaaf1
AD
644 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
645
f2104b80 646 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
bedeaaf1 647
1b4cf758 648 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
84e0c123
WB
649 my $deleted = [];
650 my $added = [];
8d723477
WB
651 my $nscmd = sub {
652 my $cmdargs = shift;
653 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
84e0c123 654 };
8d723477 655 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
2bfd1615 656
84e0c123 657 my $change_ip_config = sub {
f39002a6
DM
658 my ($ipversion) = @_;
659
660 my $family_opt = "-$ipversion";
661 my $suffix = $ipversion == 4 ? '' : $ipversion;
84e0c123
WB
662 my $gw= "gw$suffix";
663 my $ip= "ip$suffix";
bedeaaf1 664
6178b0dd
WB
665 my $newip = $newnet->{$ip};
666 my $newgw = $newnet->{$gw};
667 my $oldip = $optdata->{$ip};
668
669 my $change_ip = &$safe_string_ne($oldip, $newip);
670 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
bedeaaf1 671
84e0c123 672 return if !$change_ip && !$change_gw;
68a05bb3 673
84e0c123 674 # step 1: add new IP, if this fails we cancel
292aff54
WB
675 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
676 if ($change_ip && $is_real_ip) {
8d723477 677 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
84e0c123
WB
678 if (my $err = $@) {
679 warn $err;
680 return;
681 }
bedeaaf1 682 }
bedeaaf1 683
84e0c123
WB
684 # step 2: replace gateway
685 # If this fails we delete the added IP and cancel.
686 # If it succeeds we save the config and delete the old IP, ignoring
687 # errors. The config is then saved.
688 # Note: 'ip route replace' can add
689 if ($change_gw) {
6178b0dd 690 if ($newgw) {
292aff54
WB
691 eval {
692 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
693 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
694 }
695 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
696 };
84e0c123
WB
697 if (my $err = $@) {
698 warn $err;
699 # the route was not replaced, the old IP is still available
700 # rollback (delete new IP) and cancel
701 if ($change_ip) {
8d723477 702 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
84e0c123
WB
703 warn $@ if $@; # no need to die here
704 }
705 return;
706 }
707 } else {
8d723477 708 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
84e0c123
WB
709 # if the route was not deleted, the guest might have deleted it manually
710 # warn and continue
711 warn $@ if $@;
712 }
2bfd1615 713 }
2bfd1615 714
6178b0dd 715 # from this point on we save the configuration
84e0c123 716 # step 3: delete old IP ignoring errors
6178b0dd 717 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
8d723477
WB
718 # We need to enable promote_secondaries, otherwise our newly added
719 # address will be removed along with the old one.
720 my $promote = 0;
721 eval {
722 if ($ipversion == 4) {
723 &$nscmd({ outfunc => sub { $promote = int(shift) } },
724 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
725 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
726 }
727 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
728 };
84e0c123 729 warn $@ if $@; # no need to die here
8d723477
WB
730
731 if ($ipversion == 4) {
732 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
733 }
bedeaaf1
AD
734 }
735
84e0c123
WB
736 foreach my $property ($ip, $gw) {
737 if ($newnet->{$property}) {
738 $optdata->{$property} = $newnet->{$property};
739 } else {
740 delete $optdata->{$property};
741 }
bedeaaf1 742 }
1b4cf758 743 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
67afe46e 744 PVE::LXC::Config->write_config($vmid, $conf);
84e0c123
WB
745 $lxc_setup->setup_network($conf);
746 };
bedeaaf1 747
f39002a6
DM
748 &$change_ip_config(4);
749 &$change_ip_config(6);
489e960d
WL
750
751}
752
34fdb3d7
WB
753my $enter_namespace = sub {
754 my ($vmid, $pid, $which, $type) = @_;
755 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
756 or die "failed to open $which namespace of container $vmid: $!\n";
757 PVE::Tools::setns(fileno($fd), $type)
758 or die "failed to enter $which namespace of container $vmid: $!\n";
759 close $fd;
760};
761
762my $do_syncfs = sub {
763 my ($vmid, $pid, $socket) = @_;
764
765 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
766
767 # Tell the parent process to start reading our /proc/mounts
768 print {$socket} "go\n";
769 $socket->flush();
770
771 # Receive /proc/self/mounts
772 my $mountdata = do { local $/ = undef; <$socket> };
773 close $socket;
774
775 # Now sync all mountpoints...
776 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
777 foreach my $mp (@$mounts) {
778 my ($what, $dir, $fs) = @$mp;
779 next if $fs eq 'fuse.lxcfs';
780 eval { PVE::Tools::sync_mountpoint($dir); };
781 warn $@ if $@;
782 }
783};
784
785sub sync_container_namespace {
786 my ($vmid) = @_;
787 my $pid = find_lxc_pid($vmid);
788
789 # SOCK_DGRAM is nicer for barriers but cannot be slurped
790 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
791 or die "failed to create socketpair: $!\n";
792
793 my $child = fork();
794 die "fork failed: $!\n" if !defined($child);
795
796 if (!$child) {
797 eval {
798 close $pfd;
799 &$do_syncfs($vmid, $pid, $cfd);
800 };
801 if (my $err = $@) {
802 warn $err;
803 POSIX::_exit(1);
804 }
805 POSIX::_exit(0);
806 }
807 close $cfd;
808 my $go = <$pfd>;
809 die "failed to enter container namespace\n" if $go ne "go\n";
810
811 open my $mounts, '<', "/proc/$child/mounts"
812 or die "failed to open container's /proc/mounts: $!\n";
813 my $mountdata = do { local $/ = undef; <$mounts> };
814 close $mounts;
815 print {$pfd} $mountdata;
816 close $pfd;
817
818 while (waitpid($child, 0) != $child) {}
819 die "failed to sync container namespace\n" if $? != 0;
820}
821
bb1ac2de
DM
822sub template_create {
823 my ($vmid, $conf) = @_;
824
825 my $storecfg = PVE::Storage::config();
826
1b4cf758 827 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
bb1ac2de
DM
828 my $volid = $rootinfo->{volume};
829
830 die "Template feature is not available for '$volid'\n"
831 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
832
833 PVE::Storage::activate_volumes($storecfg, [$volid]);
834
835 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
836 $rootinfo->{volume} = $template_volid;
1b4cf758 837 $conf->{rootfs} = PVE::LXC::Config->print_ct_mountpoint($rootinfo, 1);
bb1ac2de 838
67afe46e 839 PVE::LXC::Config->write_config($vmid, $conf);
bb1ac2de
DM
840}
841
52389a07 842sub check_ct_modify_config_perm {
f1ba1a4b 843 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
52389a07 844
c81f19d1 845 return 1 if $authuser eq 'root@pam';
52389a07 846
f1ba1a4b
WB
847 my $check = sub {
848 my ($opt, $delete) = @_;
52389a07
DM
849 if ($opt eq 'cpus' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
850 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
e59a61ed 851 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
52389a07 852 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
f1ba1a4b 853 return if $delete;
1b4cf758
FG
854 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
855 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
f1ba1a4b 856 raise_perm_exc("mountpoint type $data->{type}") if $data->{type} ne 'volume';
52389a07
DM
857 } elsif ($opt eq 'memory' || $opt eq 'swap') {
858 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
859 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
860 $opt eq 'searchdomain' || $opt eq 'hostname') {
861 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
862 } else {
863 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
864 }
f1ba1a4b
WB
865 };
866
867 foreach my $opt (keys %$newconf) {
868 &$check($opt, 0);
869 }
870 foreach my $opt (@$delete) {
871 &$check($opt, 1);
52389a07
DM
872 }
873
874 return 1;
875}
876
9622e848 877sub umount_all {
da629848 878 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
9622e848
DM
879
880 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
d250604f 881 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848 882
d250604f 883 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
9622e848
DM
884 my ($ms, $mountpoint) = @_;
885
886 my $volid = $mountpoint->{volume};
887 my $mount = $mountpoint->{mp};
888
889 return if !$volid || !$mount;
890
d18f96b4 891 my $mount_path = "$rootdir/$mount";
f845a93d 892 $mount_path =~ s!/+!/!g;
9622e848 893
228a5a1d
WL
894 return if !PVE::ProcFSTools::is_mounted($mount_path);
895
9622e848 896 eval {
d18f96b4 897 PVE::Tools::run_command(['umount', '-d', $mount_path]);
9622e848
DM
898 };
899 if (my $err = $@) {
900 if ($noerr) {
901 warn $err;
902 } else {
903 die $err;
904 }
905 }
906 });
9622e848
DM
907}
908
909sub mount_all {
7b49dfe0 910 my ($vmid, $storage_cfg, $conf) = @_;
9622e848
DM
911
912 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1adc7e53 913 File::Path::make_path($rootdir);
9622e848 914
d250604f 915 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848
DM
916 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
917
918 eval {
d250604f 919 PVE::LXC::Config->foreach_mountpoint($conf, sub {
9622e848
DM
920 my ($ms, $mountpoint) = @_;
921
da629848 922 mountpoint_mount($mountpoint, $rootdir, $storage_cfg);
9622e848
DM
923 });
924 };
925 if (my $err = $@) {
e2007ac2 926 warn "mounting container failed\n";
9622e848 927 umount_all($vmid, $storage_cfg, $conf, 1);
e2007ac2 928 die $err;
9622e848
DM
929 }
930
da629848 931 return $rootdir;
9622e848
DM
932}
933
934
b15c75fc 935sub mountpoint_mount_path {
da629848 936 my ($mountpoint, $storage_cfg, $snapname) = @_;
b15c75fc 937
da629848 938 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
b15c75fc 939}
cc6b0307 940
2cfae16e
WB
941my $check_mount_path = sub {
942 my ($path) = @_;
943 $path = File::Spec->canonpath($path);
944 my $real = Cwd::realpath($path);
945 if ($real ne $path) {
946 die "mount path modified by symlink: $path != $real";
947 }
948};
949
21f292ff
WB
950sub query_loopdev {
951 my ($path) = @_;
952 my $found;
953 my $parser = sub {
954 my $line = shift;
955 if ($line =~ m@^(/dev/loop\d+):@) {
956 $found = $1;
957 }
958 };
959 my $cmd = ['losetup', '--associated', $path];
960 PVE::Tools::run_command($cmd, outfunc => $parser);
961 return $found;
962}
963
50df544c
WB
964# Run a function with a file attached to a loop device.
965# The loop device is always detached afterwards (or set to autoclear).
966# Returns the loop device.
967sub run_with_loopdev {
968 my ($func, $file) = @_;
54d11e5c
WB
969 my $device = query_loopdev($file);
970 # Try to reuse an existing device
971 if ($device) {
972 # We assume that whoever setup the loop device is responsible for
973 # detaching it.
974 &$func($device);
975 return $device;
976 }
977
50df544c
WB
978 my $parser = sub {
979 my $line = shift;
980 if ($line =~ m@^(/dev/loop\d+)$@) {
981 $device = $1;
982 }
983 };
984 PVE::Tools::run_command(['losetup', '--show', '-f', $file], outfunc => $parser);
985 die "failed to setup loop device for $file\n" if !$device;
986 eval { &$func($device); };
987 my $err = $@;
988 PVE::Tools::run_command(['losetup', '-d', $device]);
989 die $err if $err;
990 return $device;
991}
992
c2744c97
WB
993sub bindmount {
994 my ($dir, $dest, $ro, @extra_opts) = @_;
995 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
996 if ($ro) {
997 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
998 if (my $err = $@) {
999 warn "bindmount error\n";
1000 # don't leave writable bind-mounts behind...
1001 PVE::Tools::run_command(['umount', $dest]);
1002 die $err;
1003 }
1004 }
1005}
1006
b15c75fc 1007# use $rootdir = undef to just return the corresponding mount path
cc6b0307 1008sub mountpoint_mount {
da629848 1009 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
cc6b0307
AD
1010
1011 my $volid = $mountpoint->{volume};
1012 my $mount = $mountpoint->{mp};
7c921c80 1013 my $type = $mountpoint->{type};
50df544c
WB
1014 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1015 my $mounted_dev;
b15c75fc 1016
cc6b0307
AD
1017 return if !$volid || !$mount;
1018
b15c75fc
DM
1019 my $mount_path;
1020
1021 if (defined($rootdir)) {
1022 $rootdir =~ s!/+$!!;
1023 $mount_path = "$rootdir/$mount";
f845a93d 1024 $mount_path =~ s!/+!/!g;
2cfae16e 1025 &$check_mount_path($mount_path);
b15c75fc 1026 File::Path::mkpath($mount_path);
116ce06f 1027 }
b15c75fc
DM
1028
1029 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
cc6b0307 1030
b15c75fc 1031 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
cc6b0307 1032
471dd315
WB
1033 my $optstring = '';
1034 if (defined($mountpoint->{acl})) {
1035 $optstring .= ($mountpoint->{acl} ? 'acl' : 'noacl');
1036 }
c2744c97 1037 my $readonly = $mountpoint->{ro};
471dd315
WB
1038
1039 my @extra_opts = ('-o', $optstring);
1040
b15c75fc
DM
1041 if ($storage) {
1042
1043 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1044 my $path = PVE::Storage::path($storage_cfg, $volid, $snapname);
1045
1046 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1047 PVE::Storage::parse_volname($storage_cfg, $volid);
1048
c87b9dd8
DM
1049 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1050
b15c75fc 1051 if ($format eq 'subvol') {
30de33be
DM
1052 if ($mount_path) {
1053 if ($snapname) {
e84f7f5d
DM
1054 if ($scfg->{type} eq 'zfspool') {
1055 my $path_arg = $path;
1056 $path_arg =~ s!^/+!!;
471dd315 1057 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
e84f7f5d 1058 } else {
30de33be
DM
1059 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1060 }
e84f7f5d 1061 } else {
c2744c97 1062 bindmount($path, $mount_path, $readonly, @extra_opts);
50df544c 1063 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
30de33be 1064 }
b15c75fc 1065 }
50df544c 1066 return wantarray ? ($path, 0, $mounted_dev) : $path;
c87b9dd8 1067 } elsif ($format eq 'raw' || $format eq 'iso') {
50df544c
WB
1068 my $domount = sub {
1069 my ($path) = @_;
1070 if ($mount_path) {
1071 if ($format eq 'iso') {
1072 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1073 } elsif ($isBase || defined($snapname)) {
1074 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1075 } else {
1076 if ($quota) {
1077 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1078 }
c2744c97 1079 push @extra_opts, '-o', 'ro' if $readonly;
50df544c
WB
1080 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1081 }
1082 }
1083 };
30de33be 1084 my $use_loopdev = 0;
b15c75fc 1085 if ($scfg->{path}) {
50df544c 1086 $mounted_dev = run_with_loopdev($domount, $path);
30de33be 1087 $use_loopdev = 1;
2e879877
DM
1088 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1089 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
50df544c
WB
1090 $mounted_dev = $path;
1091 &$domount($path);
b15c75fc
DM
1092 } else {
1093 die "unsupported storage type '$scfg->{type}'\n";
1094 }
50df544c 1095 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
b15c75fc
DM
1096 } else {
1097 die "unsupported image format '$format'\n";
1098 }
7c921c80 1099 } elsif ($type eq 'device') {
c2744c97 1100 push @extra_opts, '-o', 'ro' if $readonly;
471dd315 1101 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
50df544c 1102 return wantarray ? ($volid, 0, $volid) : $volid;
e2007ac2
DM
1103 } elsif ($type eq 'bind') {
1104 die "directory '$volid' does not exist\n" if ! -d $volid;
2cfae16e 1105 &$check_mount_path($volid);
c2744c97 1106 bindmount($volid, $mount_path, $readonly, @extra_opts) if $mount_path;
50df544c
WB
1107 warn "cannot enable quota control for bind mounts\n" if $quota;
1108 return wantarray ? ($volid, 0, undef) : $volid;
b15c75fc
DM
1109 }
1110
1111 die "unsupported storage";
cc6b0307
AD
1112}
1113
6c871c36 1114sub mkfs {
d216e891 1115 my ($dev, $rootuid, $rootgid) = @_;
6c871c36 1116
d216e891
WB
1117 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1118 '-E', "root_owner=$rootuid:$rootgid",
1119 $dev]);
6c871c36
DM
1120}
1121
1122sub format_disk {
d216e891 1123 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
6c871c36
DM
1124
1125 if ($volid =~ m!^/dev/.+!) {
1126 mkfs($volid);
1127 return;
1128 }
1129
1130 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1131
1132 die "cannot format volume '$volid' with no storage\n" if !$storage;
1133
08ca136d
DM
1134 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1135
6c871c36
DM
1136 my $path = PVE::Storage::path($storage_cfg, $volid);
1137
1138 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1139 PVE::Storage::parse_volname($storage_cfg, $volid);
1140
1141 die "cannot format volume '$volid' (format == $format)\n"
1142 if $format ne 'raw';
1143
d216e891 1144 mkfs($path, $rootuid, $rootgid);
6c871c36
DM
1145}
1146
1147sub destroy_disks {
1148 my ($storecfg, $vollist) = @_;
1149
1150 foreach my $volid (@$vollist) {
1151 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1152 warn $@ if $@;
1153 }
1154}
1155
1156sub create_disks {
1157 my ($storecfg, $vmid, $settings, $conf) = @_;
1158
1159 my $vollist = [];
1160
1161 eval {
d216e891
WB
1162 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1163 my $chown_vollist = [];
1164
d250604f 1165 PVE::LXC::Config->foreach_mountpoint($settings, sub {
6c871c36
DM
1166 my ($ms, $mountpoint) = @_;
1167
1168 my $volid = $mountpoint->{volume};
1169 my $mp = $mountpoint->{mp};
1170
1171 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1172
e2007ac2 1173 if ($storage && ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/)) {
8ed5ff9d 1174 my ($storeid, $size_gb) = ($1, $2);
6c871c36 1175
8ed5ff9d 1176 my $size_kb = int(${size_gb}*1024) * 1024;
6c871c36
DM
1177
1178 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1179 # fixme: use better naming ct-$vmid-disk-X.raw?
1180
1181 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
8ed5ff9d 1182 if ($size_kb > 0) {
6c871c36 1183 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
8ed5ff9d 1184 undef, $size_kb);
d216e891 1185 format_disk($storecfg, $volid, $rootuid, $rootgid);
6c871c36
DM
1186 } else {
1187 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1188 undef, 0);
d216e891 1189 push @$chown_vollist, $volid;
6c871c36
DM
1190 }
1191 } elsif ($scfg->{type} eq 'zfspool') {
1192
1193 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
8ed5ff9d 1194 undef, $size_kb);
d216e891 1195 push @$chown_vollist, $volid;
2e879877 1196 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
6c871c36 1197
8ed5ff9d 1198 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
d216e891 1199 format_disk($storecfg, $volid, $rootuid, $rootgid);
6c871c36
DM
1200
1201 } elsif ($scfg->{type} eq 'rbd') {
1202
1203 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd};
8ed5ff9d 1204 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
d216e891 1205 format_disk($storecfg, $volid, $rootuid, $rootgid);
6c871c36
DM
1206 } else {
1207 die "unable to create containers on storage type '$scfg->{type}'\n";
1208 }
1209 push @$vollist, $volid;
71c780b9
WB
1210 $mountpoint->{volume} = $volid;
1211 $mountpoint->{size} = $size_kb * 1024;
1b4cf758 1212 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36 1213 } else {
e2007ac2 1214 # use specified/existing volid/dir/device
1b4cf758 1215 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36
DM
1216 }
1217 });
d216e891
WB
1218
1219 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1220 foreach my $volid (@$chown_vollist) {
1221 my $path = PVE::Storage::path($storecfg, $volid, undef);
1222 chown($rootuid, $rootgid, $path);
1223 }
1224 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
6c871c36
DM
1225 };
1226 # free allocated images on error
1227 if (my $err = $@) {
1228 destroy_disks($storecfg, $vollist);
1229 die $err;
1230 }
1231 return $vollist;
1232}
1233
68e8f3c5
DM
1234# bash completion helper
1235
1236sub complete_os_templates {
1237 my ($cmdname, $pname, $cvalue) = @_;
1238
1239 my $cfg = PVE::Storage::config();
1240
9e9bc3a6 1241 my $storeid;
68e8f3c5
DM
1242
1243 if ($cvalue =~ m/^([^:]+):/) {
1244 $storeid = $1;
1245 }
1246
1247 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1248 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1249
1250 my $res = [];
1251 foreach my $id (keys %$data) {
1252 foreach my $item (@{$data->{$id}}) {
1253 push @$res, $item->{volid} if defined($item->{volid});
1254 }
1255 }
1256
1257 return $res;
1258}
1259
68e8f3c5
DM
1260my $complete_ctid_full = sub {
1261 my ($running) = @_;
1262
1263 my $idlist = vmstatus();
1264
1265 my $active_hash = list_active_containers();
1266
1267 my $res = [];
1268
1269 foreach my $id (keys %$idlist) {
1270 my $d = $idlist->{$id};
1271 if (defined($running)) {
1272 next if $d->{template};
1273 next if $running && !$active_hash->{$id};
1274 next if !$running && $active_hash->{$id};
1275 }
1276 push @$res, $id;
1277
1278 }
1279 return $res;
1280};
1281
1282sub complete_ctid {
1283 return &$complete_ctid_full();
1284}
1285
1286sub complete_ctid_stopped {
1287 return &$complete_ctid_full(0);
1288}
1289
1290sub complete_ctid_running {
1291 return &$complete_ctid_full(1);
1292}
1293
c6a605f9
WB
1294sub parse_id_maps {
1295 my ($conf) = @_;
1296
1297 my $id_map = [];
1298 my $rootuid = 0;
1299 my $rootgid = 0;
1300
1301 my $lxc = $conf->{lxc};
1302 foreach my $entry (@$lxc) {
1303 my ($key, $value) = @$entry;
1304 next if $key ne 'lxc.id_map';
1305 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1306 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1307 push @$id_map, [$type, $ct, $host, $length];
1308 if ($ct == 0) {
1309 $rootuid = $host if $type eq 'u';
1310 $rootgid = $host if $type eq 'g';
1311 }
1312 } else {
1313 die "failed to parse id_map: $value\n";
1314 }
1315 }
1316
1317 if (!@$id_map && $conf->{unprivileged}) {
1318 # Should we read them from /etc/subuid?
1319 $id_map = [ ['u', '0', '100000', '65536'],
1320 ['g', '0', '100000', '65536'] ];
1321 $rootuid = $rootgid = 100000;
1322 }
1323
1324 return ($id_map, $rootuid, $rootgid);
1325}
1326
01dce99b
WB
1327sub userns_command {
1328 my ($id_map) = @_;
1329 if (@$id_map) {
1330 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1331 }
1332 return [];
1333}
1334
846a66b0 1335
f76a2828 13361;