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