]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC/Setup.pm
migrate: also set targetsid for unreferenced disks
[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, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
128 if (@$id_map) {
129 $plugin->{id_map} = $id_map;
130 $plugin->{rootuid} = $rootuid;
131 $plugin->{rootgid} = $rootgid;
132 }
133
134 return $self;
135 }
136
137 # Forks into a chroot and executes $sub
138 sub protected_call {
139 my ($self, $sub) = @_;
140
141 # avoid recursion:
142 return $sub->() if $self->{in_chroot};
143
144 pipe(my $res_in, my $res_out) or die "pipe failed: $!\n";
145
146 my $child = fork();
147 die "fork failed: $!\n" if !defined($child);
148
149 if (!$child) {
150 close($res_in);
151 # avoid recursive forks
152 $self->{in_chroot} = 1;
153 eval {
154 my $rootdir = $self->{rootdir};
155 chroot($rootdir) or die "failed to change root to: $rootdir: $!\n";
156 chdir('/') or die "failed to change to root directory\n";
157 my $res = $sub->();
158 if (defined($res)) {
159 print {$res_out} "$res";
160 $res_out->flush();
161 }
162 };
163 if (my $err = $@) {
164 warn $err;
165 POSIX::_exit(1);
166 }
167 POSIX::_exit(0);
168 }
169 close($res_out);
170 my $result = do { local $/ = undef; <$res_in> };
171 while (waitpid($child, 0) != $child) {}
172 if ($? != 0) {
173 my $method = (caller(1))[3];
174 die "error in setup task $method\n";
175 }
176 return $result;
177 }
178
179 sub template_fixup {
180 my ($self) = @_;
181 $self->protected_call(sub { $self->{plugin}->template_fixup($self->{conf}) });
182 }
183
184 sub setup_network {
185 my ($self) = @_;
186 $self->protected_call(sub { $self->{plugin}->setup_network($self->{conf}) });
187 }
188
189 sub set_hostname {
190 my ($self) = @_;
191 $self->protected_call(sub { $self->{plugin}->set_hostname($self->{conf}) });
192 }
193
194 sub set_dns {
195 my ($self) = @_;
196 $self->protected_call(sub { $self->{plugin}->set_dns($self->{conf}) });
197 }
198
199 sub set_timezone {
200 my ($self) = @_;
201 $self->protected_call(sub { $self->{plugin}->set_timezone($self->{conf}) });
202 }
203
204 sub setup_init {
205 my ($self) = @_;
206 $self->protected_call(sub { $self->{plugin}->setup_init($self->{conf}) });
207 }
208
209 sub set_user_password {
210 my ($self, $user, $pw) = @_;
211 $self->protected_call(sub { $self->{plugin}->set_user_password($self->{conf}, $user, $pw) });
212 }
213
214 my sub generate_ssh_key { # create temporary key in hosts' /run, then read and unlink
215 my ($type, $comment) = @_;
216
217 my $key_id = '';
218 my $keygen_outfunc = sub {
219 if ($_[0] =~ m/^((?:[0-9a-f]{2}:)+[0-9a-f]{2}|SHA256:[0-9a-z+\/]{43})\s+\Q$comment\E$/i) {
220 $key_id = $_[0];
221 }
222 };
223 my $file = "/run/pve/.tmp$$.$type";
224 PVE::Tools::run_command(
225 ['ssh-keygen', '-f', $file, '-t', $type, '-N', '', '-E', 'sha256', '-C', $comment],
226 outfunc => $keygen_outfunc,
227 );
228 my ($private) = (PVE::Tools::file_get_contents($file) =~ /^(.*)$/sg); # untaint
229 my ($public) = (PVE::Tools::file_get_contents("$file.pub") =~ /^(.*)$/sg); # untaint
230 unlink $file, "$file.pub";
231
232 return ($key_id, $private, $public);
233 }
234
235 sub rewrite_ssh_host_keys {
236 my ($self) = @_;
237
238 my $plugin = $self->{plugin};
239
240 my $keynames = $plugin->ssh_host_key_types_to_generate();
241
242 return if ! -d "$self->{rootdir}/etc/ssh" || !$keynames || !scalar(keys $keynames->%*);
243
244 my $hostname = $self->{conf}->{hostname} || 'localhost';
245 $hostname =~ s/\..*$//;
246
247 my $keyfiles = [];
248 for my $keytype (keys $keynames->%*) {
249 my $basename = $keynames->{$keytype};
250 print "Creating SSH host key '$basename' - this may take some time ...\n";
251 my ($id, $private, $public) = generate_ssh_key($keytype, "root\@$hostname");
252 print "done: $id\n";
253
254 push $keyfiles->@*, ["/etc/ssh/$basename", $private, 0600], ["/etc/ssh/$basename.pub", $public, 0644];
255 }
256
257 $self->protected_call(sub { # write them now all to the CTs rootfs at once
258 for my $file ($keyfiles->@*) {
259 $plugin->ct_file_set_contents($file->@*);
260 }
261 });
262 }
263
264 sub pre_start_hook {
265 my ($self) = @_;
266
267 $self->protected_call(sub { $self->{plugin}->pre_start_hook($self->{conf}) });
268 }
269
270 sub post_clone_hook {
271 my ($self, $conf) = @_;
272
273 $self->protected_call(sub { $self->{plugin}->post_clone_hook($conf) });
274 }
275
276 sub post_create_hook {
277 my ($self, $root_password, $ssh_keys) = @_;
278
279 $self->protected_call(sub {
280 $self->{plugin}->post_create_hook($self->{conf}, $root_password, $ssh_keys);
281 });
282 $self->rewrite_ssh_host_keys();
283 }
284
285 sub unified_cgroupv2_support {
286 my ($self) = @_;
287
288 return $self->protected_call(sub { $self->{plugin}->unified_cgroupv2_support() });
289 }
290
291 # os-release(5):
292 # (...) a newline-separated list of environment-like shell-compatible
293 # variable assignments. (...) beyond mere variable assignments, no shell
294 # features are supported (this means variable expansion is explicitly not
295 # supported) (...). Variable assignment values must be enclosed in double or
296 # single quotes *if* they include spaces, semicolons or other special
297 # characters outside of A-Z, a-z, 0-9. Shell special characters ("$", quotes,
298 # backslash, backtick) must be escaped with backslashes (...). All strings
299 # should be in UTF-8 format, and non-printable characters should not be used.
300 # It is not supported to concatenate multiple individually quoted strings.
301 # Lines beginning with "#" shall be ignored as comments.
302 my $parse_os_release = sub {
303 my ($data) = @_;
304 my $variables = {};
305 while (defined($data) && $data =~ /^(.+)$/gm) {
306 next if $1 !~ /^\s*([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;
307 my ($var, $content) = ($1, $2);
308 chomp $content;
309
310 if ($content =~ /^'([^']*)'/) {
311 $variables->{$var} = $1;
312 } elsif ($content =~ /^"((?:[^"\\]|\\.)*)"/) {
313 my $s = $1;
314 $s =~ s/(\\["'`nt\$\\])/"\"$1\""/eeg;
315 $variables->{$var} = $s;
316 } elsif ($content =~ /^([A-Za-z0-9]*)/) {
317 $variables->{$var} = $1;
318 }
319 }
320 return $variables;
321 };
322
323 sub get_ct_os_release {
324 my ($self) = @_;
325
326 my $data = $self->protected_call(sub {
327 if (-f '/etc/os-release') {
328 return PVE::Tools::file_get_contents('/etc/os-release');
329 } elsif (-f '/usr/lib/os-release') {
330 return PVE::Tools::file_get_contents('/usr/lib/os-release');
331 }
332 return undef;
333 });
334
335 return &$parse_os_release($data);
336 }
337
338 1;