]> git.proxmox.com Git - dab.git/blob - PVE/DAB.pm
deprecate old releases
[dab.git] / PVE / DAB.pm
1 package PVE::DAB;
2
3 use strict;
4 use warnings;
5
6 use Cwd;
7 use File::Basename;
8 use File::Path;
9 use IO::File;
10 use IO::Select;
11 use IPC::Open2;
12 use IPC::Open3;
13 use POSIX qw (LONG_MAX);
14 use UUID;
15
16 # fixme: lock container ?
17
18 my $dablibdir = "/usr/lib/dab";
19 my $devicetar = "$dablibdir/devices.tar.gz";
20 my $default_env = "$dablibdir/scripts/defenv";
21 my $fake_init = "$dablibdir/scripts/init.pl";
22 my $script_ssh_init = "$dablibdir/scripts/ssh_gen_host_keys";
23 my $script_mysql_randompw = "$dablibdir/scripts/mysql_randompw";
24 my $script_init_urandom = "$dablibdir/scripts/init_urandom";
25
26 my $postfix_main_cf = <<EOD;
27 # See /usr/share/postfix/main.cf.dist for a commented, more complete version
28
29 smtpd_banner = \$myhostname ESMTP \$mail_name (Debian/GNU)
30 biff = no
31
32 # appending .domain is the MUA's job.
33 append_dot_mydomain = no
34
35 # Uncomment the next line to generate "delayed mail" warnings
36 #delay_warning_time = 4h
37
38 alias_maps = hash:/etc/aliases
39 alias_database = hash:/etc/aliases
40 mydestination = \$myhostname, localhost.\$mydomain, localhost
41 relayhost =
42 mynetworks = 127.0.0.0/8
43 inet_interfaces = loopback-only
44 recipient_delimiter = +
45
46 compatibility_level = 2
47
48 EOD
49
50 # produce apt compatible filenames (/var/lib/apt/lists)
51 sub __url_to_filename {
52 my $url = shift;
53
54 $url =~ s|^\S+://||;
55 $url =~ s|_|%5f|g;
56 $url =~ s|/|_|g;
57
58 return $url;
59 }
60
61 # defaults:
62 # origin: debian
63 # flags:
64 # systemd: true (except for devuan ostypes)
65 my $supported_suites = {
66 'bookworm' => {
67 ostype => "debian-12",
68 },
69 'bullseye' => {
70 ostype => "debian-11",
71 },
72 'buster' => {
73 ostype => "debian-10",
74 },
75
76 # DEVUAN (imply systemd = 0 default)
77 'beowulf' => {
78 ostype => "devuan-3.0",
79 },
80 'chimaera' => {
81 ostype => "devuan-4.0",
82 },
83 'daedalus' => {
84 ostype => "devuan-5.0",
85 },
86
87 # UBUNTU
88 'bionic' => {
89 ostype => "ubuntu-18.04",
90 origin => 'ubuntu',
91 },
92 'focal' => {
93 ostype => "ubuntu-20.04",
94 origin => 'ubuntu',
95 },
96 'jammy' => {
97 ostype => "ubuntu-22.04",
98 origin => 'ubuntu',
99 },
100 'kinetic' => {
101 ostype => "ubuntu-22.10",
102 origin => 'ubuntu',
103 },
104 'lunar' => {
105 ostype => "ubuntu-23.04",
106 origin => 'ubuntu',
107 },
108 'mantic' => {
109 ostype => "ubuntu-23.10",
110 origin => 'ubuntu',
111 },
112 };
113
114 sub get_suite_info {
115 my ($suite) = @_;
116
117 my $suiteinfo = $supported_suites->{$suite} || die "unsupported suite '$suite'!\n";
118
119 # set defaults
120 $suiteinfo->{origin} //= 'debian';
121 $suiteinfo->{suite} //= $suite;
122
123 $suiteinfo->{flags} //= {};
124 if ($suiteinfo->{ostype} =~ /^devuan/) {
125 $suiteinfo->{flags}->{systemd} //= 0;
126 } else {
127 $suiteinfo->{flags}->{systemd} //= 1;
128 }
129
130 return $suiteinfo;
131 }
132
133 sub download {
134 my ($self, $url, $path) = @_;
135 my $tmpfn = "$path.tmp$$";
136
137 $self->logmsg ("download: $url\n");
138
139 eval { $self->run_command ("wget -q '$url' -O '$tmpfn'") };
140 if (my $err = $@) {
141 unlink $tmpfn;
142 die $err;
143 }
144
145 rename ($tmpfn, $path);
146 }
147
148 sub write_file {
149 my ($data, $file, $perm) = @_;
150
151 die "no filename" if !$file;
152
153 unlink $file;
154
155 my $fh = IO::File->new ($file, O_WRONLY | O_CREAT, $perm) ||
156 die "unable to open file '$file'";
157
158 print $fh $data;
159
160 $fh->close;
161 }
162
163 sub read_file {
164 my ($file) = @_;
165
166 die "no filename" if !$file;
167
168 my $fh = IO::File->new ($file) ||
169 die "unable to open file '$file'";
170
171 local $/; # slurp mode
172
173 my $data = <$fh>;
174
175 $fh->close;
176
177 return $data;
178 }
179
180 sub read_config {
181 my ($filename) = @_;
182
183 my $res = {};
184
185 my $fh = IO::File->new ("<$filename") || return $res;
186 my $rec = '';
187
188 while (defined (my $line = <$fh>)) {
189 next if $line =~ m/^\#/;
190 next if $line =~ m/^\s*$/;
191 $rec .= $line;
192 };
193
194 close ($fh);
195
196 chomp $rec;
197 $rec .= "\n";
198
199 while ($rec) {
200 if ($rec =~ s/^Description:\s*([^\n]*)(\n\s+.*)*$//si) {
201 $res->{headline} = $1;
202 chomp $res->{headline};
203 my $long = $2;
204 $long =~ s/^\s+/ /;
205 $res->{description} = $long;
206 chomp $res->{description};
207 } elsif ($rec =~ s/^([^:]+):\s*(.*\S)\s*\n//) {
208 my ($key, $value) = (lc ($1), $2);
209 if ($key eq 'source' || $key eq 'mirror') {
210 push @{$res->{$key}}, $value;
211 } else {
212 die "duplicate key '$key'\n" if defined ($res->{$key});
213 $res->{$key} = $value;
214 }
215 } else {
216 die "unable to parse config file: $rec";
217 }
218 }
219
220 die "unable to parse config file" if $rec;
221
222 return $res;
223 }
224
225 sub run_command {
226 my ($self, $cmd, $input, $getoutput) = @_;
227
228 my $reader = IO::File->new();
229 my $writer = IO::File->new();
230 my $error = IO::File->new();
231
232 my $orig_pid = $$;
233
234 my $cmdstr = ref ($cmd) eq 'ARRAY' ? join (' ', @$cmd) : $cmd;
235
236 my $pid;
237 eval {
238 if (ref ($cmd) eq 'ARRAY') {
239 $pid = open3 ($writer, $reader, $error, @$cmd) || die $!;
240 } else {
241 $pid = open3 ($writer, $reader, $error, $cmdstr) || die $!;
242 }
243 };
244
245 my $err = $@;
246
247 # catch exec errors
248 if ($orig_pid != $$) {
249 $self->logmsg ("ERROR: command '$cmdstr' failed - fork failed\n");
250 POSIX::_exit (1);
251 kill ('KILL', $$);
252 }
253
254 die $err if $err;
255
256 print $writer $input if defined $input;
257 close $writer;
258
259 my $select = IO::Select->new();
260 $select->add ($reader);
261 $select->add ($error);
262
263 my $res = '';
264 my $logfd = $self->{logfd};
265
266 while ($select->count) {
267 my @handles = $select->can_read ();
268
269 foreach my $h (@handles) {
270 my $buf = '';
271 my $count = sysread ($h, $buf, 4096);
272 if (!defined ($count)) {
273 waitpid ($pid, 0);
274 die "command '$cmdstr' failed: $!";
275 }
276 $select->remove ($h) if !$count;
277
278 print $logfd $buf;
279
280 $res .= $buf if $getoutput;
281 }
282 }
283
284 waitpid ($pid, 0);
285 my $ec = ($? >> 8);
286
287 die "command '$cmdstr' failed with exit code $ec\n" if $ec;
288
289 return $res;
290 }
291
292 sub logmsg {
293 my $self = shift;
294 print STDERR @_;
295 $self->writelog (@_);
296 }
297
298 sub writelog {
299 my $self = shift;
300 my $fd = $self->{logfd};
301 print $fd @_;
302 }
303
304 sub __sample_config {
305 my ($self) = @_;
306
307 my $data = '';
308 my $arch = $self->{config}->{architecture};
309
310 my $ostype = $self->{config}->{ostype};
311
312 if ($ostype =~ m/^de(bi|vu)an-/) {
313 $data .= "lxc.include = /usr/share/lxc/config/debian.common.conf\n";
314 } elsif ($ostype =~ m/^ubuntu-/) {
315 $data .= "lxc.include = /usr/share/lxc/config/ubuntu.common.conf\n";
316 } else {
317 die "unknown os type '$ostype'\n";
318 }
319 $data .= "lxc.uts.name = localhost\n";
320 $data .= "lxc.rootfs.path = $self->{rootfs}\n";
321
322 return $data;
323 }
324
325 sub __allocate_ve {
326 my ($self) = @_;
327
328 my $cid;
329 if (my $fd = IO::File->new (".veid")) {
330 $cid = <$fd>;
331 chomp $cid;
332 close ($fd);
333 }
334
335
336 $self->{working_dir} = getcwd;
337 $self->{veconffile} = "$self->{working_dir}/config";
338 $self->{rootfs} = "$self->{working_dir}/rootfs";
339
340 if ($cid) {
341 $self->{veid} = $cid;
342 return $cid;
343 }
344
345 my $uuid;
346 my $uuid_str;
347 UUID::generate($uuid);
348 UUID::unparse($uuid, $uuid_str);
349 $self->{veid} = $uuid_str;
350
351 my $fd = IO::File->new (">.veid") ||
352 die "unable to write '.veid'\n";
353 print $fd "$self->{veid}\n";
354 close ($fd);
355
356 my $cdata = $self->__sample_config();
357
358 my $fh = IO::File->new ($self->{veconffile}, O_WRONLY|O_CREAT|O_EXCL) ||
359 die "unable to write lxc config file '$self->{veconffile}' - $!";
360 print $fh $cdata;
361 close ($fh);
362
363 mkdir $self->{rootfs} || die "unable to create rootfs - $!";
364
365 $self->logmsg ("allocated VE $self->{veid}\n");
366
367 return $self->{veid};
368 }
369
370 # just use some simple heuristic for now, merge usr for releases newer than ubuntu 21.x or debian 11
371 sub can_usr_merge {
372 my ($self) = @_;
373
374 my $ostype = $self->{config}->{ostype};
375
376 # FIXME: add configuration override posibillity
377
378 if ($ostype =~ m/^debian-(\d+)/) {
379 return int($1) >= 11;
380 } elsif ($ostype =~ m/^ubuntu-(\d+)/) {
381 return int($1) >= 21;
382 }
383 return; # false
384 }
385
386 sub setup_usr_merge {
387 my ($self) = @_;
388
389 my $rootfs = $self->{rootfs};
390 my $arch = $self->{config}->{architecture};
391
392 # similar to https://salsa.debian.org/installer-team/debootstrap/-/blob/master/functions#L1354
393 my @merged_dirs = qw(bin sbin lib);
394
395 if ($arch eq 'amd64') {
396 push @merged_dirs, qw(lib32 lib64 libx32);
397 } elsif ($arch eq 'i386') {
398 push @merged_dirs, qw(lib64 libx32);
399 }
400
401 $self->logmsg ("setup usr-merge symlinks for '" . join("', '", @merged_dirs) . "'\n");
402
403 for my $dir (@merged_dirs) {
404 symlink("usr/$dir", "$rootfs/$dir") or warn "could not create symlink - $!\n";
405 mkpath "$rootfs/usr/$dir";
406 }
407 }
408
409 sub get_target_name {
410 my ($config) = @_;
411
412 my $name = $config->{name} || die "no 'name' specified\n";
413 $name =~ m/^[a-z][0-9a-z\-\*\.]+$/ || die "illegal characters in name '$name'\n";
414
415 my ($version, $arch, $ostype) = $config->@{'version', 'architecture', 'ostype'};
416 $name = "${ostype}-${name}" if $name !~ m/^$ostype/;
417
418 return "${name}_${version}_${arch}"
419 }
420
421 sub new {
422 my ($class, $config) = @_;
423
424 $class = ref ($class) || $class;
425 $config = read_config ('dab.conf') if !$config;
426
427 my $self = {
428 config => $config,
429 };
430 bless $self, $class;
431
432 $self->{logfile} = "logfile";
433 $self->{logfd} = IO::File->new (">>$self->{logfile}") || die "unable to open log file";
434
435 my $arch = $config->{architecture} || die "no 'architecture' specified\n";
436 die "unsupported architecture '$arch'\n" if $arch !~ m/^(i386|amd64)$/;
437
438 my $suite = $config->{suite} || die "no 'suite' specified\n";
439
440 my $suiteinfo = get_suite_info($suite);
441 $suite = $suiteinfo->{suite};
442 $config->{ostype} = $suiteinfo->{ostype};
443
444 # assert required dab.conf keys exist
445 for my $key (qw(version section headline maintainer)) {
446 die "no '$key' specified\n" if !$config->{$key};
447 }
448
449 $self->{targetname} = get_target_name($config);
450
451 if (!$config->{source}) {
452 if (lc($suiteinfo->{origin}) eq 'debian') {
453 if ($suite eq 'etch' || $suite eq 'lenny') {
454 push @{$config->{source}}, (
455 'http://ftp.debian.org/debian SUITE main contrib',
456 'http://security.debian.org SUITE/updates main contrib',
457 );
458 } elsif ($suite =~ /^(?:bullseye|bookworm|trixie|forky)$/) {
459 push @{$config->{source}}, (
460 "http://deb.debian.org/debian SUITE main contrib",
461 "http://deb.debian.org/debian SUITE-updates main contrib",
462 "http://security.debian.org SUITE-security main contrib",
463 );
464 } else {
465 push @{$config->{source}}, (
466 "http://ftp.debian.org/debian SUITE main contrib",
467 "http://ftp.debian.org/debian SUITE-updates main contrib",
468 "http://security.debian.org SUITE/updates main contrib",
469 );
470 }
471 } elsif (lc($suiteinfo->{origin}) eq 'ubuntu') {
472 my $comp = "main restricted universe multiverse";
473 push @{$config->{source}}, (
474 "http://archive.ubuntu.com/ubuntu SUITE $comp",
475 "http://archive.ubuntu.com/ubuntu SUITE-updates $comp",
476 "http://archive.ubuntu.com/ubuntu SUITE-security $comp",
477 );
478 } else {
479 die "implement me";
480 }
481 }
482
483 my $sources = undef;
484
485 foreach my $s (@{$config->{source}}) {
486 if ($s =~ m@^\s*((https?|ftp)://\S+)\s+(\S+)((\s+(\S+))+)$@) {
487 my ($url, $su, $components) = ($1, $3, $4);
488 $su =~ s/SUITE/$suite/;
489 $components =~ s/^\s+//;
490 $components =~ s/\s+$//;
491 my $ca;
492 foreach my $co (split (/\s+/, $components)) {
493 push @$ca, $co;
494 }
495 $ca = ['main'] if !$ca;
496
497 push @$sources, {
498 source => $url,
499 comp => $ca,
500 suite => $su,
501 };
502 } else {
503 die "syntax error in source spezification '$s'\n";
504 }
505 }
506
507 foreach my $m (@{$config->{mirror}}) {
508 if ($m =~ m@^\s*((https?|ftp)://\S+)\s*=>\s*((https?|ftp)://\S+)\s*$@) {
509 my ($ms, $md) = ($1, $3);
510 my $found;
511 foreach my $ss (@$sources) {
512 if ($ss->{source} eq $ms) {
513 $found = 1;
514 $ss->{mirror} = $md;
515 last;
516 }
517 }
518 die "unusable mirror $ms\n" if !$found;
519 } else {
520 die "syntax error in mirror spezification '$m'\n";
521 }
522 }
523 $self->{sources} = $sources;
524 $self->{infodir} = "info";
525
526 $self->__allocate_ve();
527
528 $self->{cachedir} = ($config->{cachedir} || 'cache') . "/$suite";;
529
530 my $incl = [qw (less ssh openssh-server logrotate)];
531 my $excl = [qw (modutils reiserfsprogs ppp pppconfig pppoe pppoeconf nfs-common mtools ntp)];
532
533 # ubuntu has too many dependencies on udev, so we cannot exclude it (instead we disable udevd)
534 if (lc($suiteinfo->{origin}) eq 'ubuntu' && $suiteinfo->{flags}->{systemd}) {
535 push @$incl, 'isc-dhcp-client';
536 push @$excl, qw(libmodule-build-perl libdrm-common libdrm2 libplymouth5 plymouth plymouth-theme-ubuntu-text powermgmt-base);
537 if ($suite eq 'jammy') {
538 push @$excl, qw(fuse); # avoid fuse2 <-> fuse3 conflict
539 }
540 } elsif ($suite eq 'buster' || $suite eq 'bullseye' || $suite eq 'bookworm') {
541 push @$excl, qw(module-init-tools pciutils hdparm memtest86+ parted);
542 } else {
543 push @$excl, qw(udev module-init-tools pciutils hdparm memtest86+ parted);
544 }
545
546 $self->{incl} = $incl;
547 $self->{excl} = $excl;
548
549 return $self;
550 }
551
552 sub initialize {
553 my ($self) = @_;
554
555 my $infodir = $self->{infodir};
556 my $arch = $self->{config}->{architecture};
557
558 rmtree $infodir;
559 mkpath $infodir;
560
561 # truncate log
562 my $logfd = $self->{logfd} = IO::File->new (">$self->{logfile}") ||
563 die "unable to open log file";
564
565 my $COMPRESSORS = [
566 {
567 ext => 'xz',
568 decomp => 'xz -d',
569 },
570 {
571 ext => 'gz',
572 decomp => 'gzip -d',
573 },
574 ];
575
576 foreach my $ss (@{$self->{sources}}) {
577 my $src = $ss->{mirror} || $ss->{source};
578 my $path = "dists/$ss->{suite}/Release";
579 my $url = "$src/$path";
580 my $target = __url_to_filename ("$ss->{source}/$path");
581 eval {
582 $self->download ($url, "$infodir/$target");
583 $self->download ("$url.gpg", "$infodir/$target.gpg");
584 # fixme: impl. verify (needs --keyring option)
585 };
586 if (my $err = $@) {
587 print $logfd $@;
588 warn "Release info ignored\n";
589 };
590
591 foreach my $comp (@{$ss->{comp}}) {
592 foreach my $compressor (@$COMPRESSORS) {
593 $path = "dists/$ss->{suite}/$comp/binary-$arch/Packages.$compressor->{ext}";
594 $target = "$infodir/" . __url_to_filename ("$ss->{source}/$path");
595 my $pkgsrc = "$src/$path";
596 eval {
597 $self->download ($pkgsrc, $target);
598 $self->run_command ("$compressor->{decomp} '$target'");
599 };
600 if (my $err = $@) {
601 print $logfd "could not download Packages.$compressor->{ext}\n";
602 } else {
603 last;
604 }
605 }
606 }
607 }
608 }
609
610 sub write_config {
611 my ($self, $filename, $size) = @_;
612
613 my $config = $self->{config};
614
615 my $data = '';
616
617 $data .= "Name: $config->{name}\n";
618 $data .= "Version: $config->{version}\n";
619 $data .= "Type: lxc\n";
620 $data .= "OS: $config->{ostype}\n";
621 $data .= "Section: $config->{section}\n";
622 $data .= "Maintainer: $config->{maintainer}\n";
623 $data .= "Architecture: $config->{architecture}\n";
624 $data .= "Installed-Size: $size\n";
625
626 # optional
627 $data .= "Infopage: $config->{infopage}\n" if $config->{infopage};
628 $data .= "ManageUrl: $config->{manageurl}\n" if $config->{manageurl};
629 $data .= "Certified: $config->{certified}\n" if $config->{certified};
630
631 # description
632 $data .= "Description: $config->{headline}\n";
633 $data .= "$config->{description}\n" if $config->{description};
634
635 write_file ($data, $filename, 0644);
636 }
637
638 sub finalize {
639 my ($self, $opts) = @_;
640
641 my $suite = $self->{config}->{suite};
642 my $infodir = $self->{infodir};
643 my $arch = $self->{config}->{architecture};
644
645 my $instpkgs = $self->read_installed ();
646 my $pkginfo = $self->pkginfo();
647 my $veid = $self->{veid};
648 my $conffile = $self->{veconffile};
649 my $rootdir = $self->{rootfs};
650
651 my $vestat = $self->ve_status();
652 die "ve not running - unable to finalize\n" if !$vestat->{running};
653
654 # cleanup mysqld
655 if (-f "$rootdir/etc/init.d/mysql") {
656 $self->ve_command ("/etc/init.d/mysql stop");
657 }
658
659 if (!($opts->{keepmycnf} || (-f "$rootdir/etc/init.d/mysql_randompw"))) {
660 unlink "$rootdir/root/.my.cnf";
661 }
662
663 if ($suite eq 'etch') {
664 # enable apache2 startup
665 if ($instpkgs->{apache2}) {
666 write_file ("NO_START=0\n", "$rootdir/etc/default/apache2");
667 } else {
668 unlink "$rootdir/etc/default/apache2";
669 }
670 }
671 $self->logmsg ("cleanup package status\n");
672 # prevent auto selection of all standard, required or important
673 # packages which are not installed
674 foreach my $pkg (keys %$pkginfo) {
675 my $pri = $pkginfo->{$pkg}->{priority};
676 if ($pri && ($pri eq 'required' || $pri eq 'important'
677 || $pri eq 'standard')) {
678 if (!$instpkgs->{$pkg}) {
679 $self->ve_dpkg_set_selection ($pkg, 'purge');
680 }
681 }
682 }
683
684 $self->ve_command ("apt-get clean");
685
686 $self->logmsg ("update available package list\n");
687
688 $self->ve_command ("dpkg --clear-avail");
689 foreach my $ss (@{$self->{sources}}) {
690 my $relsrc = __url_to_filename ("$ss->{source}/dists/$ss->{suite}/Release");
691 if (-f "$infodir/$relsrc" && -f "$infodir/$relsrc.gpg") {
692 $self->run_command ("cp '$infodir/$relsrc' '$rootdir/var/lib/apt/lists/$relsrc'");
693 $self->run_command ("cp '$infodir/$relsrc.gpg' '$rootdir/var/lib/apt/lists/$relsrc.gpg'");
694 }
695 foreach my $comp (@{$ss->{comp}}) {
696 my $src = __url_to_filename ("$ss->{source}/dists/$ss->{suite}/" .
697 "$comp/binary-$arch/Packages");
698 my $target = "/var/lib/apt/lists/$src";
699 $self->run_command ("cp '$infodir/$src' '$rootdir/$target'");
700 $self->ve_command ("dpkg --merge-avail '$target'");
701 }
702 }
703
704 # set dselect default method
705 write_file ("apt apt\n", "$rootdir/var/lib/dpkg/cmethopt");
706
707 $self->ve_divert_remove ("/usr/sbin/policy-rc.d");
708
709 $self->ve_divert_remove ("/sbin/start-stop-daemon");
710
711 $self->ve_divert_remove ("/sbin/init");
712
713 # finally stop the VE
714 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
715
716 unlink "$rootdir/sbin/defenv";
717 unlink <$rootdir/root/dead.letter*>;
718 unlink "$rootdir/var/log/init.log";
719 unlink "$rootdir/aquota.group", "$rootdir/aquota.user";
720
721 write_file ("", "$rootdir/var/log/syslog");
722
723 my $get_path_size = sub {
724 my ($path) = @_;
725 my $sizestr = $self->run_command ("du -sm $path", undef, 1);
726 if ($sizestr =~ m/^(\d+)\s+\Q$path\E$/) {
727 return int($1);
728 } else {
729 die "unable to detect size for '$path'\n";
730 }
731 };
732
733 $self->logmsg ("detecting final appliance size: ");
734 my $size = $get_path_size->($rootdir);
735 $self->logmsg ("$size MB\n");
736
737 $self->write_config ("$rootdir/etc/appliance.info", $size);
738
739 $self->logmsg ("creating final appliance archive\n");
740
741 my $target = "$self->{targetname}.tar";
742
743 my $compressor = $opts->{compressor} // 'gz';
744 my $compressor2cmd_map = {
745 gz => 'gzip',
746 gzip => 'gzip',
747 zst => 'zstd --rm -9',
748 zstd => 'zstd --rm -9',
749 'zstd-max' => 'zstd --rm -19 -T0', # maximal level where the decompressor can still run efficiently
750 };
751 my $compressor2ending = {
752 gzip => 'gz',
753 zstd => 'zst',
754 'zstd-max' => 'zst',
755 };
756 my $compressor_cmd = $compressor2cmd_map->{$compressor};
757 die "unkown compressor '$compressor', use one of: ". join(', ', sort keys %$compressor2cmd_map)
758 if !defined($compressor_cmd);
759
760 my $ending = $compressor2ending->{$compressor} // $compressor;
761 my $final_archive = "${target}.${ending}";
762 unlink $target;
763 unlink $final_archive;
764
765 $self->run_command ("tar cpf $target --numeric-owner -C '$rootdir' ./etc/appliance.info");
766 $self->run_command ("tar rpf $target --numeric-owner -C '$rootdir' --exclude ./etc/appliance.info .");
767 $self->run_command ("$compressor_cmd $target");
768
769 $self->logmsg ("detecting final commpressed appliance size: ");
770 $size = $get_path_size->($final_archive);
771 $self->logmsg ("$size MB\n");
772
773 $self->logmsg ("appliance archive: $final_archive\n");
774 }
775
776 sub read_installed {
777 my ($self) = @_;
778
779 my $rootdir = $self->{rootfs};
780
781 my $pkgfilelist = "$rootdir/var/lib/dpkg/status";
782 local $/ = '';
783 open(my $PKGLST, '<', $pkgfilelist) or die "unable to open '$pkgfilelist' - $!";
784
785 my $pkglist = {};
786
787 while (my $rec = <$PKGLST>) {
788 chomp $rec;
789 $rec =~ s/\n\s+/ /g;
790 $rec .= "\n";
791 my $res = {};
792
793 while ($rec =~ s/^([^:]+):\s+(.*?)\s*\n//) {
794 $res->{lc $1} = $2;
795 }
796
797 my $pkg = $res->{'package'};
798 if (my $status = $res->{status}) {
799 my @sa = split (/\s+/, $status);
800 my $stat = $sa[0];
801 if ($stat && ($stat ne 'purge')) {
802 $pkglist->{$pkg} = $res;
803 }
804 }
805 }
806
807 close ($PKGLST);
808
809 return $pkglist;
810 }
811
812 sub ve_status {
813 my ($self) = @_;
814
815 my $veid = $self->{veid};
816
817 my $res = { running => 0 };
818
819 $res->{exist} = 1 if -d "$self->{rootfs}/usr";
820
821 my $filename = "/proc/net/unix";
822
823 # similar test is used by lcxcontainers.c: list_active_containers
824 my $fh = IO::File->new ($filename, "r");
825 return $res if !$fh;
826
827 while (defined(my $line = <$fh>)) {
828 if ($line =~ m/^[a-f0-9]+:\s\S+\s\S+\s\S+\s\S+\s\S+\s\d+\s(\S+)$/) {
829 my $path = $1;
830 if ($path =~ m!^@/\S+/$veid/command$!) {
831 $res->{running} = 1;
832 }
833 }
834 }
835 close($fh);
836
837 return $res;
838 }
839
840 sub ve_command {
841 my ($self, $cmd, $input) = @_;
842
843 my $veid = $self->{veid};
844 my $conffile = $self->{veconffile};
845
846 if (ref ($cmd) eq 'ARRAY') {
847 unshift @$cmd, 'lxc-attach', '-n', $veid, '--rcfile', $conffile, '--clear-env', '--', 'defenv';
848 $self->run_command($cmd, $input);
849 } else {
850 $self->run_command("lxc-attach -n $veid --rcfile $conffile --clear-env -- defenv $cmd", $input);
851 }
852 }
853
854 # like ve_command, but pipes stdin correctly
855 sub ve_exec {
856 my ($self, @cmd) = @_;
857
858 my $veid = $self->{veid};
859 my $conffile = $self->{veconffile};
860
861 my $reader;
862 my $pid = open2($reader, "<&STDIN", 'lxc-attach', '-n', $veid, '--rcfile', $conffile, '--',
863 'defenv', @cmd) || die "unable to exec command";
864
865 while (defined (my $line = <$reader>)) {
866 $self->logmsg ($line);
867 }
868
869 waitpid ($pid, 0);
870 my $rc = $? >> 8;
871
872 die "ve_exec failed - status $rc\n" if $rc != 0;
873 }
874
875 sub ve_divert_add {
876 my ($self, $filename) = @_;
877
878 $self->ve_command ("dpkg-divert --add --divert '$filename.distrib' " .
879 "--rename '$filename'");
880 }
881 sub ve_divert_remove {
882 my ($self, $filename) = @_;
883
884 my $rootdir = $self->{rootfs};
885
886 unlink "$rootdir/$filename";
887 $self->ve_command ("dpkg-divert --remove --rename '$filename'");
888 }
889
890 sub ve_debconfig_set {
891 my ($self, $dcdata) = @_;
892
893 my $rootdir = $self->{rootfs};
894 my $cfgfile = "/tmp/debconf.txt";
895 write_file ($dcdata, "$rootdir/$cfgfile");
896 $self->ve_command ("debconf-set-selections $cfgfile");
897 unlink "$rootdir/$cfgfile";
898 }
899
900 sub ve_dpkg_set_selection {
901 my ($self, $pkg, $status) = @_;
902
903 $self->ve_command ("dpkg --set-selections", "$pkg $status");
904 }
905
906 sub ve_dpkg {
907 my ($self, $cmd, @pkglist) = @_;
908
909 return if !scalar (@pkglist);
910
911 my $pkginfo = $self->pkginfo();
912
913 my $rootdir = $self->{rootfs};
914 my $cachedir = $self->{cachedir};
915
916 my @files;
917
918 foreach my $pkg (@pkglist) {
919 my $filename = $self->getpkgfile ($pkg);
920 $self->run_command ("cp '$cachedir/$filename' '$rootdir/$filename'");
921 push @files, "/$filename";
922 $self->logmsg ("$cmd: $pkg\n");
923 }
924
925 my $fl = join (' ', @files);
926
927 if ($cmd eq 'install') {
928 $self->ve_command ("dpkg --force-depends --force-confold --install $fl");
929 } elsif ($cmd eq 'unpack') {
930 $self->ve_command ("dpkg --force-depends --unpack $fl");
931 } else {
932 die "internal error";
933 }
934
935 foreach my $fn (@files) { unlink "$rootdir$fn"; }
936 }
937
938 sub ve_destroy {
939 my ($self) = @_;
940
941 my $veid = $self->{veid}; # fixme
942 my $conffile = $self->{veconffile};
943
944 my $vestat = $self->ve_status();
945 if ($vestat->{running}) {
946 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
947 }
948
949 rmtree $self->{rootfs};
950 unlink $self->{veconffile};
951 }
952
953 sub ve_init {
954 my ($self) = @_;
955
956 my $veid = $self->{veid};
957 my $conffile = $self->{veconffile};
958
959 $self->logmsg ("initialize VE $veid\n");
960
961 my $vestat = $self->ve_status();
962 if ($vestat->{running}) {
963 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
964 }
965
966 rmtree $self->{rootfs};
967 mkpath $self->{rootfs};
968 }
969
970 sub __deb_version_cmp {
971 my ($cur, $op, $new) = @_;
972
973 if (system("dpkg", "--compare-versions", $cur, $op, $new) == 0) {
974 return 1;
975 }
976
977 return 0;
978 }
979
980 sub __parse_packages {
981 my ($pkginfo, $filename, $src) = @_;
982
983 local $/ = '';
984 open(my $PKGLST, '<', $filename) or die "unable to open '$filename' - $!";
985
986 while (my $rec = <$PKGLST>) {
987 $rec =~ s/\n\s+/ /g;
988 chomp $rec;
989 $rec .= "\n";
990
991 my $res = {};
992
993 while ($rec =~ s/^([^:]+):\s+(.*?)\s*\n//) {
994 $res->{lc $1} = $2;
995 }
996
997 my $pkg = $res->{'package'};
998 if ($pkg && $res->{'filename'}) {
999 my $cur;
1000 if (my $info = $pkginfo->{$pkg}) {
1001 $cur = $info->{version};
1002 }
1003 my $new = $res->{version};
1004 if (!$cur || __deb_version_cmp ($cur, 'lt', $new)) {
1005 if ($src) {
1006 $res->{url} = "$src/$res->{'filename'}";
1007 } else {
1008 die "no url for package '$pkg'" if !$res->{url};
1009 }
1010 $pkginfo->{$pkg} = $res;
1011 }
1012 }
1013 }
1014
1015 close ($PKGLST);
1016 }
1017
1018 sub pkginfo {
1019 my ($self) = @_;
1020
1021 return $self->{pkginfo} if $self->{pkginfo};
1022
1023 my $infodir = $self->{infodir};
1024 my $arch = $self->{config}->{architecture};
1025
1026 my $availfn = "$infodir/available";
1027
1028 my $pkginfo = {};
1029 my $pkgcount = 0;
1030
1031 # reading 'available' is faster, because it only contains latest version
1032 # (no need to do slow version compares)
1033 if (-f $availfn) {
1034 __parse_packages ($pkginfo, $availfn);
1035 $self->{pkginfo} = $pkginfo;
1036 return $pkginfo;
1037 }
1038
1039 $self->logmsg ("generating available package list\n");
1040
1041 foreach my $ss (@{$self->{sources}}) {
1042 foreach my $comp (@{$ss->{comp}}) {
1043 my $url = "$ss->{source}/dists/$ss->{suite}/$comp/binary-$arch/Packages";
1044 my $pkgfilelist = "$infodir/" . __url_to_filename ($url);
1045
1046 my $src = $ss->{mirror} || $ss->{source};
1047
1048 __parse_packages ($pkginfo, $pkgfilelist, $src);
1049 }
1050 }
1051
1052 if (my $dep = $self->{config}->{depends}) {
1053 foreach my $d (split (/,/, $dep)) {
1054 if ($d =~ m/^\s*(\S+)\s*(\((\S+)\s+(\S+)\)\s*)?$/) {
1055 my ($pkg, $op, $rver) = ($1, $3, $4);
1056 $self->logmsg ("checking dependencies: $d\n");
1057 my $info = $pkginfo->{$pkg};
1058 die "package '$pkg' not available\n" if !$info;
1059 if ($op) {
1060 my $cver = $info->{version};
1061 if (!__deb_version_cmp ($cver, $op, $rver)) {
1062 die "detected wrong version '$cver'\n";
1063 }
1064 }
1065 } else {
1066 die "syntax error in depends field";
1067 }
1068 }
1069 }
1070
1071 $self->{pkginfo} = $pkginfo;
1072
1073 my $tmpfn = "$availfn.tmp$$";
1074 my $fd = IO::File->new (">$tmpfn");
1075 foreach my $pkg (sort keys %$pkginfo) {
1076 my $info = $pkginfo->{$pkg};
1077 print $fd "package: $pkg\n";
1078 foreach my $k (sort keys %$info) {
1079 next if $k eq 'description';
1080 next if $k eq 'package';
1081 my $v = $info->{$k};
1082 print $fd "$k: $v\n" if $v;
1083 }
1084 print $fd "description: $info->{description}\n" if $info->{description};
1085 print $fd "\n";
1086 }
1087 close ($fd);
1088
1089 rename ($tmpfn, $availfn);
1090
1091 return $pkginfo;
1092 }
1093
1094 sub __record_provides {
1095 my ($pkginfo, $closure, $list, $skipself) = @_;
1096
1097 foreach my $pname (@$list) {
1098 my $info = $pkginfo->{$pname};
1099 # fixme: if someone install packages directly using dpkg, there
1100 # is no entry in 'available', only in 'status'. In that case, we
1101 # should extract info from $instpkgs
1102 if (!$info) {
1103 warn "hint: ignoring provides for '$pname' - package not in 'available' list.\n";
1104 next;
1105 }
1106 if (my $prov = $info->{provides}) {
1107 my @pl = split (',', $prov);
1108 foreach my $p (@pl) {
1109 $p =~ m/\s*(\S+)/;
1110 if (!($skipself && (grep { $1 eq $_ } @$list))) {
1111 $closure->{$1} = 1;
1112 }
1113 }
1114 }
1115 $closure->{$pname} = 1 if !$skipself;
1116 }
1117 }
1118
1119 sub closure {
1120 my ($self, $closure, $list) = @_;
1121
1122 my $pkginfo = $self->pkginfo();
1123
1124 # first, record provided packages
1125 __record_provides ($pkginfo, $closure, $list, 1);
1126
1127 my $pkghash = {};
1128 my $pkglist = [];
1129
1130 # then resolve dependencies
1131 foreach my $pname (@$list) {
1132 __closure_single ($pkginfo, $closure, $pkghash, $pkglist, $pname, $self->{excl});
1133 }
1134
1135 return $pkglist;
1136 }
1137
1138 sub __closure_single {
1139 my ($pkginfo, $closure, $pkghash, $pkglist, $pname, $excl) = @_;
1140
1141 $pname =~ s/^\s+//;
1142 $pname =~ s/\s+$//;
1143 $pname =~ s/:any$//;
1144
1145 return if $closure->{$pname};
1146
1147 my $info = $pkginfo->{$pname} || die "no such package '$pname'";
1148
1149 my $dep = $info->{depends};
1150 my $predep = $info->{'pre-depends'};
1151
1152 my $size = $info->{size};
1153 my $url = $info->{url};
1154
1155 $url || die "$pname: no url for package '$pname'";
1156
1157 if (!$pkghash->{$pname}) {
1158 unshift @$pkglist, $pname;
1159 $pkghash->{$pname} = 1;
1160 }
1161
1162 __record_provides ($pkginfo, $closure, [$pname]) if $info->{provides};
1163
1164 $closure->{$pname} = 1;
1165
1166 #print "$url\n";
1167
1168 my @l;
1169
1170 push @l, split (/,/, $predep) if $predep;
1171 push @l, split (/,/, $dep) if $dep;
1172
1173 DEPEND: foreach my $p (@l) {
1174 my @l1 = split (/\|/, $p);
1175 foreach my $p1 (@l1) {
1176 if ($p1 =~ m/^\s*(\S+).*/) {
1177 #printf (STDERR "$pname: $p --> $1\n");
1178 if ($closure->{$1}) {
1179 next DEPEND; # dependency already met
1180 }
1181 }
1182 }
1183 # search for non-excluded alternative
1184 my $found;
1185 foreach my $p1 (@l1) {
1186 if ($p1 =~ m/^\s*(\S+).*/) {
1187 next if grep { $1 eq $_ } @$excl;
1188 $found = $1;
1189 last;
1190 }
1191 }
1192 die "package '$pname' depends on exclusion '$p'\n" if !$found;
1193
1194 #printf (STDERR "$pname: $p --> $found\n");
1195
1196 __closure_single ($pkginfo, $closure, $pkghash, $pkglist, $found, $excl);
1197 }
1198 }
1199
1200 sub cache_packages {
1201 my ($self, $pkglist) = @_;
1202
1203 foreach my $pkg (@$pkglist) {
1204 $self->getpkgfile ($pkg);
1205 }
1206 }
1207
1208 sub getpkgfile {
1209 my ($self, $pkg) = @_;
1210
1211 my $pkginfo = $self->pkginfo();
1212 my $info = $pkginfo->{$pkg} || die "no such package '$pkg'";
1213 my $cachedir = $self->{cachedir};
1214
1215 my $url = $info->{url};
1216
1217 my $filename;
1218 if ($url =~ m|/([^/]+.deb)$|) {
1219 $filename = $1;
1220 } else {
1221 die "internal error";
1222 }
1223
1224 return $filename if -f "$cachedir/$filename";
1225
1226 mkpath $cachedir;
1227
1228 $self->download ($url, "$cachedir/$filename");
1229
1230 return $filename;
1231 }
1232
1233 sub install_init_script {
1234 my ($self, $script, $runlevel, $prio) = @_;
1235
1236 my $suite = $self->{config}->{suite};
1237 my $suiteinfo = get_suite_info($suite);
1238 my $rootdir = $self->{rootfs};
1239
1240 my $base = basename ($script);
1241 my $target = "$rootdir/etc/init.d/$base";
1242
1243 $self->run_command ("install -m 0755 '$script' '$target'");
1244 if ($suite eq 'etch' || $suite eq 'lenny') {
1245 $self->ve_command ("update-rc.d $base start $prio $runlevel .");
1246 } elsif ($suiteinfo->{flags}->{systemd}) {
1247 die "unable to install init script (system uses systemd)\n";
1248 } elsif ($suite eq 'trusty' || $suite eq 'precise') {
1249 die "unable to install init script (system uses upstart)\n";
1250 } else {
1251 $self->ve_command ("insserv $base");
1252 }
1253
1254 return $target;
1255 }
1256
1257 sub bootstrap {
1258 my ($self, $opts) = @_;
1259
1260 my $pkginfo = $self->pkginfo();
1261 my $veid = $self->{veid};
1262 my $suite = $self->{config}->{suite};
1263 my $suiteinfo = get_suite_info($suite);
1264
1265 my $important = [ @{$self->{incl}} ];
1266 my $required;
1267 my $standard;
1268
1269 my $mta = $opts->{exim} ? 'exim' : 'postfix';
1270 if ($mta eq 'postfix') {
1271 push @$important, "postfix";
1272 }
1273
1274 if ($opts->{include}) {
1275 push @$important, split(',', $opts->{include});
1276 }
1277
1278 my $exclude = {};
1279 if ($opts->{exclude}) {
1280 $exclude->{$_} = 1 for split(',', $opts->{exclude});
1281 }
1282
1283 foreach my $p (sort keys %$pkginfo) {
1284 next if grep { $p eq $_ } @{$self->{excl}};
1285 my $pri = $pkginfo->{$p}->{priority};
1286 next if !$pri;
1287 next if $mta ne 'exim' && $p =~ m/exim/;
1288 next if $p =~ m/(selinux|semanage|policycoreutils)/;
1289
1290 push @$required, $p if $pri eq 'required';
1291 next if $exclude->{$p};
1292 push @$important, $p if $pri eq 'important';
1293 push @$standard, $p if $pri eq 'standard' && !$opts->{minimal};
1294 }
1295
1296 my $closure = {};
1297 $required = $self->closure($closure, $required);
1298 $important = $self->closure($closure, $important);
1299
1300 if (!$opts->{minimal}) {
1301 $standard = $self->closure($closure, $standard);
1302 }
1303
1304 # test if we have all 'ubuntu-minimal' and 'ubuntu-standard' packages
1305 # except those explicitly excluded
1306 if ($suite eq 'hardy' || $suite eq 'intrepid' || $suite eq 'jaunty') {
1307 my $mdeps = $pkginfo->{'ubuntu-minimal'}->{depends};
1308 foreach my $d (split (/,/, $mdeps)) {
1309 if ($d =~ m/^\s*(\S+)$/) {
1310 my $pkg = $1;
1311 next if $closure->{$pkg};
1312 next if grep { $pkg eq $_ } @{$self->{excl}};
1313 die "missing ubuntu-minimal package '$pkg'\n";
1314 }
1315 }
1316 if (!$opts->{minimal}) {
1317 $mdeps = $pkginfo->{'ubuntu-standard'}->{depends};
1318 foreach my $d (split (/,/, $mdeps)) {
1319 if ($d =~ m/^\s*(\S+)$/) {
1320 my $pkg = $1;
1321 next if $closure->{$pkg};
1322 next if grep { $pkg eq $_ } @{$self->{excl}};
1323 die "missing ubuntu-standard package '$pkg'\n";
1324 }
1325 }
1326 }
1327 }
1328
1329 # download/cache all files first
1330 $self->cache_packages ($required);
1331 $self->cache_packages ($important);
1332 $self->cache_packages ($standard);
1333
1334 my $rootdir = $self->{rootfs};
1335
1336 # extract required packages first
1337 $self->logmsg ("create basic environment\n");
1338
1339 if ($self->can_usr_merge()) {
1340 $self->setup_usr_merge();
1341 }
1342
1343 my $compressor2opt = {
1344 'zst' => '--zstd',
1345 'gz' => '--gzip',
1346 'xz' => '--xz',
1347 };
1348 my $compressor_re = join('|', keys $compressor2opt->%*);
1349
1350 $self->logmsg ("extract required packages to rootfs\n");
1351 foreach my $p (@$required) {
1352 my $filename = $self->getpkgfile ($p);
1353 my $content = $self->run_command("ar -t '$self->{cachedir}/$filename'", undef, 1);
1354 if ($content =~ m/^(data.tar.($compressor_re))$/m) {
1355 my $archive = $1;
1356 my $tar_opts = "--keep-directory-symlink $compressor2opt->{$2}";
1357
1358 $self->run_command("ar -p '$self->{cachedir}/$filename' '$archive' | tar -C '$rootdir' -xf - $tar_opts");
1359 } else {
1360 die "unexpected error for $p: no data.tar.{xz,gz,zst} found...";
1361 }
1362 }
1363
1364 # fake dpkg status
1365 my $data = "Package: dpkg\n" .
1366 "Version: $pkginfo->{dpkg}->{version}\n" .
1367 "Status: install ok installed\n";
1368
1369 write_file ($data, "$rootdir/var/lib/dpkg/status");
1370 write_file ("", "$rootdir/var/lib/dpkg/info/dpkg.list");
1371 write_file ("", "$rootdir/var/lib/dpkg/available");
1372
1373 $data = '';
1374 foreach my $ss (@{$self->{sources}}) {
1375 my $url = $ss->{source};
1376 my $comp = join (' ', @{$ss->{comp}});
1377 $data .= "deb $url $ss->{suite} $comp\n\n";
1378 }
1379
1380 write_file ($data, "$rootdir/etc/apt/sources.list");
1381
1382 $data = "# UNCONFIGURED FSTAB FOR BASE SYSTEM\n";
1383 write_file ($data, "$rootdir/etc/fstab", 0644);
1384
1385 write_file ("localhost\n", "$rootdir/etc/hostname", 0644);
1386
1387 # avoid warnings about non-existent resolv.conf
1388 write_file ("", "$rootdir/etc/resolv.conf", 0644);
1389
1390 if (lc($suiteinfo->{origin}) eq 'ubuntu' && $suiteinfo->{flags}->{systemd}) {
1391 # no need to configure loopback device
1392 # FIXME: Debian (systemd based?) too?
1393 } else {
1394 $data = "auto lo\niface lo inet loopback\n";
1395 mkdir "$rootdir/etc/network";
1396 write_file ($data, "$rootdir/etc/network/interfaces", 0644);
1397 }
1398
1399 # setup devices
1400 $self->run_command ("tar xzf '$devicetar' -C '$rootdir'") if $opts->{'device-skelleton'};
1401
1402 # avoid warnings about missing default locale
1403 write_file ("LANG=\"C\"\n", "$rootdir/etc/default/locale", 0644);
1404
1405 # fake init
1406 rename ("$rootdir/sbin/init", "$rootdir/sbin/init.org");
1407 $self->run_command ("cp '$fake_init' '$rootdir/sbin/init'");
1408
1409 $self->run_command ("cp '$default_env' '$rootdir/sbin/defenv'");
1410
1411 $self->run_command ("lxc-start -n $veid -f $self->{veconffile}");
1412
1413 $self->logmsg ("initialize ld cache\n");
1414 $self->ve_command ("/sbin/ldconfig");
1415 $self->run_command ("ln -sf mawk '$rootdir/usr/bin/awk'");
1416
1417 $self->logmsg ("installing packages\n");
1418
1419 $self->ve_dpkg ('install', 'base-files', 'base-passwd');
1420
1421 $self->ve_dpkg ('install', 'dpkg');
1422
1423 $self->run_command ("ln -sf /usr/share/zoneinfo/UTC '$rootdir/etc/localtime'");
1424
1425 $self->run_command ("ln -sf bash '$rootdir/bin/sh'");
1426
1427 $self->ve_dpkg ('install', 'libc6');
1428 $self->ve_dpkg ('install', 'perl-base');
1429
1430 unlink "$rootdir/usr/bin/awk";
1431
1432 $self->ve_dpkg ('install', 'mawk');
1433 $self->ve_dpkg ('install', 'debconf');
1434
1435 # unpack required packages
1436 foreach my $p (@$required) {
1437 $self->ve_dpkg ('unpack', $p);
1438 }
1439
1440 rename ("$rootdir/sbin/init.org", "$rootdir/sbin/init");
1441 $self->ve_divert_add ("/sbin/init");
1442 $self->run_command ("cp '$fake_init' '$rootdir/sbin/init'");
1443
1444 # disable service activation
1445 $self->ve_divert_add ("/usr/sbin/policy-rc.d");
1446 $data = "#!/bin/sh\nexit 101\n";
1447 write_file ($data, "$rootdir/usr/sbin/policy-rc.d", 755);
1448
1449 # disable start-stop-daemon
1450 $self->ve_divert_add ("/sbin/start-stop-daemon");
1451 $data = <<EOD;
1452 #!/bin/sh
1453 echo
1454 echo \"Warning: Fake start-stop-daemon called, doing nothing\"
1455 EOD
1456 write_file ($data, "$rootdir/sbin/start-stop-daemon", 0755);
1457
1458 # disable udevd
1459 $self->ve_divert_add ("/sbin/udevd");
1460
1461 if ($suite eq 'etch') {
1462 write_file ("NO_START=1\n", "$rootdir/etc/default/apache2"); # disable apache2 startup
1463 }
1464
1465 $self->logmsg ("configure required packages\n");
1466 $self->ve_command ("dpkg --force-confold --skip-same-version --configure -a");
1467
1468 # set postfix defaults
1469 if ($mta eq 'postfix') {
1470 $data = "postfix postfix/main_mailer_type select Local only\n";
1471 $self->ve_debconfig_set ($data);
1472
1473 $data = "postmaster: root\nwebmaster: root\n";
1474 write_file ($data, "$rootdir/etc/aliases");
1475 }
1476
1477 if ($suite eq 'jaunty') {
1478 # jaunty does not create /var/run/network, so network startup fails.
1479 # so we do not use tmpfs for /var/run and /var/lock
1480 $self->run_command ("sed -e 's/RAMRUN=yes/RAMRUN=no/' -e 's/RAMLOCK=yes/RAMLOCK=no/' -i $rootdir/etc/default/rcS");
1481 # and create the directory here
1482 $self->run_command ("mkdir $rootdir/var/run/network");
1483 }
1484
1485 # unpack base packages
1486 foreach my $p (@$important) {
1487 $self->ve_dpkg ('unpack', $p);
1488 }
1489
1490 # start loopback
1491 if (-x "$rootdir/sbin/ifconfig") {
1492 $self->ve_command ("ifconfig lo up");
1493 } else {
1494 $self->ve_command ("ip link set lo up");
1495 }
1496
1497 $self->logmsg ("configure important packages\n");
1498 $self->ve_command ("dpkg --force-confold --skip-same-version --configure -a");
1499
1500 if (-d "$rootdir/etc/event.d") {
1501 unlink <$rootdir/etc/event.d/tty*>;
1502 }
1503
1504 if (-f "$rootdir/etc/inittab") {
1505 $self->run_command ("sed -i -e '/getty\\s38400\\stty[23456]/d' '$rootdir/etc/inittab'");
1506 }
1507
1508 # Link /etc/mtab to /proc/mounts, so df and friends will work:
1509 unlink "$rootdir/etc/mtab";
1510 $self->ve_command ("ln -s /proc/mounts /etc/mtab");
1511
1512 # reset password
1513 $self->ve_command ("usermod -L root");
1514
1515 if ($mta eq 'postfix') {
1516 $data = "postfix postfix/main_mailer_type select No configuration\n";
1517 $self->ve_debconfig_set ($data);
1518
1519 unlink "$rootdir/etc/mailname";
1520 write_file ($postfix_main_cf, "$rootdir/etc/postfix/main.cf");
1521 }
1522
1523 if (!$opts->{minimal}) {
1524 # unpack standard packages
1525 foreach my $p (@$standard) {
1526 $self->ve_dpkg ('unpack', $p);
1527 }
1528
1529 $self->logmsg ("configure standard packages\n");
1530 $self->ve_command ("dpkg --force-confold --skip-same-version --configure -a");
1531 }
1532
1533 # disable HWCLOCK access
1534 $self->run_command ("echo 'HWCLOCKACCESS=no' >> '$rootdir/etc/default/rcS'");
1535
1536 # disable hald
1537 $self->ve_divert_add ("/usr/sbin/hald");
1538
1539 # disable /dev/urandom init
1540 $self->run_command ("install -m 0755 '$script_init_urandom' '$rootdir/etc/init.d/urandom'");
1541
1542 if ($suite eq 'etch' || $suite eq 'hardy' || $suite eq 'intrepid' || $suite eq 'jaunty') {
1543 # avoid klogd start
1544 $self->ve_divert_add ("/sbin/klogd");
1545 }
1546
1547 # remove unnecessays sysctl entries to avoid warnings
1548 my $cmd = 'sed';
1549 $cmd .= ' -e \'s/^\(kernel\.printk.*\)/#\1/\'';
1550 $cmd .= ' -e \'s/^\(kernel\.maps_protect.*\)/#\1/\'';
1551 $cmd .= ' -e \'s/^\(fs\.inotify\.max_user_watches.*\)/#\1/\'';
1552 $cmd .= ' -e \'s/^\(vm\.mmap_min_addr.*\)/#\1/\'';
1553 $cmd .= " -i '$rootdir/etc/sysctl.conf'";
1554 $self->run_command ($cmd);
1555
1556 my $bindv6only = "$rootdir/etc/sysctl.d/bindv6only.conf";
1557 if (-f $bindv6only) {
1558 $cmd = 'sed';
1559 $cmd .= ' -e \'s/^\(net\.ipv6\.bindv6only.*\)/#\1/\'';
1560 $cmd .= " -i '$bindv6only'";
1561 $self->run_command ($cmd);
1562 }
1563
1564 if ($suite eq 'hardy' || $suite eq 'intrepid' || $suite eq 'jaunty') {
1565 # disable tty init (console-setup)
1566 my $cmd = 'sed';
1567 $cmd .= ' -e \'s/^\(ACTIVE_CONSOLES=.*\)/ACTIVE_CONSOLES=/\'';
1568 $cmd .= " -i '$rootdir/etc/default/console-setup'";
1569 $self->run_command ($cmd);
1570 }
1571
1572 if ($suite eq 'intrepid' || $suite eq 'jaunty') {
1573 # remove sysctl setup (avoid warnings at startup)
1574 my $filelist = "$rootdir/etc/sysctl.d/10-console-messages.conf";
1575 $filelist .= " $rootdir/etc/sysctl.d/10-process-security.conf" if $suite eq 'intrepid';
1576 $filelist .= " $rootdir/etc/sysctl.d/10-network-security.conf";
1577 $self->run_command ("rm $filelist");
1578 }
1579
1580 if (-e "$rootdir/lib/systemd/system/sys-kernel-config.mount") {
1581 $self->ve_command ("ln -s /dev/null /etc/systemd/system/sys-kernel-debug.mount");
1582 }
1583 }
1584
1585 sub enter {
1586 my ($self) = @_;
1587
1588 my $veid = $self->{veid};
1589 my $conffile = $self->{veconffile};
1590
1591 my $vestat = $self->ve_status();
1592
1593 if (!$vestat->{exist}) {
1594 $self->logmsg ("Please create the appliance first (bootstrap)");
1595 return;
1596 }
1597
1598 if (!$vestat->{running}) {
1599 $self->run_command ("lxc-start -n $veid -f $conffile");
1600 }
1601
1602 system ("lxc-attach -n $veid --rcfile $conffile --clear-env");
1603 }
1604
1605 sub ve_mysql_command {
1606 my ($self, $sql, $password) = @_;
1607
1608 #my $bootstrap = "/usr/sbin/mysqld --bootstrap --user=mysql --skip-grant-tables " .
1609 #"--skip-bdb --skip-innodb --skip-ndbcluster";
1610
1611 $self->ve_command("mysql", $sql);
1612 }
1613
1614 sub ve_mysql_bootstrap {
1615 my ($self, $sql, $password) = @_;
1616
1617 my $cmd = "/usr/sbin/mysqld --bootstrap --user=mysql --skip-grant-tables --skip-bdb --skip-innodb --skip-ndbcluster";
1618 $self->ve_command($cmd, $sql);
1619 }
1620
1621 sub compute_required {
1622 my ($self, $pkglist) = @_;
1623
1624 my $pkginfo = $self->pkginfo();
1625 my $instpkgs = $self->read_installed ();
1626
1627 my $closure = {};
1628 __record_provides($pkginfo, $closure, [keys $instpkgs->%*]);
1629
1630 return $self->closure ($closure, $pkglist);
1631 }
1632
1633 sub task_postgres {
1634 my ($self, $opts) = @_;
1635
1636 my @supp = ('7.4', '8.1');
1637 my $pgversion; # NOTE: not setting that defaults to the distro default, normally the best choice
1638
1639 my $suite = $self->{config}->{suite};
1640
1641 if ($suite eq 'buster') {
1642 @supp = ('11');
1643 $pgversion = '11';
1644 } elsif ($suite eq 'bullseye') {
1645 @supp = ('13');
1646 } elsif ($suite eq 'bookworm') {
1647 @supp = ('15');
1648 }
1649 $pgversion = $opts->{version} if $opts->{version};
1650
1651 my $required;
1652 if (defined($pgversion)) {
1653 die "unsupported postgres version '$pgversion'\n" if !grep { $pgversion eq $_; } @supp;
1654
1655 $required = $self->compute_required (["postgresql-$pgversion"]);
1656 } else {
1657 $required = $self->compute_required (["postgresql"]);
1658 }
1659
1660 $self->cache_packages ($required);
1661
1662 $self->ve_dpkg ('install', @$required);
1663
1664 my $iscript = "postgresql-$pgversion";
1665 $self->ve_command ("/etc/init.d/$iscript start") if $opts->{start};
1666 }
1667
1668 sub task_mysql {
1669 my ($self, $opts) = @_;
1670
1671 my $password = $opts->{password};
1672 my $rootdir = $self->{rootfs};
1673
1674 my $suite = $self->{config}->{suite};
1675
1676 my $required = $self->compute_required(['mariadb-server']);
1677
1678 $self->cache_packages($required);
1679
1680 $self->ve_dpkg ('install', @$required);
1681
1682 # fix security (see /usr/bin/mysql_secure_installation)
1683 my $sql = "DELETE FROM mysql.user WHERE User='';\n" .
1684 "DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';\n" .
1685 "FLUSH PRIVILEGES;\n";
1686 $self->ve_mysql_bootstrap ($sql);
1687
1688 if ($password) {
1689
1690 my $rpw = $password eq 'random' ? 'admin' : $password;
1691
1692 my $sql = "USE mysql;\n" .
1693 "UPDATE user SET password=PASSWORD(\"$rpw\") WHERE user='root';\n" .
1694 "FLUSH PRIVILEGES;\n";
1695 $self->ve_mysql_bootstrap ($sql);
1696
1697 write_file ("[client]\nuser=root\npassword=\"$rpw\"\n", "$rootdir/root/.my.cnf", 0600);
1698 if ($password eq 'random') {
1699 $self->install_init_script ($script_mysql_randompw, 2, 20);
1700 }
1701 }
1702
1703 $self->ve_command("/etc/init.d/mysql start") if $opts->{start}; # FIXME: use systemd service?!
1704 }
1705
1706 sub task_php {
1707 my ($self, $opts) = @_;
1708
1709 my $memlimit = $opts->{memlimit};
1710 my $rootdir = $self->{rootfs};
1711 my $suite = $self->{config}->{suite};
1712
1713 my $base_set = [qw(php-cli libapache2-mod-php php-gd)];
1714 my $required = $self->compute_required($base_set);
1715
1716 $self->cache_packages ($required);
1717
1718 $self->ve_dpkg ('install', @$required);
1719
1720 if ($memlimit) {
1721 my $sed_cmd = ['sed', '-e', "s/^\\s*memory_limit\\s*=.*;/memory_limit = ${memlimit}M;/", '-i'];
1722 my $found = 0;
1723 for my $fn (glob("'${rootdir}/etc/php/*/apache2/php.ini'")) {
1724 push @$sed_cmd, "$rootdir/$fn";
1725 $found = 1;
1726 }
1727 if (!$found) {
1728 warn "WARN: did not found any php.ini to set the memlimit!\n";
1729 return;
1730 }
1731 $self->run_command($sed_cmd);
1732 }
1733 }
1734
1735 sub install {
1736 my ($self, $pkglist, $unpack) = @_;
1737
1738 my $required = $self->compute_required ($pkglist);
1739
1740 $self->cache_packages ($required);
1741
1742 $self->ve_dpkg ($unpack ? 'unpack' : 'install', @$required);
1743 }
1744
1745 sub cleanup {
1746 my ($self, $distclean) = @_;
1747
1748 unlink $self->{logfile};
1749 unlink "$self->{targetname}.tar";
1750 unlink "$self->{targetname}.tar.gz";
1751
1752 $self->ve_destroy ();
1753 unlink ".veid";
1754
1755 rmtree $self->{cachedir} if $distclean && !$self->{config}->{cachedir};
1756
1757 rmtree $self->{infodir};
1758
1759 }
1760
1761 1;