]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC/Setup.pm
b6c5b17187c26be62a7269dfc76c2ed53cfd89d7
[pve-container.git] / src / PVE / LXC / Setup.pm
1 package PVE::LXC::Setup;
2
3 use strict;
4 use warnings;
5
6 use POSIX;
7 use Cwd 'abs_path';
8
9 use PVE::Tools;
10
11 use PVE::LXC::Setup::Alpine;
12 use PVE::LXC::Setup::ArchLinux;
13 use PVE::LXC::Setup::CentOS;
14 use PVE::LXC::Setup::Debian;
15 use PVE::LXC::Setup::Devuan;
16 use PVE::LXC::Setup::Fedora;
17 use PVE::LXC::Setup::Gentoo;
18 use PVE::LXC::Setup::SUSE;
19 use PVE::LXC::Setup::Ubuntu;
20
21 my $plugins = {
22 alpine => 'PVE::LXC::Setup::Alpine',
23 archlinux => 'PVE::LXC::Setup::ArchLinux',
24 centos => 'PVE::LXC::Setup::CentOS',
25 debian => 'PVE::LXC::Setup::Debian',
26 devuan => 'PVE::LXC::Setup::Devuan',
27 fedora => 'PVE::LXC::Setup::Fedora',
28 gentoo => 'PVE::LXC::Setup::Gentoo',
29 opensuse => 'PVE::LXC::Setup::SUSE',
30 ubuntu => 'PVE::LXC::Setup::Ubuntu',
31 };
32
33 # a map to allow supporting related distro flavours
34 my $plugin_alias = {
35 'opensuse-leap' => 'opensuse',
36 'opensuse-tumbleweed' => 'opensuse',
37 arch => 'archlinux',
38 sles => 'opensuse',
39 };
40
41 my $autodetect_type = sub {
42 my ($self, $rootdir, $os_release) = @_;
43
44 if (my $id = $os_release->{ID}) {
45 return $id if $plugins->{$id};
46 return $plugin_alias->{$id} if $plugin_alias->{$id};
47 warn "unknown ID '$id' in /etc/os-release file, trying fallback detection\n";
48 }
49
50 # fallback compatibility checks
51
52 my $lsb_fn = "$rootdir/etc/lsb-release";
53 if (-f $lsb_fn) {
54 my $data = PVE::Tools::file_get_contents($lsb_fn);
55 if ($data =~ m/^DISTRIB_ID=Ubuntu$/im) {
56 return 'ubuntu';
57 }
58 }
59
60 if (-f "$rootdir/etc/debian_version") {
61 return "debian";
62 } elsif (-f "$rootdir/etc/devuan_version") {
63 return "devuan";
64 } elsif (-f "$rootdir/etc/SuSE-brand" || -f "$rootdir/etc/SuSE-release") {
65 return "opensuse";
66 } elsif (-f "$rootdir/etc/fedora-release") {
67 return "fedora";
68 } elsif (-f "$rootdir/etc/centos-release" || -f "$rootdir/etc/redhat-release") {
69 return "centos";
70 } elsif (-f "$rootdir/etc/arch-release") {
71 return "archlinux";
72 } elsif (-f "$rootdir/etc/alpine-release") {
73 return "alpine";
74 } elsif (-f "$rootdir/etc/gentoo-release") {
75 return "gentoo";
76 } elsif (-f "$rootdir/etc/os-release") {
77 die "unable to detect OS distribution\n";
78 } else {
79 warn "/etc/os-release file not found and autodetection failed, falling back to 'unmanaged'\n";
80 return "unmanaged";
81 }
82 };
83
84 sub new {
85 my ($class, $conf, $rootdir, $type) = @_;
86
87 die "no root directory\n" if !$rootdir || $rootdir eq '/';
88
89 my $self = bless { conf => $conf, rootdir => $rootdir}, $class;
90
91 my $os_release = $self->get_ct_os_release();
92
93 if ($conf->{ostype} && $conf->{ostype} eq 'unmanaged') {
94 return $self;
95 } elsif (!defined($type)) {
96 # try to autodetect type
97 $type = &$autodetect_type($self, $rootdir, $os_release);
98 my $expected_type = $conf->{ostype} || $type;
99
100 if ($type ne $expected_type) {
101 warn "WARNING: /etc not present in CT, is the rootfs mounted?\n"
102 if ! -e "$rootdir/etc";
103 warn "got unexpected ostype ($type != $expected_type)\n"
104 }
105 }
106
107 if ($type eq 'unmanaged') {
108 $conf->{ostype} = $type;
109 return $self;
110 }
111
112 my $plugin_class = $plugins->{$type} || die "no such OS type '$type'\n";
113
114 my $plugin = $plugin_class->new($conf, $rootdir, $os_release);
115 $self->{plugin} = $plugin;
116 $self->{in_chroot} = 0;
117
118 # Cache some host files we need access to:
119 $plugin->{host_resolv_conf} = PVE::INotify::read_file('resolvconf');
120 $plugin->{host_localtime} = abs_path('/etc/localtime');
121
122 # pass on user namespace information:
123 my ($id_map, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
124 if (@$id_map) {
125 $plugin->{id_map} = $id_map;
126 $plugin->{rootuid} = $rootuid;
127 $plugin->{rootgid} = $rootgid;
128 }
129
130 return $self;
131 }
132
133 # Forks into a chroot and executes $sub
134 sub protected_call {
135 my ($self, $sub) = @_;
136
137 # avoid recursion:
138 return $sub->() if $self->{in_chroot};
139
140 pipe(my $res_in, my $res_out) or die "pipe failed: $!\n";
141
142 my $child = fork();
143 die "fork failed: $!\n" if !defined($child);
144
145 if (!$child) {
146 close($res_in);
147 # avoid recursive forks
148 $self->{in_chroot} = 1;
149 eval {
150 my $rootdir = $self->{rootdir};
151 chroot($rootdir) or die "failed to change root to: $rootdir: $!\n";
152 chdir('/') or die "failed to change to root directory\n";
153 my $res = $sub->();
154 if (defined($res)) {
155 print {$res_out} "$res";
156 $res_out->flush();
157 }
158 };
159 if (my $err = $@) {
160 warn $err;
161 POSIX::_exit(1);
162 }
163 POSIX::_exit(0);
164 }
165 close($res_out);
166 my $result = do { local $/ = undef; <$res_in> };
167 while (waitpid($child, 0) != $child) {}
168 if ($? != 0) {
169 my $method = (caller(1))[3];
170 die "error in setup task $method\n";
171 }
172 return $result;
173 }
174
175 sub template_fixup {
176 my ($self) = @_;
177
178 return if !$self->{plugin}; # unmanaged
179
180 $self->protected_call(sub { $self->{plugin}->template_fixup($self->{conf}) });
181 }
182
183 sub setup_network {
184 my ($self) = @_;
185
186 return if !$self->{plugin}; # unmanaged
187
188 $self->protected_call(sub { $self->{plugin}->setup_network($self->{conf}) });
189 }
190
191 sub set_hostname {
192 my ($self) = @_;
193
194 return if !$self->{plugin}; # unmanaged
195
196 $self->protected_call(sub { $self->{plugin}->set_hostname($self->{conf}) });
197 }
198
199 sub set_dns {
200 my ($self) = @_;
201
202 return if !$self->{plugin}; # unmanaged
203
204 $self->protected_call(sub { $self->{plugin}->set_dns($self->{conf}) });
205 }
206
207 sub set_timezone {
208 my ($self) = @_;
209
210 return if !$self->{plugin}; # unmanaged
211
212 $self->protected_call(sub { $self->{plugin}->set_timezone($self->{conf}) });
213 }
214
215 sub setup_init {
216 my ($self) = @_;
217
218 return if !$self->{plugin}; # unmanaged
219
220 $self->protected_call(sub { $self->{plugin}->setup_init($self->{conf}) });
221 }
222
223 sub set_user_password {
224 my ($self, $user, $pw) = @_;
225
226 return if !$self->{plugin}; # unmanaged
227
228 $self->protected_call(sub { $self->{plugin}->set_user_password($self->{conf}, $user, $pw) });
229 }
230
231 my sub generate_ssh_key { # create temporary key in hosts' /run, then read and unlink
232 my ($type, $comment) = @_;
233
234 my $key_id = '';
235 my $keygen_outfunc = sub {
236 if ($_[0] =~ m/^((?:[0-9a-f]{2}:)+[0-9a-f]{2}|SHA256:[0-9a-z+\/]{43})\s+\Q$comment\E$/i) {
237 $key_id = $_[0];
238 }
239 };
240 my $file = "/run/pve/.tmp$$.$type";
241 PVE::Tools::run_command(
242 ['ssh-keygen', '-f', $file, '-t', $type, '-N', '', '-E', 'sha256', '-C', $comment],
243 outfunc => $keygen_outfunc,
244 );
245 my ($private) = (PVE::Tools::file_get_contents($file) =~ /^(.*)$/sg); # untaint
246 my ($public) = (PVE::Tools::file_get_contents("$file.pub") =~ /^(.*)$/sg); # untaint
247 unlink $file, "$file.pub";
248
249 return ($key_id, $private, $public);
250 }
251
252 sub rewrite_ssh_host_keys {
253 my ($self) = @_;
254
255 return if !$self->{plugin}; # unmanaged
256
257 my $conf = $self->{conf};
258 my $plugin = $self->{plugin};
259 my $rootdir = $self->{rootdir};
260
261 return if ! -d "$rootdir/etc/ssh";
262
263 my $keynames = {
264 rsa => 'ssh_host_rsa_key',
265 dsa => 'ssh_host_dsa_key',
266 ecdsa => 'ssh_host_ecdsa_key',
267 ed25519 => 'ssh_host_ed25519_key',
268 };
269
270 my $hostname = $conf->{hostname} || 'localhost';
271 $hostname =~ s/\..*$//;
272
273 my $keyfiles = [];
274 for my $keytype (keys $keynames->%*) {
275 my $basename = $keynames->{$keytype};
276 print "Creating SSH host key '$basename' - this may take some time ...\n";
277 my ($id, $private, $public) = generate_ssh_key($keytype, "root\@$hostname");
278 print "done: $id\n";
279
280 push $keyfiles->@*, ["/etc/ssh/$basename", $private, 0600], ["/etc/ssh/$basename.pub", $public, 0644];
281 }
282
283 $self->protected_call(sub { # write them now all to the CTs rootfs at once
284 for my $file ($keyfiles->@*) {
285 $plugin->ct_file_set_contents($file->@*);
286 }
287 });
288 }
289
290 my $container_emulator_path = {
291 'amd64' => '/usr/bin/qemu-x86_64-static',
292 'arm64' => '/usr/bin/qemu-aarch64-static',
293 };
294
295 sub pre_start_hook {
296 my ($self) = @_;
297
298 return if !$self->{plugin}; # unmanaged
299
300 my $host_arch = PVE::Tools::get_host_arch();
301
302 # containers use different architecture names
303 if ($host_arch eq 'x86_64') {
304 $host_arch = 'amd64';
305 } elsif ($host_arch eq 'aarch64') {
306 $host_arch = 'arm64';
307 } else {
308 die "unsupported host architecture '$host_arch'\n";
309 }
310
311 my $container_arch = $self->{conf}->{arch};
312
313 $container_arch = 'amd64' if $container_arch eq 'i386'; # always use 64 bit version
314 $container_arch = 'arm64' if $container_arch eq 'armhf'; # always use 64 bit version
315
316 my $emul;
317 my $emul_data;
318
319 if ($host_arch ne $container_arch) {
320 if ($emul = $container_emulator_path->{$container_arch}) {
321 $emul_data = PVE::Tools::file_get_contents($emul, 10*1024*1024) if -f $emul;
322 }
323 }
324
325 my $code = sub {
326 if ($emul && $emul_data) {
327 $self->{plugin}->ct_file_set_contents($emul, $emul_data, 0755);
328 }
329 # Create /fastboot to skip run fsck
330 $self->{plugin}->ct_file_set_contents('/fastboot', '');
331
332 $self->{plugin}->pre_start_hook($self->{conf});
333 };
334 $self->protected_call($code);
335 }
336
337 sub post_clone_hook {
338 my ($self, $conf) = @_;
339
340 $self->protected_call(sub { $self->{plugin}->post_clone_hook($conf) });
341 }
342
343 sub post_create_hook {
344 my ($self, $root_password, $ssh_keys) = @_;
345
346 return if !$self->{plugin}; # unmanaged
347
348 $self->protected_call(sub {
349 $self->{plugin}->post_create_hook($self->{conf}, $root_password, $ssh_keys);
350 });
351 $self->rewrite_ssh_host_keys();
352 }
353
354 sub unified_cgroupv2_support {
355 my ($self) = @_;
356
357 $self->protected_call(sub { $self->{plugin}->unified_cgroupv2_support() });
358 }
359
360 # os-release(5):
361 # (...) a newline-separated list of environment-like shell-compatible
362 # variable assignments. (...) beyond mere variable assignments, no shell
363 # features are supported (this means variable expansion is explicitly not
364 # supported) (...). Variable assignment values must be enclosed in double or
365 # single quotes *if* they include spaces, semicolons or other special
366 # characters outside of A-Z, a-z, 0-9. Shell special characters ("$", quotes,
367 # backslash, backtick) must be escaped with backslashes (...). All strings
368 # should be in UTF-8 format, and non-printable characters should not be used.
369 # It is not supported to concatenate multiple individually quoted strings.
370 # Lines beginning with "#" shall be ignored as comments.
371 my $parse_os_release = sub {
372 my ($data) = @_;
373 my $variables = {};
374 while (defined($data) && $data =~ /^(.+)$/gm) {
375 next if $1 !~ /^\s*([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;
376 my ($var, $content) = ($1, $2);
377 chomp $content;
378
379 if ($content =~ /^'([^']*)'/) {
380 $variables->{$var} = $1;
381 } elsif ($content =~ /^"((?:[^"\\]|\\.)*)"/) {
382 my $s = $1;
383 $s =~ s/(\\["'`nt\$\\])/"\"$1\""/eeg;
384 $variables->{$var} = $s;
385 } elsif ($content =~ /^([A-Za-z0-9]*)/) {
386 $variables->{$var} = $1;
387 }
388 }
389 return $variables;
390 };
391
392 sub get_ct_os_release {
393 my ($self) = @_;
394
395 my $data = $self->protected_call(sub {
396 if (-f '/etc/os-release') {
397 return PVE::Tools::file_get_contents('/etc/os-release');
398 } elsif (-f '/usr/lib/os-release') {
399 return PVE::Tools::file_get_contents('/usr/lib/os-release');
400 }
401 return undef;
402 });
403
404 return &$parse_os_release($data);
405 }
406
407 1;