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