]> git.proxmox.com Git - aab.git/blame - PVE/AAB.pm
exclude linux-firmware from installed packages
[aab.git] / PVE / AAB.pm
CommitLineData
7b25f331
WB
1package PVE::AAB;
2
3use strict;
4use warnings;
5
6use File::Path;
7use File::Copy;
8use IO::File;
9use IO::Select;
7c20fd82 10use IPC::Open2;
7b25f331
WB
11use IPC::Open3;
12use UUID;
13use Cwd;
14
15my @BASE_PACKAGES = qw(base openssh);
16my @BASE_EXCLUDES = qw(e2fsprogs
17 jfsutils
18 linux
60dbf75e 19 linux-firmware
7b25f331
WB
20 lvm2
21 mdadm
22 netctl
23 pcmciautils
24 reiserfsprogs
25 xfsprogs);
26
27my $PKGDIR = "/var/cache/pacman/pkg";
28
29my ($aablibdir, $fake_init);
30
31sub setup_defaults($) {
32 my ($dir) = @_;
33 $aablibdir = $dir;
34 $fake_init = "$aablibdir/scripts/init.bash";
35}
36
37setup_defaults('/usr/lib/aab');
38
39sub write_file {
40 my ($data, $file, $perm) = @_;
41
42 die "no filename" if !$file;
43 unlink $file;
44
45 my $fh = IO::File->new ($file, O_WRONLY | O_CREAT, $perm) ||
46 die "unable to open file '$file'";
47
48 print $fh $data;
49 $fh->close;
50}
51
52sub copy_file {
53 my ($a, $b) = @_;
54 copy($a, $b) or die "failed to copy $a => $b: $!";
55}
56
57sub rename_file {
58 my ($a, $b) = @_;
59 rename($a, $b) or die "failed to rename $a => $b: $!";
60}
61
62sub symln {
63 my ($a, $b) = @_;
64 symlink($a, $b) or die "failed to symlink $a => $b: $!";
65}
66
67sub logmsg {
68 my $self = shift;
69 print STDERR @_;
70 $self->writelog (@_);
71}
72
73sub writelog {
74 my $self = shift;
75 my $fd = $self->{logfd};
76 print $fd @_;
77}
78
79sub read_config {
80 my ($filename) = @_;
81
82 my $res = {};
83
84 my $fh = IO::File->new ("<$filename") || return $res;
85 my $rec = '';
86
87 while (defined (my $line = <$fh>)) {
88 next if $line =~ m/^\#/;
89 next if $line =~ m/^\s*$/;
90 $rec .= $line;
91 };
92
93 close ($fh);
94
95 chomp $rec;
96 $rec .= "\n";
97
98 while ($rec) {
99 if ($rec =~ s/^Description:\s*([^\n]*)(\n\s+.*)*$//si) {
100 $res->{headline} = $1;
101 chomp $res->{headline};
102 my $long = $2;
103 $long =~ s/^\s+/ /;
104 $res->{description} = $long;
b8f914c1 105 chomp $res->{description};
7b25f331
WB
106 } elsif ($rec =~ s/^([^:]+):\s*(.*\S)\s*\n//) {
107 my ($key, $value) = (lc ($1), $2);
108 if ($key eq 'source' || $key eq 'mirror') {
109 push @{$res->{$key}}, $value;
110 } else {
111 die "duplicate key '$key'\n" if defined ($res->{$key});
112 $res->{$key} = $value;
113 }
114 } else {
115 die "unable to parse config file: $rec";
116 }
117 }
118
119 die "unable to parse config file" if $rec;
120
0cff4ef1
WB
121 $res->{architecture} = 'amd64' if $res->{architecture} eq 'x86_64';
122
7b25f331
WB
123 return $res;
124}
125
126sub new {
127 my ($class, $config) = @_;
128
129 $config = read_config ('aab.conf') if !$config;
130 my $version = $config->{version};
131 die "no 'version' specified\n" if !$version;
132 die "no 'section' specified\n" if !$config->{section};
133 die "no 'description' specified\n" if !$config->{headline};
134 die "no 'maintainer' specified\n" if !$config->{maintainer};
135
136 my $name = $config->{name} || die "no 'name' specified\n";
b8f914c1 137 $name =~ m/^[a-z][0-9a-z\-\*\.]+$/ ||
7b25f331
WB
138 die "illegal characters in name '$name'\n";
139
140 my $targetname;
141 if ($name =~ m/^archlinux/) {
142 $targetname = "${name}_${version}_$config->{architecture}";
143 } else {
144 $targetname = "archlinux-${name}_${version}_$config->{architecture}";
145 }
146
147 my $self = { logfile => 'logfile',
148 config => $config,
149 targetname => $targetname,
150 incl => [@BASE_PACKAGES],
151 excl => [@BASE_EXCLUDES],
152 };
153
154 $self->{logfd} = IO::File->new($self->{logfile}, O_WRONLY | O_APPEND | O_CREAT)
155 or die "unable to open log file";
156
157 bless $self, $class;
158
159 $self->__allocate_ve();
160
161 return $self;
162}
163
164sub __sample_config {
165 my ($self) = @_;
166
167 my $arch = $self->{config}->{architecture};
168
169 return <<"CFG";
170lxc.arch = $arch
171lxc.include = /usr/share/lxc/config/archlinux.common.conf
87fbfb3a
TL
172lxc.uts.name = localhost
173lxc.rootfs.path = $self->{rootfs}
7b25f331
WB
174lxc.mount.entry = $self->{pkgcache} $self->{pkgdir} none bind 0 0
175CFG
176}
177
178sub __allocate_ve {
179 my ($self) = @_;
180
181 my $cid;
182 if (my $fd = IO::File->new(".veid")) {
183 $cid = <$fd>;
184 chomp $cid;
185 close ($fd);
186 }
187
188
189 $self->{working_dir} = getcwd;
190 $self->{veconffile} = "$self->{working_dir}/config";
191 $self->{rootfs} = "$self->{working_dir}/rootfs";
192 $self->{pkgdir} = "$self->{working_dir}/rootfs/$PKGDIR";
193 $self->{pkgcache} = "$self->{working_dir}/pkgcache";
194 $self->{'pacman.conf'} = "$self->{working_dir}/pacman.conf";
195
196 if ($cid) {
197 $self->{veid} = $cid;
198 return $cid;
199 }
200
201 my $uuid;
202 my $uuid_str;
203 UUID::generate($uuid);
204 UUID::unparse($uuid, $uuid_str);
205 $self->{veid} = $uuid_str;
206
207 my $fd = IO::File->new (">.veid") ||
208 die "unable to write '.veid'\n";
209 print $fd "$self->{veid}\n";
210 close ($fd);
211 $self->logmsg("allocated VE $self->{veid}\n");
212}
213
214sub initialize {
215 my ($self) = @_;
216
217 my $config = $self->{config};
218
219 $self->{logfd} = IO::File->new($self->{logfile}, O_WRONLY | O_TRUNC | O_CREAT)
220 or die "unable to open log file";
221
222 my $cdata = $self->__sample_config();
223
224 my $fh = IO::File->new($self->{veconffile}, O_WRONLY|O_CREAT|O_EXCL) ||
225 die "unable to write lxc config file '$self->{veconffile}' - $!";
226 print $fh $cdata;
227 close ($fh);
228
229 if (!$config->{source} && !$config->{mirror}) {
230 die "no sources/mirrors specified";
231 }
232
233 $config->{source} //= [];
234 $config->{mirror} //= [];
235
236 my $servers = "Server = "
237 . join("\nServer = ", @{$config->{source}}, @{$config->{mirror}})
238 . "\n";
239
240 $fh = IO::File->new($self->{'pacman.conf'}, O_WRONLY|O_CREAT|O_EXCL) ||
241 die "unable to write pacman config file $self->{'pacman.conf'} - $!";
0cff4ef1
WB
242 my $arch = $config->{architecture};
243 $arch = 'x86_64' if $arch eq 'amd64';
7b25f331
WB
244 print $fh <<"EOF";
245[options]
246HoldPkg = pacman glibc
0cff4ef1 247Architecture = $arch
7b25f331
WB
248CheckSpace
249SigLevel = Never
250
251[core]
252$servers
253[extra]
254$servers
255[community]
256$servers
7b25f331
WB
257EOF
258
4eaaed91
WB
259 if ($config->{architecture} eq 'x86_64') {
260 print $fh "[multilib]\n$servers\n";
261 }
262
7b25f331
WB
263 mkdir $self->{rootfs} || die "unable to create rootfs - $!";
264
265 $self->logmsg("configured VE $self->{veid}\n");
266}
267
268sub ve_status {
269 my ($self) = @_;
270
271 my $veid = $self->{veid};
272
273 my $res = { running => 0 };
274
275 $res->{exist} = 1 if -d "$self->{rootfs}/usr";
276
277 my $filename = "/proc/net/unix";
278
279 # similar test is used by lcxcontainers.c: list_active_containers
280 my $fh = IO::File->new ($filename, "r");
281 return $res if !$fh;
282
283 while (defined(my $line = <$fh>)) {
284 if ($line =~ m/^[a-f0-9]+:\s\S+\s\S+\s\S+\s\S+\s\S+\s\d+\s(\S+)$/) {
285 my $path = $1;
286 if ($path =~ m!^@/\S+/$veid/command$!) {
287 $res->{running} = 1;
288 }
289 }
290 }
291 close($fh);
b8f914c1 292
7b25f331
WB
293 return $res;
294}
295
296sub ve_destroy {
297 my ($self) = @_;
298
299 my $veid = $self->{veid}; # fixme
300
301 my $vestat = $self->ve_status();
302 if ($vestat->{running}) {
303 $self->stop_container();
304 }
305
306 rmtree $self->{rootfs};
307 unlink $self->{veconffile};
308}
309
310sub ve_init {
311 my ($self) = @_;
312
313
314 my $veid = $self->{veid};
d43d058d 315 my $conffile = $self->{veconffile};
7b25f331
WB
316
317 $self->logmsg ("initialize VE $veid\n");
318
319 my $vestat = $self->ve_status();
320 if ($vestat->{running}) {
d43d058d 321 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
b8f914c1 322 }
7b25f331
WB
323
324 rmtree $self->{rootfs};
325 mkpath $self->{rootfs};
326}
327
328sub ve_command {
329 my ($self, $cmd, $input) = @_;
330
331 my $veid = $self->{veid};
d43d058d 332 my $conffile = $self->{veconffile};
7b25f331
WB
333
334 if (ref ($cmd) eq 'ARRAY') {
d43d058d 335 unshift @$cmd, 'lxc-attach', '-n', $veid, '--rcfile', $conffile,'--clear-env', '--';
7b25f331
WB
336 $self->run_command ($cmd, $input);
337 } else {
d43d058d 338 $self->run_command ("lxc-attach -n $veid --rcfile $conffile --clear-env -- $cmd", $input);
7b25f331
WB
339 }
340}
341
342sub ve_exec {
343 my ($self, @cmd) = @_;
344
345 my $veid = $self->{veid};
d43d058d 346 my $conffile = $self->{veconffile};
7b25f331
WB
347
348 my $reader;
d43d058d 349 my $pid = open2($reader, "<&STDIN", 'lxc-attach', '-n', $veid, '--rcfile', $conffile, '--', @cmd)
7b25f331
WB
350 or die "unable to exec command";
351
352 while (defined (my $line = <$reader>)) {
353 $self->logmsg ($line);
354 }
355
356 waitpid ($pid, 0);
357 my $rc = $? >> 8;
358
359 die "ve_exec failed - status $rc\n" if $rc != 0;
360}
361
362sub run_command {
363 my ($self, $cmd, $input, $getoutput) = @_;
364
365 my $reader = IO::File->new();
366 my $writer = IO::File->new();
367 my $error = IO::File->new();
368
369 my $orig_pid = $$;
370
371 my $cmdstr = ref ($cmd) eq 'ARRAY' ? join (' ', @$cmd) : $cmd;
372
373 my $pid;
374 eval {
375 if (ref ($cmd) eq 'ARRAY') {
376 $pid = open3 ($writer, $reader, $error, @$cmd) || die $!;
377 } else {
378 $pid = open3 ($writer, $reader, $error, $cmdstr) || die $!;
379 }
380 };
381
382 my $err = $@;
383
384 # catch exec errors
385 if ($orig_pid != $$) {
386 $self->logmsg ("ERROR: command '$cmdstr' failed - fork failed\n");
b8f914c1
OB
387 POSIX::_exit (1);
388 kill ('KILL', $$);
7b25f331
WB
389 }
390
391 die $err if $err;
392
393 print $writer $input if defined $input;
394 close $writer;
395
396 my $select = new IO::Select;
397 $select->add ($reader);
398 $select->add ($error);
399
400 my $res = '';
401 my $logfd = $self->{logfd};
402
403 while ($select->count) {
404 my @handles = $select->can_read ();
405
406 foreach my $h (@handles) {
407 my $buf = '';
408 my $count = sysread ($h, $buf, 4096);
409 if (!defined ($count)) {
410 waitpid ($pid, 0);
411 die "command '$cmdstr' failed: $!";
412 }
413 $select->remove ($h) if !$count;
414
415 print $logfd $buf;
416
417 $res .= $buf if $getoutput;
418 }
419 }
420
421 waitpid ($pid, 0);
422 my $ec = ($? >> 8);
423
424 die "command '$cmdstr' failed with exit code $ec\n" if $ec;
425
426 return $res;
427}
428
429sub start_container {
430 my ($self) = @_;
431 my $veid = $self->{veid};
432 $self->run_command(['lxc-start', '-n', $veid, '-f', $self->{veconffile}, '/usr/bin/aab_fake_init']);
433}
434
435sub stop_container {
436 my ($self) = @_;
437 my $veid = $self->{veid};
d43d058d
WB
438 my $conffile = $self->{veconffile};
439 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
7b25f331
WB
440}
441
442sub pacman_command {
443 my ($self) = @_;
444 my $root = $self->{rootfs};
445 return ('/usr/bin/pacman',
446 '--root', $root,
5f96733f 447 '--config', $self->{'pacman.conf'},
7b25f331
WB
448 '--cachedir', $self->{pkgcache},
449 '--noconfirm');
450}
451
452sub cache_packages {
453 my ($self, $packages) = @_;
454 my $root = $self->{rootfs};
455
456 my @pacman = $self->pacman_command();
457 $self->run_command([@pacman, '-Sw', '--', @$packages]);
458}
459
460sub bootstrap {
461 my ($self, $include, $exclude) = @_;
462 my $root = $self->{rootfs};
463
464 my @pacman = $self->pacman_command();
465
466 print "Fetching package database...\n";
467 mkpath $self->{pkgcache};
468 mkpath $self->{pkgdir};
469 mkpath "$root/var/lib/pacman";
b8f914c1 470 $self->run_command([@pacman, '-Syy']);
7b25f331
WB
471
472 print "Figuring out what to install...\n";
473 my $incl = { map { $_ => 1 } @{$self->{incl}} };
474 my $excl = { map { $_ => 1 } @{$self->{excl}} };
475
476 foreach my $addinc (@$include) {
477 $incl->{$addinc} = 1;
478 delete $excl->{$addinc};
479 }
480 foreach my $addexc (@$exclude) {
481 $excl->{$addexc} = 1;
482 delete $incl->{$addexc};
483 }
484
485 my $expand = sub {
486 my ($lst) = @_;
487 foreach my $inc (keys %$lst) {
488 my $group;
489 eval { $group = $self->run_command([@pacman, '-Sqg', $inc], undef, 1); };
490 if ($group && !$@) {
491 # add the group
492 delete $lst->{$inc};
493 $lst->{$_} = 1 foreach split(/\s+/, $group);
494 }
495 }
496 };
497
498 $expand->($incl);
499 $expand->($excl);
500
501 my $packages = [ grep { !$excl->{$_} } keys %$incl ];
502
503 print "Setting up basic environment...\n";
504 mkpath "$root/etc";
505 mkpath "$root/usr/bin";
506
507 my $data = "# UNCONFIGURED FSTAB FOR BASE SYSTEM\n";
508 write_file ($data, "$root/etc/fstab", 0644);
509
510 write_file ("", "$root/etc/resolv.conf", 0644);
511 write_file("localhost\n", "$root/etc/hostname", 0644);
512 $self->run_command(['install', '-m0755', $fake_init, "$root/usr/bin/aab_fake_init"]);
513
514 unlink "$root/etc/localtime";
515 symln '/usr/share/zoneinfo/UTC', "$root/etc/localtime";
516
517 print "Caching packages...\n";
518 $self->cache_packages($packages);
519 #$self->copy_packages();
520
521 print "Installing package manager and essentials...\n";
522 # inetutils for 'hostname' for our init
523 $self->run_command([@pacman, '-S', 'pacman', 'inetutils', 'archlinux-keyring']);
524
525 print "Setting up pacman for installation from cache...\n";
526 my $file = "$root/etc/pacman.d/mirrorlist";
527 my $backup = "${file}.aab_orig";
528 if (!-f $backup) {
529 rename_file($file, $backup);
530 write_file("Server = file://$PKGDIR\n", $file);
531 }
532
533 print "Populating keyring...\n";
766f0fa3 534 $self->populate_keyring();
7b25f331
WB
535
536 print "Starting container...\n";
537 $self->start_container();
538
539 print "Installing packages...\n";
540 $self->ve_command(['pacman', '-S', '--needed', '--noconfirm', '--', @$packages]);
541}
542
766f0fa3
WB
543sub populate_keyring {
544 my ($self) = @_;
545 my $root = $self->{rootfs};
546
547 # devices needed for gnupg to function:
548 my $devs = {
549 '/dev/null' => ['c', '1', '3'],
550 '/dev/random' => ['c', '1', '9'], # fake /dev/random (really urandom)
551 '/dev/urandom' => ['c', '1', '9'],
552 '/dev/tty' => ['c', '5', '0'],
553 };
554
555 my $cleanup_dev = sub {
556 # remove temporary device files
557 unlink "${root}$_" foreach keys %$devs;
558 };
559 local $SIG{INT} = $SIG{TERM} = $cleanup_dev;
560
561 # at least /dev/null exists as regular file after installing the filesystem package,
562 # and we want to replace /dev/random, so delete devices first
563 &$cleanup_dev();
564
565 foreach my $dev (keys %$devs) {
566 my ($type, $major, $minor) = @{$devs->{$dev}};
567 system('mknod', "${root}${dev}", $type, $major, $minor);
568 }
569
570 # generate weak master key and populate the keyring
571 system('unshare', '--fork', '--pid', 'chroot', "$root", 'pacman-key', '--init') == 0
572 or die "failed to initialize keyring: $?";
573 system('unshare', '--fork', '--pid', 'chroot', "$root", 'pacman-key', '--populate') == 0
574 or die "failed to populate keyring: $?";
575
576 &$cleanup_dev();
577 # reset to original state
578 system('touch', "$root/dev/null");
579}
580
7b25f331
WB
581sub install {
582 my ($self, $pkglist) = @_;
583
584 $self->cache_packages($pkglist);
585 $self->ve_command(['pacman', '-S', '--needed', '--noconfirm', '--', @$pkglist]);
586}
587
588sub write_config {
589 my ($self, $filename, $size) = @_;
590
591 my $config = $self->{config};
592
593 my $data = '';
594
595 $data .= "Name: $config->{name}\n";
596 $data .= "Version: $config->{version}\n";
597 $data .= "Type: lxc\n";
598 $data .= "OS: archlinux\n";
599 $data .= "Section: $config->{section}\n";
600 $data .= "Maintainer: $config->{maintainer}\n";
601 $data .= "Architecture: $config->{architecture}\n";
b65bfe8c 602 $data .= "Infopage: https://www.archlinux.org\n";
7b25f331
WB
603 $data .= "Installed-Size: $size\n";
604
605 # optional
606 $data .= "Infopage: $config->{infopage}\n" if $config->{infopage};
607 $data .= "ManageUrl: $config->{manageurl}\n" if $config->{manageurl};
608 $data .= "Certified: $config->{certified}\n" if $config->{certified};
609
610 # description
611 $data .= "Description: $config->{headline}\n";
612 $data .= "$config->{description}\n" if $config->{description};
613
614 write_file ($data, $filename, 0644);
615}
616
617sub finalize {
618 my ($self) = @_;
619 my $rootdir = $self->{rootfs};
620
621 print "Stopping container...\n";
622 $self->stop_container();
623
624 print "Rolling back mirrorlist changes...\n";
625 my $file = "$rootdir/etc/pacman.d/mirrorlist";
626 unlink $file;
627 rename_file($file.'.aab_orig', $file);
628
e61d6533
WB
629 print "Removing weak temporary pacman keyring...\n";
630 rmtree("$rootdir/etc/pacman.d/gnupg");
631
7b25f331
WB
632 my $sizestr = $self->run_command("du -sm $rootdir", undef, 1);
633 my $size;
634 if ($sizestr =~ m/^(\d+)\s+\Q$rootdir\E$/) {
635 $size = $1;
636 } else {
637 die "unable to detect size\n";
638 }
639 $self->logmsg ("$size MB\n");
640
641 $self->write_config ("$rootdir/etc/appliance.info", $size);
642
643 $self->logmsg ("creating final appliance archive\n");
644
645 my $target = "$self->{targetname}.tar";
646 unlink $target;
647 unlink "$target.gz";
648
649 $self->run_command ("tar cpf $target --numeric-owner -C '$rootdir' ./etc/appliance.info");
650 $self->run_command ("tar rpf $target --numeric-owner -C '$rootdir' --exclude ./etc/appliance.info .");
651 $self->run_command ("gzip $target");
652}
653
654sub enter {
655 my ($self) = @_;
656 my $veid = $self->{veid};
d43d058d 657 my $conffile = $self->{veconffile};
7b25f331
WB
658
659 my $vestat = $self->ve_status();
660 if (!$vestat->{exist}) {
661 $self->logmsg ("Please create the appliance first (bootstrap)");
662 return;
663 }
664
665 if (!$vestat->{running}) {
666 $self->start_container();
667 }
668
d43d058d 669 system ("lxc-attach -n $veid --rcfile $conffile --clear-env");
7b25f331
WB
670}
671
672sub clean {
673 my ($self, $all) = @_;
674
675 unlink $self->{logfile};
676 unlink $self->{'pacman.conf'};
677 $self->ve_destroy();
678 unlink '.veid';
dfb4fbaa
SI
679 unlink $self->{veconffile};
680
7b25f331
WB
681 rmtree $self->{pkgcache} if $all;
682}
683
6841;