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