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