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