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