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