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