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