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