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