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