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