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