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