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