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