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