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