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