]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXCSetup/Base.pm
add regression test suite
[pve-container.git] / src / PVE / LXCSetup / Base.pm
1 package PVE::LXCSetup::Base;
2
3 use strict;
4 use warnings;
5
6 sub change_hostname {
7 my ($etc_hosts_data, $hostip, $oldname, $newname) = @_;
8
9 # fixme: searchdomain ?
10
11 my $done = 0;
12
13 my @lines;
14
15 foreach my $line (split(/\n/, $etc_hosts_data)) {
16 if ($line =~ m/^#/ || $line =~ m/^\s*$/) {
17 push @lines, $line;
18 next;
19 }
20
21 my ($ip, @names) = split(/\s+/, $line);
22 if (($ip eq '127.0.0.1') || ($ip eq '::1')) {
23 push @lines, $line;
24 next;
25 }
26
27 my $found = 0;
28 foreach my $name (@names) {
29 if ($name eq $oldname || $name eq $newname) {
30 $found = 1;
31 } else {
32 # fixme: record extra names?
33 }
34 }
35 $found = 1 if defined($hostip) && ($ip eq $hostip);
36
37 if ($found) {
38 if (!$done) {
39 if (defined($hostip)) {
40 push @lines, "$ip $newname";
41 } else {
42 push @lines, "127.0.1.1 $newname";
43 }
44 $done = 1;
45 }
46 next;
47 } else {
48 push @lines, $line;
49 }
50 }
51
52 if (!$done) {
53 if (defined($hostip)) {
54 push @lines, "$hostip $newname";
55 } else {
56 push @lines, "127.0.1.1 $newname";
57 }
58 }
59
60 my $found_localhost = 0;
61 foreach my $line (@lines) {
62 if ($line =~ m/^127.0.0.1\s/) {
63 $found_localhost = 1;
64 last;
65 }
66 }
67
68 if (!$found_localhost) {
69 unshift @lines, "127.0.0.1 localhost.localnet localhost";
70 }
71
72 $etc_hosts_data = join("\n", @lines) . "\n";
73
74 return $etc_hosts_data;
75 }
76
77 sub set_hostname {
78 my ($class, $conf) = @_;
79
80 my $hostname = $conf->{'lxc.utsname'} || 'debian';
81
82 $hostname =~ s/\..*$//;
83
84 my $rootfs = $conf->{'lxc.rootfs'};
85
86 my $hostname_fn = "$rootfs/etc/hostname";
87
88 my $oldname = PVE::Tools::file_read_firstline($hostname_fn) || 'debian';
89
90 my $hosts_fn = "$rootfs/etc/hosts";
91 my $etc_hosts_data = '';
92
93 if (-f $hosts_fn) {
94 $etc_hosts_data = PVE::Tools::file_get_contents($hosts_fn);
95 }
96
97 my $hostip = undef; # fixme;
98
99 $etc_hosts_data = change_hostname($etc_hosts_data, $hostip, $oldname, $hostname);
100
101 PVE::Tools::file_set_contents($hostname_fn, "$hostname\n");
102 PVE::Tools::file_set_contents($hosts_fn, $etc_hosts_data);
103 }
104
105 sub post_create {
106 my ($class, $conf) = @_;
107
108 $class->set_hostname($conf);
109
110 # fixme: what else (network, ...)
111 }
112
113 1;