]> git.proxmox.com Git - dab.git/blob - DAB.pm
ubuntu kinetic support
[dab.git] / DAB.pm
1 package PVE::DAB;
2
3 use strict;
4 use warnings;
5 use IO::File;
6 use File::Path;
7 use File::Basename;
8 use IO::Select;
9 use IPC::Open2;
10 use IPC::Open3;
11 use POSIX qw (LONG_MAX);
12 use UUID;
13 use Cwd;
14
15 # fixme: lock container ?
16
17 my $dablibdir = "/usr/lib/dab";
18 my $devicetar = "$dablibdir/devices.tar.gz";
19 my $default_env = "$dablibdir/scripts/defenv";
20 my $fake_init = "$dablibdir/scripts/init.pl";
21 my $script_ssh_init = "$dablibdir/scripts/ssh_gen_host_keys";
22 my $script_mysql_randompw = "$dablibdir/scripts/mysql_randompw";
23 my $script_init_urandom = "$dablibdir/scripts/init_urandom";
24
25 my $postfix_main_cf = <<EOD;
26 # See /usr/share/postfix/main.cf.dist for a commented, more complete version
27
28 smtpd_banner = \$myhostname ESMTP \$mail_name (Debian/GNU)
29 biff = no
30
31 # appending .domain is the MUA's job.
32 append_dot_mydomain = no
33
34 # Uncomment the next line to generate "delayed mail" warnings
35 #delay_warning_time = 4h
36
37 alias_maps = hash:/etc/aliases
38 alias_database = hash:/etc/aliases
39 mydestination = \$myhostname, localhost.\$mydomain, localhost
40 relayhost =
41 mynetworks = 127.0.0.0/8
42 inet_interfaces = loopback-only
43 recipient_delimiter = +
44
45 compatibility_level = 2
46
47 EOD
48
49 # produce apt compatible filenames (/var/lib/apt/lists)
50 sub __url_to_filename {
51 my $url = shift;
52
53 $url =~ s|^\S+://||;
54 $url =~ s|_|%5f|g;
55 $url =~ s|/|_|g;
56
57 return $url;
58 }
59
60 # defaults:
61 # origin: debian
62 # flags:
63 # systemd: true (except for devuan ostypes)
64 my $supported_suites = {
65 'bookworm' => {
66 ostype => "debian-12",
67 },
68 'bullseye' => {
69 ostype => "debian-11",
70 },
71 'buster' => {
72 ostype => "debian-10",
73 },
74 'stretch' => {
75 ostype => "debian-9.0",
76 },
77 'jessie' => {
78 ostype => "debian-8.0",
79 },
80 'wheezy' => {
81 flags => {
82 systemd => 0,
83 },
84 ostype => "debian-7.0",
85 },
86 'squeeze' => {
87 flags => {
88 systemd => 0,
89 },
90 ostype => "debian-6.0",
91 },
92 'lenny' => {
93 flags => {
94 systemd => 0,
95 },
96 ostype => "debian-5.0",
97 },
98 'etch' => {
99 flags => {
100 systemd => 0,
101 },
102 ostype => "debian-4.0",
103 },
104
105 # DEVUAN (imply systemd = 0 default)
106 'devuan-jessie' => {
107 suite => 'jessie',
108 ostype => "devuan-1.0",
109 },
110 'devuan-ascii' => {
111 suite => 'ascii',
112 ostype => "devuan-2.0",
113 },
114 'ascii' => {
115 ostype => "devuan-2.0",
116 },
117 'beowulf' => {
118 ostype => "devuan-3.0",
119 },
120 'chimaera' => {
121 ostype => "devuan-4.0",
122 },
123 'daedalus' => {
124 ostype => "devuan-5.0",
125 },
126
127 # UBUNTU
128 'hardy' => {
129 flags => {
130 systemd => 0,
131 },
132 ostype => "ubuntu-8.04",
133 origin => 'ubuntu',
134 },
135 'intrepid' => {
136 flags => {
137 systemd => 0,
138 },
139 ostype => "ubuntu-8.10",
140 origin => 'ubuntu',
141 },
142 'jaunty' => {
143 flags => {
144 systemd => 0,
145 },
146 ostype => "ubuntu-9.04",
147 origin => 'ubuntu',
148 },
149 'precise' => {
150 flags => {
151 systemd => 0,
152 },
153 ostype => "ubuntu-12.04",
154 origin => 'ubuntu',
155 },
156 'trusty' => {
157 flags => {
158 systemd => 0,
159 },
160 ostype => "ubuntu-14.04",
161 origin => 'ubuntu',
162 },
163 'vivid' => {
164 ostype => "ubuntu-15.04",
165 origin => 'ubuntu',
166 },
167 'wily' => {
168 ostype => "ubuntu-15.10",
169 origin => 'ubuntu',
170 },
171 'xenial' => {
172 ostype => "ubuntu-16.04",
173 origin => 'ubuntu',
174 },
175 'yakkety' => {
176 ostype => "ubuntu-16.10",
177 origin => 'ubuntu',
178 },
179 'zesty' => {
180 ostype => "ubuntu-17.04",
181 origin => 'ubuntu',
182 },
183 'artful' => {
184 ostype => "ubuntu-17.10",
185 origin => 'ubuntu',
186 },
187 'bionic' => {
188 ostype => "ubuntu-18.04",
189 origin => 'ubuntu',
190 },
191 'cosmic' => {
192 ostype => "ubuntu-18.10",
193 origin => 'ubuntu',
194 },
195 'disco' => {
196 ostype => "ubuntu-19.04",
197 origin => 'ubuntu',
198 },
199 'eoan' => {
200 ostype => "ubuntu-19.10",
201 origin => 'ubuntu',
202 },
203 'focal' => {
204 ostype => "ubuntu-20.04",
205 origin => 'ubuntu',
206 },
207 'groovy' => {
208 ostype => "ubuntu-20.10",
209 origin => 'ubuntu',
210 },
211 'hirsute' => {
212 ostype => "ubuntu-21.04",
213 origin => 'ubuntu',
214 },
215 'impish' => {
216 ostype => "ubuntu-21.10",
217 origin => 'ubuntu',
218 },
219 'jammy' => {
220 ostype => "ubuntu-22.04",
221 origin => 'ubuntu',
222 },
223 'kinetic' => {
224 ostype => "ubuntu-22.10",
225 origin => 'ubuntu',
226 },
227 };
228
229 sub get_suite_info {
230 my ($suite) = @_;
231
232 my $suiteinfo = $supported_suites->{$suite} || die "unsupported suite '$suite'!\n";
233
234 # set defaults
235 $suiteinfo->{origin} //= 'debian';
236 $suiteinfo->{suite} //= $suite;
237
238 $suiteinfo->{flags} //= {};
239 if ($suiteinfo->{ostype} =~ /^devuan/) {
240 $suiteinfo->{flags}->{systemd} //= 0;
241 } else {
242 $suiteinfo->{flags}->{systemd} //= 1;
243 }
244
245 return $suiteinfo;
246 }
247
248 sub download {
249 my ($self, $url, $path) = @_;
250 my $tmpfn = "$path.tmp$$";
251
252 $self->logmsg ("download: $url\n");
253
254 eval { $self->run_command ("wget -q '$url' -O '$tmpfn'") };
255 if (my $err = $@) {
256 unlink $tmpfn;
257 die $err;
258 }
259
260 rename ($tmpfn, $path);
261 }
262
263 sub write_file {
264 my ($data, $file, $perm) = @_;
265
266 die "no filename" if !$file;
267
268 unlink $file;
269
270 my $fh = IO::File->new ($file, O_WRONLY | O_CREAT, $perm) ||
271 die "unable to open file '$file'";
272
273 print $fh $data;
274
275 $fh->close;
276 }
277
278 sub read_file {
279 my ($file) = @_;
280
281 die "no filename" if !$file;
282
283 my $fh = IO::File->new ($file) ||
284 die "unable to open file '$file'";
285
286 local $/; # slurp mode
287
288 my $data = <$fh>;
289
290 $fh->close;
291
292 return $data;
293 }
294
295 sub read_config {
296 my ($filename) = @_;
297
298 my $res = {};
299
300 my $fh = IO::File->new ("<$filename") || return $res;
301 my $rec = '';
302
303 while (defined (my $line = <$fh>)) {
304 next if $line =~ m/^\#/;
305 next if $line =~ m/^\s*$/;
306 $rec .= $line;
307 };
308
309 close ($fh);
310
311 chomp $rec;
312 $rec .= "\n";
313
314 while ($rec) {
315 if ($rec =~ s/^Description:\s*([^\n]*)(\n\s+.*)*$//si) {
316 $res->{headline} = $1;
317 chomp $res->{headline};
318 my $long = $2;
319 $long =~ s/^\s+/ /;
320 $res->{description} = $long;
321 chomp $res->{description};
322 } elsif ($rec =~ s/^([^:]+):\s*(.*\S)\s*\n//) {
323 my ($key, $value) = (lc ($1), $2);
324 if ($key eq 'source' || $key eq 'mirror') {
325 push @{$res->{$key}}, $value;
326 } else {
327 die "duplicate key '$key'\n" if defined ($res->{$key});
328 $res->{$key} = $value;
329 }
330 } else {
331 die "unable to parse config file: $rec";
332 }
333 }
334
335 die "unable to parse config file" if $rec;
336
337 return $res;
338 }
339
340 sub run_command {
341 my ($self, $cmd, $input, $getoutput) = @_;
342
343 my $reader = IO::File->new();
344 my $writer = IO::File->new();
345 my $error = IO::File->new();
346
347 my $orig_pid = $$;
348
349 my $cmdstr = ref ($cmd) eq 'ARRAY' ? join (' ', @$cmd) : $cmd;
350
351 my $pid;
352 eval {
353 if (ref ($cmd) eq 'ARRAY') {
354 $pid = open3 ($writer, $reader, $error, @$cmd) || die $!;
355 } else {
356 $pid = open3 ($writer, $reader, $error, $cmdstr) || die $!;
357 }
358 };
359
360 my $err = $@;
361
362 # catch exec errors
363 if ($orig_pid != $$) {
364 $self->logmsg ("ERROR: command '$cmdstr' failed - fork failed\n");
365 POSIX::_exit (1);
366 kill ('KILL', $$);
367 }
368
369 die $err if $err;
370
371 print $writer $input if defined $input;
372 close $writer;
373
374 my $select = IO::Select->new();
375 $select->add ($reader);
376 $select->add ($error);
377
378 my $res = '';
379 my $logfd = $self->{logfd};
380
381 while ($select->count) {
382 my @handles = $select->can_read ();
383
384 foreach my $h (@handles) {
385 my $buf = '';
386 my $count = sysread ($h, $buf, 4096);
387 if (!defined ($count)) {
388 waitpid ($pid, 0);
389 die "command '$cmdstr' failed: $!";
390 }
391 $select->remove ($h) if !$count;
392
393 print $logfd $buf;
394
395 $res .= $buf if $getoutput;
396 }
397 }
398
399 waitpid ($pid, 0);
400 my $ec = ($? >> 8);
401
402 die "command '$cmdstr' failed with exit code $ec\n" if $ec;
403
404 return $res;
405 }
406
407 sub logmsg {
408 my $self = shift;
409 print STDERR @_;
410 $self->writelog (@_);
411 }
412
413 sub writelog {
414 my $self = shift;
415 my $fd = $self->{logfd};
416 print $fd @_;
417 }
418
419 sub __sample_config {
420 my ($self) = @_;
421
422 my $data = '';
423 my $arch = $self->{config}->{architecture};
424
425 my $ostype = $self->{config}->{ostype};
426
427 if ($ostype =~ m/^de(bi|vu)an-/) {
428 $data .= "lxc.include = /usr/share/lxc/config/debian.common.conf\n";
429 } elsif ($ostype =~ m/^ubuntu-/) {
430 $data .= "lxc.include = /usr/share/lxc/config/ubuntu.common.conf\n";
431 } else {
432 die "unknown os type '$ostype'\n";
433 }
434 $data .= "lxc.uts.name = localhost\n";
435 $data .= "lxc.rootfs.path = $self->{rootfs}\n";
436
437 return $data;
438 }
439
440 sub __allocate_ve {
441 my ($self) = @_;
442
443 my $cid;
444 if (my $fd = IO::File->new (".veid")) {
445 $cid = <$fd>;
446 chomp $cid;
447 close ($fd);
448 }
449
450
451 $self->{working_dir} = getcwd;
452 $self->{veconffile} = "$self->{working_dir}/config";
453 $self->{rootfs} = "$self->{working_dir}/rootfs";
454
455 if ($cid) {
456 $self->{veid} = $cid;
457 return $cid;
458 }
459
460 my $uuid;
461 my $uuid_str;
462 UUID::generate($uuid);
463 UUID::unparse($uuid, $uuid_str);
464 $self->{veid} = $uuid_str;
465
466 my $fd = IO::File->new (">.veid") ||
467 die "unable to write '.veid'\n";
468 print $fd "$self->{veid}\n";
469 close ($fd);
470
471 my $cdata = $self->__sample_config();
472
473 my $fh = IO::File->new ($self->{veconffile}, O_WRONLY|O_CREAT|O_EXCL) ||
474 die "unable to write lxc config file '$self->{veconffile}' - $!";
475 print $fh $cdata;
476 close ($fh);
477
478 mkdir $self->{rootfs} || die "unable to create rootfs - $!";
479
480 $self->logmsg ("allocated VE $self->{veid}\n");
481
482 return $self->{veid};
483 }
484
485 # just use some simple heuristic for now, merge usr for releases newer than ubuntu 21.x or debian 11
486 sub can_usr_merge {
487 my ($self) = @_;
488
489 my $ostype = $self->{config}->{ostype};
490
491 # FIXME: add configuration override posibillity
492
493 if ($ostype =~ m/^debian-(\d+)/) {
494 return int($1) >= 11;
495 } elsif ($ostype =~ m/^ubuntu-(\d+)/) {
496 return int($1) >= 21;
497 }
498 return; # false
499 }
500
501 sub setup_usr_merge {
502 my ($self) = @_;
503
504 my $rootfs = $self->{rootfs};
505 my $arch = $self->{config}->{architecture};
506
507 # similar to https://salsa.debian.org/installer-team/debootstrap/-/blob/master/functions#L1354
508 my @merged_dirs = qw(bin sbin lib);
509
510 if ($arch eq 'amd64') {
511 push @merged_dirs, qw(lib32 lib64 libx32);
512 } elsif ($arch eq 'i386') {
513 push @merged_dirs, qw(lib64 libx32);
514 }
515
516 $self->logmsg ("setup usr-merge symlinks for '" . join("', '", @merged_dirs) . "'\n");
517
518 for my $dir (@merged_dirs) {
519 symlink("usr/$dir", "$rootfs/$dir") or warn "could not create symlink - $!\n";
520 mkpath "$rootfs/usr/$dir";
521 }
522 }
523
524 sub new {
525 my ($class, $config) = @_;
526
527 $class = ref ($class) || $class;
528
529 my $self = {};
530
531 $config = read_config ('dab.conf') if !$config;
532
533 $self->{config} = $config;
534
535 bless $self, $class;
536
537 $self->{logfile} = "logfile";
538 $self->{logfd} = IO::File->new (">>$self->{logfile}") ||
539 die "unable to open log file";
540
541 my $arch = $config->{architecture};
542 die "no 'architecture' specified\n" if !$arch;
543
544 die "unsupported architecture '$arch'\n"
545 if $arch !~ m/^(i386|amd64)$/;
546
547 my $suite = $config->{suite} || die "no 'suite' specified\n";
548
549 my $suiteinfo = get_suite_info($suite);
550 $suite = $suiteinfo->{suite};
551 $config->{ostype} = $suiteinfo->{ostype};
552
553 my $name = $config->{name} || die "no 'name' specified\n";
554
555 $name =~ m/^[a-z][0-9a-z\-\*\.]+$/ ||
556 die "illegal characters in name '$name'\n";
557
558 my $version = $config->{version};
559 die "no 'version' specified\n" if !$version;
560 die "no 'section' specified\n" if !$config->{section};
561 die "no 'description' specified\n" if !$config->{headline};
562 die "no 'maintainer' specified\n" if !$config->{maintainer};
563
564 if ($name =~ m/^$config->{ostype}/) {
565 $self->{targetname} = "${name}_${version}_$config->{architecture}";
566 } else {
567 $self->{targetname} = "$config->{ostype}-${name}_" .
568 "${version}_$config->{architecture}";
569 }
570
571 if (!$config->{source}) {
572 if (lc($suiteinfo->{origin}) eq 'debian') {
573 if ($suite eq 'etch' || $suite eq 'lenny') {
574 push @{$config->{source}}, (
575 'http://ftp.debian.org/debian SUITE main contrib',
576 'http://security.debian.org SUITE/updates main contrib',
577 );
578 } elsif ($suite eq 'bullseye' || $suite eq 'bookworm') {
579 push @{$config->{source}}, (
580 "http://ftp.debian.org/debian SUITE main contrib",
581 "http://ftp.debian.org/debian SUITE-updates main contrib",
582 "http://security.debian.org SUITE-security main contrib",
583 );
584 } else {
585 push @{$config->{source}}, (
586 "http://ftp.debian.org/debian SUITE main contrib",
587 "http://ftp.debian.org/debian SUITE-updates main contrib",
588 "http://security.debian.org SUITE/updates main contrib",
589 );
590 }
591 } elsif (lc($suiteinfo->{origin}) eq 'ubuntu') {
592 my $comp = "main restricted universe multiverse";
593 push @{$config->{source}}, (
594 "http://archive.ubuntu.com/ubuntu SUITE $comp",
595 "http://archive.ubuntu.com/ubuntu SUITE-updates $comp",
596 "http://archive.ubuntu.com/ubuntu SUITE-security $comp",
597 );
598 } else {
599 die "implement me";
600 }
601 }
602
603 my $sources = undef;
604
605 foreach my $s (@{$config->{source}}) {
606 if ($s =~ m@^\s*((http|ftp)://\S+)\s+(\S+)((\s+(\S+))+)$@) {
607 my ($url, $su, $components) = ($1, $3, $4);
608 $su =~ s/SUITE/$suite/;
609 $components =~ s/^\s+//;
610 $components =~ s/\s+$//;
611 my $ca;
612 foreach my $co (split (/\s+/, $components)) {
613 push @$ca, $co;
614 }
615 $ca = ['main'] if !$ca;
616
617 push @$sources, {
618 source => $url,
619 comp => $ca,
620 suite => $su,
621 };
622 } else {
623 die "syntax error in source spezification '$s'\n";
624 }
625 }
626
627 foreach my $m (@{$config->{mirror}}) {
628 if ($m =~ m@^\s*((http|ftp)://\S+)\s*=>\s*((http|ftp)://\S+)\s*$@) {
629 my ($ms, $md) = ($1, $3);
630 my $found;
631 foreach my $ss (@$sources) {
632 if ($ss->{source} eq $ms) {
633 $found = 1;
634 $ss->{mirror} = $md;
635 last;
636 }
637 }
638 die "unusable mirror $ms\n" if !$found;
639 } else {
640 die "syntax error in mirror spezification '$m'\n";
641 }
642 }
643
644 $self->{sources} = $sources;
645
646 $self->{infodir} = "info";
647
648 $self->__allocate_ve();
649
650 $self->{cachedir} = ($config->{cachedir} || 'cache') . "/$suite";;
651
652 my $incl = [qw (less ssh openssh-server logrotate)];
653
654 my $excl = [qw (modutils reiserfsprogs ppp pppconfig pppoe pppoeconf nfs-common mtools ntp)];
655
656 # ubuntu has too many dependencies on udev, so
657 # we cannot exclude it (instead we disable udevd)
658
659 if (lc($suiteinfo->{origin}) eq 'ubuntu' && $suiteinfo->{flags}->{systemd}) {
660 push @$incl, 'isc-dhcp-client';
661 push @$excl, qw(libmodule-build-perl plymouth plymouth-theme-ubuntu-text powermgmt-base);
662 if ($suite eq 'jammy') {
663 push @$excl, qw(fuse); # avoid fuse2 <-> fuse3 conflict
664 }
665 } elsif ($suite eq 'trusty') {
666 push @$excl, qw(systemd systemd-services libpam-systemd libsystemd-daemon0 memtest86+);
667 } elsif ($suite eq 'precise') {
668 push @$excl, qw(systemd systemd-services libpam-systemd libsystemd-daemon0 memtest86+ ubuntu-standard);
669 } elsif ($suite eq 'hardy') {
670 push @$excl, qw(kbd);
671 push @$excl, qw(apparmor apparmor-utils ntfs-3g friendly-recovery);
672 } elsif ($suite eq 'intrepid' || $suite eq 'jaunty') {
673 push @$excl, qw(apparmor apparmor-utils libapparmor1 libapparmor-perl libntfs-3g28);
674 push @$excl, qw(ntfs-3g friendly-recovery);
675 } elsif ($suite eq 'jessie') {
676 push @$incl, 'sysvinit-core'; # avoid systemd and udev
677 push @$incl, 'libperl4-corelibs-perl'; # to make lsof happy
678 push @$excl, qw(systemd systemd-sysv udev module-init-tools pciutils hdparm memtest86+ parted);
679 } elsif ($suite eq 'stretch' || $suite eq 'buster' || $suite eq 'bullseye' || $suite eq 'bookworm') {
680 push @$excl, qw(module-init-tools pciutils hdparm memtest86+ parted);
681 } else {
682 push @$excl, qw(udev module-init-tools pciutils hdparm memtest86+ parted);
683 }
684
685 $self->{incl} = $incl;
686 $self->{excl} = $excl;
687
688 return $self;
689 }
690
691 sub initialize {
692 my ($self) = @_;
693
694 my $infodir = $self->{infodir};
695 my $arch = $self->{config}->{architecture};
696
697 rmtree $infodir;
698 mkpath $infodir;
699
700 # truncate log
701 my $logfd = $self->{logfd} = IO::File->new (">$self->{logfile}") ||
702 die "unable to open log file";
703
704 my $COMPRESSORS = [
705 {
706 ext => 'xz',
707 decomp => 'xz -d',
708 },
709 {
710 ext => 'gz',
711 decomp => 'gzip -d',
712 },
713 ];
714
715 foreach my $ss (@{$self->{sources}}) {
716 my $src = $ss->{mirror} || $ss->{source};
717 my $path = "dists/$ss->{suite}/Release";
718 my $url = "$src/$path";
719 my $target = __url_to_filename ("$ss->{source}/$path");
720 eval {
721 $self->download ($url, "$infodir/$target");
722 $self->download ("$url.gpg", "$infodir/$target.gpg");
723 # fixme: impl. verify (needs --keyring option)
724 };
725 if (my $err = $@) {
726 print $logfd $@;
727 warn "Release info ignored\n";
728 };
729
730 foreach my $comp (@{$ss->{comp}}) {
731 foreach my $compressor (@$COMPRESSORS) {
732 $path = "dists/$ss->{suite}/$comp/binary-$arch/Packages.$compressor->{ext}";
733 $target = "$infodir/" . __url_to_filename ("$ss->{source}/$path");
734 my $pkgsrc = "$src/$path";
735 eval {
736 $self->download ($pkgsrc, $target);
737 $self->run_command ("$compressor->{decomp} '$target'");
738 };
739 if (my $err = $@) {
740 print $logfd "could not download Packages.$compressor->{ext}\n";
741 } else {
742 last;
743 }
744 }
745 }
746 }
747 }
748
749 sub write_config {
750 my ($self, $filename, $size) = @_;
751
752 my $config = $self->{config};
753
754 my $data = '';
755
756 $data .= "Name: $config->{name}\n";
757 $data .= "Version: $config->{version}\n";
758 $data .= "Type: lxc\n";
759 $data .= "OS: $config->{ostype}\n";
760 $data .= "Section: $config->{section}\n";
761 $data .= "Maintainer: $config->{maintainer}\n";
762 $data .= "Architecture: $config->{architecture}\n";
763 $data .= "Installed-Size: $size\n";
764
765 # optional
766 $data .= "Infopage: $config->{infopage}\n" if $config->{infopage};
767 $data .= "ManageUrl: $config->{manageurl}\n" if $config->{manageurl};
768 $data .= "Certified: $config->{certified}\n" if $config->{certified};
769
770 # description
771 $data .= "Description: $config->{headline}\n";
772 $data .= "$config->{description}\n" if $config->{description};
773
774 write_file ($data, $filename, 0644);
775 }
776
777 sub finalize {
778 my ($self, $opts) = @_;
779
780 my $suite = $self->{config}->{suite};
781 my $infodir = $self->{infodir};
782 my $arch = $self->{config}->{architecture};
783
784 my $instpkgs = $self->read_installed ();
785 my $pkginfo = $self->pkginfo();
786 my $veid = $self->{veid};
787 my $conffile = $self->{veconffile};
788 my $rootdir = $self->{rootfs};
789
790 my $vestat = $self->ve_status();
791 die "ve not running - unable to finalize\n" if !$vestat->{running};
792
793 # cleanup mysqld
794 if (-f "$rootdir/etc/init.d/mysql") {
795 $self->ve_command ("/etc/init.d/mysql stop");
796 }
797
798 if (!($opts->{keepmycnf} || (-f "$rootdir/etc/init.d/mysql_randompw"))) {
799 unlink "$rootdir/root/.my.cnf";
800 }
801
802 if ($suite eq 'etch') {
803 # enable apache2 startup
804 if ($instpkgs->{apache2}) {
805 write_file ("NO_START=0\n", "$rootdir/etc/default/apache2");
806 } else {
807 unlink "$rootdir/etc/default/apache2";
808 }
809 }
810 $self->logmsg ("cleanup package status\n");
811 # prevent auto selection of all standard, required or important
812 # packages which are not installed
813 foreach my $pkg (keys %$pkginfo) {
814 my $pri = $pkginfo->{$pkg}->{priority};
815 if ($pri && ($pri eq 'required' || $pri eq 'important'
816 || $pri eq 'standard')) {
817 if (!$instpkgs->{$pkg}) {
818 $self->ve_dpkg_set_selection ($pkg, 'purge');
819 }
820 }
821 }
822
823 $self->ve_command ("apt-get clean");
824
825 $self->logmsg ("update available package list\n");
826
827 $self->ve_command ("dpkg --clear-avail");
828 foreach my $ss (@{$self->{sources}}) {
829 my $relsrc = __url_to_filename ("$ss->{source}/dists/$ss->{suite}/Release");
830 if (-f "$infodir/$relsrc" && -f "$infodir/$relsrc.gpg") {
831 $self->run_command ("cp '$infodir/$relsrc' '$rootdir/var/lib/apt/lists/$relsrc'");
832 $self->run_command ("cp '$infodir/$relsrc.gpg' '$rootdir/var/lib/apt/lists/$relsrc.gpg'");
833 }
834 foreach my $comp (@{$ss->{comp}}) {
835 my $src = __url_to_filename ("$ss->{source}/dists/$ss->{suite}/" .
836 "$comp/binary-$arch/Packages");
837 my $target = "/var/lib/apt/lists/$src";
838 $self->run_command ("cp '$infodir/$src' '$rootdir/$target'");
839 $self->ve_command ("dpkg --merge-avail '$target'");
840 }
841 }
842
843 # set dselect default method
844 write_file ("apt apt\n", "$rootdir/var/lib/dpkg/cmethopt");
845
846 $self->ve_divert_remove ("/usr/sbin/policy-rc.d");
847
848 $self->ve_divert_remove ("/sbin/start-stop-daemon");
849
850 $self->ve_divert_remove ("/sbin/init");
851
852 # finally stop the VE
853 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
854
855 unlink "$rootdir/sbin/defenv";
856 unlink <$rootdir/root/dead.letter*>;
857 unlink "$rootdir/var/log/init.log";
858 unlink "$rootdir/aquota.group", "$rootdir/aquota.user";
859
860 write_file ("", "$rootdir/var/log/syslog");
861
862 my $get_path_size = sub {
863 my ($path) = @_;
864 my $sizestr = $self->run_command ("du -sm $path", undef, 1);
865 if ($sizestr =~ m/^(\d+)\s+\Q$path\E$/) {
866 return int($1);
867 } else {
868 die "unable to detect size for '$path'\n";
869 }
870 };
871
872 $self->logmsg ("detecting final appliance size: ");
873 my $size = $get_path_size->($rootdir);
874 $self->logmsg ("$size MB\n");
875
876 $self->write_config ("$rootdir/etc/appliance.info", $size);
877
878 $self->logmsg ("creating final appliance archive\n");
879
880 my $target = "$self->{targetname}.tar";
881
882 my $compressor = $opts->{compressor} // 'gz';
883 my $compressor2cmd_map = {
884 gz => 'gzip',
885 gzip => 'gzip',
886 zst => 'zstd -9',
887 zstd => 'zstd -9',
888 'zstd-max' => 'zstd -19 -T0', # maximal level where the decompressor can still run efficiently
889 };
890 my $compressor2ending = {
891 gzip => 'gz',
892 zstd => 'zst',
893 'zstd-max' => 'zst',
894 };
895 my $compressor_cmd = $compressor2cmd_map->{$compressor};
896 die "unkown compressor '$compressor', use one of: ". join(', ', sort keys %$compressor2cmd_map)
897 if !defined($compressor_cmd);
898
899 my $ending = $compressor2ending->{$compressor} // $compressor;
900 my $final_archive = "${target}.${ending}";
901 unlink $target;
902 unlink $final_archive;
903
904 $self->run_command ("tar cpf $target --numeric-owner -C '$rootdir' ./etc/appliance.info");
905 $self->run_command ("tar rpf $target --numeric-owner -C '$rootdir' --exclude ./etc/appliance.info .");
906 $self->run_command ("$compressor_cmd $target");
907
908 $self->logmsg ("detecting final commpressed appliance size: ");
909 $size = $get_path_size->($final_archive);
910 $self->logmsg ("$size MB\n");
911
912 $self->logmsg ("appliance archive: $final_archive\n");
913 }
914
915 sub read_installed {
916 my ($self) = @_;
917
918 my $rootdir = $self->{rootfs};
919
920 my $pkgfilelist = "$rootdir/var/lib/dpkg/status";
921 local $/ = '';
922 open(my $PKGLST, '<', $pkgfilelist) or die "unable to open '$pkgfilelist' - $!";
923
924 my $pkglist = {};
925
926 while (my $rec = <$PKGLST>) {
927 chomp $rec;
928 $rec =~ s/\n\s+/ /g;
929 $rec .= "\n";
930 my $res = {};
931
932 while ($rec =~ s/^([^:]+):\s+(.*?)\s*\n//) {
933 $res->{lc $1} = $2;
934 }
935
936 my $pkg = $res->{'package'};
937 if (my $status = $res->{status}) {
938 my @sa = split (/\s+/, $status);
939 my $stat = $sa[0];
940 if ($stat && ($stat ne 'purge')) {
941 $pkglist->{$pkg} = $res;
942 }
943 }
944 }
945
946 close ($PKGLST);
947
948 return $pkglist;
949 }
950
951 sub ve_status {
952 my ($self) = @_;
953
954 my $veid = $self->{veid};
955
956 my $res = { running => 0 };
957
958 $res->{exist} = 1 if -d "$self->{rootfs}/usr";
959
960 my $filename = "/proc/net/unix";
961
962 # similar test is used by lcxcontainers.c: list_active_containers
963 my $fh = IO::File->new ($filename, "r");
964 return $res if !$fh;
965
966 while (defined(my $line = <$fh>)) {
967 if ($line =~ m/^[a-f0-9]+:\s\S+\s\S+\s\S+\s\S+\s\S+\s\d+\s(\S+)$/) {
968 my $path = $1;
969 if ($path =~ m!^@/\S+/$veid/command$!) {
970 $res->{running} = 1;
971 }
972 }
973 }
974 close($fh);
975
976 return $res;
977 }
978
979 sub ve_command {
980 my ($self, $cmd, $input) = @_;
981
982 my $veid = $self->{veid};
983 my $conffile = $self->{veconffile};
984
985 if (ref ($cmd) eq 'ARRAY') {
986 unshift @$cmd, 'lxc-attach', '-n', $veid, '--rcfile', $conffile, '--clear-env', '--', 'defenv';
987 $self->run_command($cmd, $input);
988 } else {
989 $self->run_command("lxc-attach -n $veid --rcfile $conffile --clear-env -- defenv $cmd", $input);
990 }
991 }
992
993 # like ve_command, but pipes stdin correctly
994 sub ve_exec {
995 my ($self, @cmd) = @_;
996
997 my $veid = $self->{veid};
998 my $conffile = $self->{veconffile};
999
1000 my $reader;
1001 my $pid = open2($reader, "<&STDIN", 'lxc-attach', '-n', $veid, '--rcfile', $conffile, '--',
1002 'defenv', @cmd) || die "unable to exec command";
1003
1004 while (defined (my $line = <$reader>)) {
1005 $self->logmsg ($line);
1006 }
1007
1008 waitpid ($pid, 0);
1009 my $rc = $? >> 8;
1010
1011 die "ve_exec failed - status $rc\n" if $rc != 0;
1012 }
1013
1014 sub ve_divert_add {
1015 my ($self, $filename) = @_;
1016
1017 $self->ve_command ("dpkg-divert --add --divert '$filename.distrib' " .
1018 "--rename '$filename'");
1019 }
1020 sub ve_divert_remove {
1021 my ($self, $filename) = @_;
1022
1023 my $rootdir = $self->{rootfs};
1024
1025 unlink "$rootdir/$filename";
1026 $self->ve_command ("dpkg-divert --remove --rename '$filename'");
1027 }
1028
1029 sub ve_debconfig_set {
1030 my ($self, $dcdata) = @_;
1031
1032 my $rootdir = $self->{rootfs};
1033 my $cfgfile = "/tmp/debconf.txt";
1034 write_file ($dcdata, "$rootdir/$cfgfile");
1035 $self->ve_command ("debconf-set-selections $cfgfile");
1036 unlink "$rootdir/$cfgfile";
1037 }
1038
1039 sub ve_dpkg_set_selection {
1040 my ($self, $pkg, $status) = @_;
1041
1042 $self->ve_command ("dpkg --set-selections", "$pkg $status");
1043 }
1044
1045 sub ve_dpkg {
1046 my ($self, $cmd, @pkglist) = @_;
1047
1048 return if !scalar (@pkglist);
1049
1050 my $pkginfo = $self->pkginfo();
1051
1052 my $rootdir = $self->{rootfs};
1053 my $cachedir = $self->{cachedir};
1054
1055 my @files;
1056
1057 foreach my $pkg (@pkglist) {
1058 my $filename = $self->getpkgfile ($pkg);
1059 $self->run_command ("cp '$cachedir/$filename' '$rootdir/$filename'");
1060 push @files, "/$filename";
1061 $self->logmsg ("$cmd: $pkg\n");
1062 }
1063
1064 my $fl = join (' ', @files);
1065
1066 if ($cmd eq 'install') {
1067 $self->ve_command ("dpkg --force-depends --force-confold --install $fl");
1068 } elsif ($cmd eq 'unpack') {
1069 $self->ve_command ("dpkg --force-depends --unpack $fl");
1070 } else {
1071 die "internal error";
1072 }
1073
1074 foreach my $fn (@files) { unlink "$rootdir$fn"; }
1075 }
1076
1077 sub ve_destroy {
1078 my ($self) = @_;
1079
1080 my $veid = $self->{veid}; # fixme
1081 my $conffile = $self->{veconffile};
1082
1083 my $vestat = $self->ve_status();
1084 if ($vestat->{running}) {
1085 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
1086 }
1087
1088 rmtree $self->{rootfs};
1089 unlink $self->{veconffile};
1090 }
1091
1092 sub ve_init {
1093 my ($self) = @_;
1094
1095 my $veid = $self->{veid};
1096 my $conffile = $self->{veconffile};
1097
1098 $self->logmsg ("initialize VE $veid\n");
1099
1100 my $vestat = $self->ve_status();
1101 if ($vestat->{running}) {
1102 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
1103 }
1104
1105 rmtree $self->{rootfs};
1106 mkpath $self->{rootfs};
1107 }
1108
1109 sub __deb_version_cmp {
1110 my ($cur, $op, $new) = @_;
1111
1112 if (system("dpkg", "--compare-versions", $cur, $op, $new) == 0) {
1113 return 1;
1114 }
1115
1116 return 0;
1117 }
1118
1119 sub __parse_packages {
1120 my ($pkginfo, $filename, $src) = @_;
1121
1122 local $/ = '';
1123 open(my $PKGLST, '<', $filename) or 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 my $suite = $self->{config}->{suite};
1897
1898 my $base_set = [qw(php-cli libapache2-mod-php php-gd)];
1899 if ($suite =~ /(?:squeeze|wheezy|jessie)$/) {
1900 $self->logmsg("WARN: using EOL php release on EOL suite");
1901 $base_set = [qw(php5 php5-cli libapache2-mod-php5 php5-gd)];
1902 }
1903 my $required = $self->compute_required($base_set);
1904
1905 $self->cache_packages ($required);
1906
1907 $self->ve_dpkg ('install', @$required);
1908
1909 if ($memlimit) {
1910 my $sed_cmd = ['sed', '-e', "s/^\\s*memory_limit\\s*=.*;/memory_limit = ${memlimit}M;/", '-i'];
1911 if ($suite =~ /(?:squeeze|wheezy|jessie)$/) {
1912 push @$sed_cmd, "$rootdir/etc/php5/apache2/php.ini";
1913 } else {
1914 my $found = 0;
1915 for my $fn (glob("'${rootdir}/etc/php/*/apache2/php.ini'")) {
1916 push @$sed_cmd, "$rootdir/$fn";
1917 $found = 1;
1918 }
1919 if (!$found) {
1920 warn "WARN: did not found any php.ini to set the memlimit!\n";
1921 return;
1922 }
1923 }
1924 $self->run_command($sed_cmd);
1925 }
1926 }
1927
1928 sub install {
1929 my ($self, $pkglist, $unpack) = @_;
1930
1931 my $required = $self->compute_required ($pkglist);
1932
1933 $self->cache_packages ($required);
1934
1935 $self->ve_dpkg ($unpack ? 'unpack' : 'install', @$required);
1936 }
1937
1938 sub cleanup {
1939 my ($self, $distclean) = @_;
1940
1941 unlink $self->{logfile};
1942 unlink "$self->{targetname}.tar";
1943 unlink "$self->{targetname}.tar.gz";
1944
1945 $self->ve_destroy ();
1946 unlink ".veid";
1947
1948 rmtree $self->{cachedir} if $distclean && !$self->{config}->{cachedir};
1949
1950 rmtree $self->{infodir};
1951
1952 }
1953
1954 1;