]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuServer/Cloudinit.pm
introduce one global CLOUDINIT_DISK_SIZE constant
[qemu-server.git] / PVE / QemuServer / Cloudinit.pm
1 package PVE::QemuServer::Cloudinit;
2
3 use strict;
4 use warnings;
5
6 use File::Path;
7 use Digest::SHA;
8 use URI::Escape;
9
10 use PVE::Tools qw(run_command file_set_contents);
11 use PVE::Storage;
12 use PVE::QemuServer;
13
14 use constant CLOUDINIT_DISK_SIZE => 4 * 1024 * 1024; # 4MiB in bytes
15
16 sub commit_cloudinit_disk {
17 my ($conf, $vmid, $drive, $volname, $storeid, $files, $label) = @_;
18
19 my $path = "/run/pve/cloudinit/$vmid/";
20 mkpath $path;
21 foreach my $filepath (keys %$files) {
22 if ($filepath !~ m@^(.*)\/[^/]+$@) {
23 die "internal error: bad file name in cloud-init image: $filepath\n";
24 }
25 my $dirname = $1;
26 mkpath "$path/$dirname";
27
28 my $contents = $files->{$filepath};
29 file_set_contents("$path/$filepath", $contents);
30 }
31
32 my $storecfg = PVE::Storage::config();
33 my $iso_path = PVE::Storage::path($storecfg, $drive->{file});
34 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
35 my $format = PVE::QemuServer::qemu_img_format($scfg, $volname);
36
37 # required before file_size_info, some existing vols won't show up else
38 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
39 eval { $plugin->activate_volume($storeid, $scfg, $volname) };
40
41 my $size = eval { PVE::Storage::file_size_info($iso_path) };
42 if ($size <= 0) {
43 $volname =~ m/(vm-$vmid-cloudinit(.\Q$format\E)?)/;
44 my $name = $1;
45 $size = 4 * 1024;
46 PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $format, $name, $size);
47 $size *= 1024; # vdisk alloc takes KB, qemu-img dd's osize takes byte
48 $plugin->activate_volume($storeid, $scfg, $volname);
49 }
50
51 eval {
52 run_command([['genisoimage', '-R', '-V', $label, $path],
53 ['qemu-img', 'dd', '-n', '-f', 'raw', '-O', $format,
54 'isize=0', "osize=$size", "of=$iso_path"]]);
55 };
56 my $err = $@;
57 rmtree($path);
58 die $err if $err;
59 }
60
61 sub get_cloudinit_format {
62 my ($conf) = @_;
63 if (defined(my $format = $conf->{citype})) {
64 return $format;
65 }
66
67 # No format specified, default based on ostype because windows'
68 # cloudbased-init only supports configdrivev2, whereas on linux we need
69 # to use mac addresses because regular cloudinit doesn't map 'ethX' to
70 # the new predicatble network device naming scheme.
71 if (defined(my $ostype = $conf->{ostype})) {
72 return 'configdrive2'
73 if PVE::QemuServer::windows_version($ostype);
74 }
75
76 return 'nocloud';
77 }
78
79 sub get_hostname_fqdn {
80 my ($conf, $vmid) = @_;
81 my $hostname = $conf->{name} // "VM$vmid";
82 my $fqdn;
83 if ($hostname =~ /\./) {
84 $fqdn = $hostname;
85 $hostname =~ s/\..*$//;
86 } elsif (my $search = $conf->{searchdomain}) {
87 $fqdn = "$hostname.$search";
88 }
89 return ($hostname, $fqdn);
90 }
91
92 sub get_dns_conf {
93 my ($conf) = @_;
94
95 # Same logic as in pve-container, but without the testcase special case
96 my $host_resolv_conf = PVE::INotify::read_file('resolvconf');
97
98 my $searchdomains = [
99 split(/\s+/, $conf->{searchdomain} // $host_resolv_conf->{search})
100 ];
101
102 my $nameserver = $conf->{nameserver};
103 if (!defined($nameserver)) {
104 $nameserver = [grep { $_ } $host_resolv_conf->@{qw(dns1 dns2 dns3)}];
105 } else {
106 $nameserver = [split(/\s+/, $nameserver)];
107 }
108
109 return ($searchdomains, $nameserver);
110 }
111
112 sub cloudinit_userdata {
113 my ($conf, $vmid) = @_;
114
115 my ($hostname, $fqdn) = get_hostname_fqdn($conf, $vmid);
116
117 my $content = "#cloud-config\n";
118
119 $content .= "hostname: $hostname\n";
120 $content .= "manage_etc_hosts: true\n";
121 $content .= "fqdn: $fqdn\n" if defined($fqdn);
122
123 my $username = $conf->{ciuser};
124 my $password = $conf->{cipassword};
125
126 $content .= "user: $username\n" if defined($username);
127 $content .= "disable_root: False\n" if defined($username) && $username eq 'root';
128 $content .= "password: $password\n" if defined($password);
129
130 if (defined(my $keys = $conf->{sshkeys})) {
131 $keys = URI::Escape::uri_unescape($keys);
132 $keys = [map { chomp $_; $_ } split(/\n/, $keys)];
133 $keys = [grep { /\S/ } @$keys];
134 $content .= "ssh_authorized_keys:\n";
135 foreach my $k (@$keys) {
136 $content .= " - $k\n";
137 }
138 }
139 $content .= "chpasswd:\n";
140 $content .= " expire: False\n";
141
142 if (!defined($username) || $username ne 'root') {
143 $content .= "users:\n";
144 $content .= " - default\n";
145 }
146
147 $content .= "package_upgrade: true\n";
148
149 return $content;
150 }
151
152 sub split_ip4 {
153 my ($ip) = @_;
154 my ($addr, $mask) = split('/', $ip);
155 die "not a CIDR: $ip\n" if !defined $mask;
156 return ($addr, $PVE::Network::ipv4_reverse_mask->[$mask]);
157 }
158
159 sub configdrive2_network {
160 my ($conf) = @_;
161
162 my $content = "auto lo\n";
163 $content .= "iface lo inet loopback\n\n";
164
165 my ($searchdomains, $nameservers) = get_dns_conf($conf);
166 if ($nameservers && @$nameservers) {
167 $nameservers = join(' ', @$nameservers);
168 $content .= " dns_nameservers $nameservers\n";
169 }
170 if ($searchdomains && @$searchdomains) {
171 $searchdomains = join(' ', @$searchdomains);
172 $content .= " dns_search $searchdomains\n";
173 }
174
175 my @ifaces = grep(/^net(\d+)$/, keys %$conf);
176 foreach my $iface (@ifaces) {
177 (my $id = $iface) =~ s/^net//;
178 next if !$conf->{"ipconfig$id"};
179 my $net = PVE::QemuServer::parse_ipconfig($conf->{"ipconfig$id"});
180 $id = "eth$id";
181
182 $content .="auto $id\n";
183 if ($net->{ip}) {
184 if ($net->{ip} eq 'dhcp') {
185 $content .= "iface $id inet dhcp\n";
186 } else {
187 my ($addr, $mask) = split_ip4($net->{ip});
188 $content .= "iface $id inet static\n";
189 $content .= " address $addr\n";
190 $content .= " netmask $mask\n";
191 $content .= " gateway $net->{gw}\n" if $net->{gw};
192 }
193 }
194 if ($net->{ip6}) {
195 if ($net->{ip6} =~ /^(auto|dhcp)$/) {
196 $content .= "iface $id inet6 $1\n";
197 } else {
198 my ($addr, $mask) = split('/', $net->{ip6});
199 $content .= "iface $id inet6 static\n";
200 $content .= " address $addr\n";
201 $content .= " netmask $mask\n";
202 $content .= " gateway $net->{gw6}\n" if $net->{gw6};
203 }
204 }
205 }
206
207 return $content;
208 }
209
210 sub configdrive2_metadata {
211 my ($uuid) = @_;
212 return <<"EOF";
213 {
214 "uuid": "$uuid",
215 "network_config": { "content_path": "/content/0000" }
216 }
217 EOF
218 }
219
220 sub generate_configdrive2 {
221 my ($conf, $vmid, $drive, $volname, $storeid) = @_;
222
223 my ($user_data, $network_data, $meta_data) = get_custom_cloudinit_files($conf);
224 $user_data = cloudinit_userdata($conf, $vmid) if !defined($user_data);
225 $network_data = configdrive2_network($conf) if !defined($network_data);
226
227 if (!defined($meta_data)) {
228 my $digest_data = $user_data . $network_data;
229 my $uuid_str = Digest::SHA::sha1_hex($digest_data);
230
231 $meta_data = configdrive2_metadata($uuid_str);
232 }
233 my $files = {
234 '/openstack/latest/user_data' => $user_data,
235 '/openstack/content/0000' => $network_data,
236 '/openstack/latest/meta_data.json' => $meta_data
237 };
238 commit_cloudinit_disk($conf, $vmid, $drive, $volname, $storeid, $files, 'config-2');
239 }
240
241 sub nocloud_network_v2 {
242 my ($conf) = @_;
243
244 my $content = '';
245
246 my $head = "version: 2\n"
247 . "ethernets:\n";
248
249 my $dns_done;
250
251 my @ifaces = grep(/^net(\d+)$/, keys %$conf);
252 foreach my $iface (@ifaces) {
253 (my $id = $iface) =~ s/^net//;
254 next if !$conf->{"ipconfig$id"};
255
256 # indentation - network interfaces are inside an 'ethernets' hash
257 my $i = ' ';
258
259 my $net = PVE::QemuServer::parse_net($conf->{$iface});
260 my $ipconfig = PVE::QemuServer::parse_ipconfig($conf->{"ipconfig$id"});
261
262 my $mac = $net->{macaddr}
263 or die "network interface '$iface' has no mac address\n";
264
265 $content .= "${i}$iface:\n";
266 $i .= ' ';
267 $content .= "${i}match:\n"
268 . "${i} macaddress: \"$mac\"\n"
269 . "${i}set-name: eth$id\n";
270 my @addresses;
271 if (defined(my $ip = $ipconfig->{ip})) {
272 if ($ip eq 'dhcp') {
273 $content .= "${i}dhcp4: true\n";
274 } else {
275 push @addresses, $ip;
276 }
277 }
278 if (defined(my $ip = $ipconfig->{ip6})) {
279 if ($ip eq 'dhcp') {
280 $content .= "${i}dhcp6: true\n";
281 } else {
282 push @addresses, $ip;
283 }
284 }
285 if (@addresses) {
286 $content .= "${i}addresses:\n";
287 $content .= "${i}- '$_'\n" foreach @addresses;
288 }
289 if (defined(my $gw = $ipconfig->{gw})) {
290 $content .= "${i}gateway4: '$gw'\n";
291 }
292 if (defined(my $gw = $ipconfig->{gw6})) {
293 $content .= "${i}gateway6: '$gw'\n";
294 }
295
296 next if $dns_done;
297 $dns_done = 1;
298
299 my ($searchdomains, $nameservers) = get_dns_conf($conf);
300 if ($searchdomains || $nameservers) {
301 $content .= "${i}nameservers:\n";
302 if (defined($nameservers) && @$nameservers) {
303 $content .= "${i} addresses:\n";
304 $content .= "${i} - '$_'\n" foreach @$nameservers;
305 }
306 if (defined($searchdomains) && @$searchdomains) {
307 $content .= "${i} search:\n";
308 $content .= "${i} - '$_'\n" foreach @$searchdomains;
309 }
310 }
311 }
312
313 return $head.$content;
314 }
315
316 sub nocloud_network {
317 my ($conf) = @_;
318
319 my $content = "version: 1\n"
320 . "config:\n";
321
322 my @ifaces = grep(/^net(\d+)$/, keys %$conf);
323 foreach my $iface (@ifaces) {
324 (my $id = $iface) =~ s/^net//;
325 next if !$conf->{"ipconfig$id"};
326
327 # indentation - network interfaces are inside an 'ethernets' hash
328 my $i = ' ';
329
330 my $net = PVE::QemuServer::parse_net($conf->{$iface});
331 my $ipconfig = PVE::QemuServer::parse_ipconfig($conf->{"ipconfig$id"});
332
333 my $mac = lc($net->{macaddr})
334 or die "network interface '$iface' has no mac address\n";
335
336 $content .= "${i}- type: physical\n"
337 . "${i} name: eth$id\n"
338 . "${i} mac_address: '$mac'\n"
339 . "${i} subnets:\n";
340 $i .= ' ';
341 if (defined(my $ip = $ipconfig->{ip})) {
342 if ($ip eq 'dhcp') {
343 $content .= "${i}- type: dhcp4\n";
344 } else {
345 my ($addr, $mask) = split_ip4($ip);
346 $content .= "${i}- type: static\n"
347 . "${i} address: '$addr'\n"
348 . "${i} netmask: '$mask'\n";
349 if (defined(my $gw = $ipconfig->{gw})) {
350 $content .= "${i} gateway: '$gw'\n";
351 }
352 }
353 }
354 if (defined(my $ip = $ipconfig->{ip6})) {
355 if ($ip eq 'dhcp') {
356 $content .= "${i}- type: dhcp6\n";
357 } elsif ($ip eq 'auto') {
358 # SLAAC is not supported by cloud-init, this fallback should work with an up-to-date netplan at least
359 $content .= "${i}- type: dhcp6\n";
360 } else {
361 $content .= "${i}- type: static\n"
362 . "${i} address: '$ip'\n";
363 if (defined(my $gw = $ipconfig->{gw6})) {
364 $content .= "${i} gateway: '$gw'\n";
365 }
366 }
367 }
368 }
369
370 my $i = ' ';
371 my ($searchdomains, $nameservers) = get_dns_conf($conf);
372 if ($searchdomains || $nameservers) {
373 $content .= "${i}- type: nameserver\n";
374 if (defined($nameservers) && @$nameservers) {
375 $content .= "${i} address:\n";
376 $content .= "${i} - '$_'\n" foreach @$nameservers;
377 }
378 if (defined($searchdomains) && @$searchdomains) {
379 $content .= "${i} search:\n";
380 $content .= "${i} - '$_'\n" foreach @$searchdomains;
381 }
382 }
383
384 return $content;
385 }
386
387 sub nocloud_metadata {
388 my ($uuid) = @_;
389 return "instance-id: $uuid\n";
390 }
391
392 sub generate_nocloud {
393 my ($conf, $vmid, $drive, $volname, $storeid) = @_;
394
395 my ($user_data, $network_data, $meta_data) = get_custom_cloudinit_files($conf);
396 $user_data = cloudinit_userdata($conf, $vmid) if !defined($user_data);
397 $network_data = nocloud_network($conf) if !defined($network_data);
398
399 if (!defined($meta_data)) {
400 my $digest_data = $user_data . $network_data;
401 my $uuid_str = Digest::SHA::sha1_hex($digest_data);
402
403 $meta_data = nocloud_metadata($uuid_str);
404 }
405
406 my $files = {
407 '/user-data' => $user_data,
408 '/network-config' => $network_data,
409 '/meta-data' => $meta_data
410 };
411 commit_cloudinit_disk($conf, $vmid, $drive, $volname, $storeid, $files, 'cidata');
412 }
413
414 sub get_custom_cloudinit_files {
415 my ($conf) = @_;
416
417 my $cicustom = $conf->{cicustom};
418 my $files = $cicustom ? PVE::JSONSchema::parse_property_string('pve-qm-cicustom', $cicustom) : {};
419
420 my $network_volid = $files->{network};
421 my $user_volid = $files->{user};
422 my $meta_volid = $files->{meta};
423
424 my $storage_conf = PVE::Storage::config();
425
426 my $network_data;
427 if ($network_volid) {
428 $network_data = read_cloudinit_snippets_file($storage_conf, $network_volid);
429 }
430
431 my $user_data;
432 if ($user_volid) {
433 $user_data = read_cloudinit_snippets_file($storage_conf, $user_volid);
434 }
435
436 my $meta_data;
437 if ($meta_volid) {
438 $meta_data = read_cloudinit_snippets_file($storage_conf, $meta_volid);
439 }
440
441 return ($user_data, $network_data, $meta_data);
442 }
443
444 sub read_cloudinit_snippets_file {
445 my ($storage_conf, $volid) = @_;
446
447 my ($full_path, undef, $type) = PVE::Storage::path($storage_conf, $volid);
448 die "$volid is not in the snippets directory\n" if $type ne 'snippets';
449 return PVE::Tools::file_get_contents($full_path, 1 * 1024 * 1024);
450 }
451
452 my $cloudinit_methods = {
453 configdrive2 => \&generate_configdrive2,
454 nocloud => \&generate_nocloud,
455 };
456
457 sub generate_cloudinitconfig {
458 my ($conf, $vmid) = @_;
459
460 my $format = get_cloudinit_format($conf);
461
462 PVE::QemuServer::foreach_drive($conf, sub {
463 my ($ds, $drive) = @_;
464
465 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file}, 1);
466
467 return if !$volname || $volname !~ m/vm-$vmid-cloudinit/;
468
469 my $generator = $cloudinit_methods->{$format}
470 or die "missing cloudinit methods for format '$format'\n";
471
472 $generator->($conf, $vmid, $drive, $volname, $storeid);
473 });
474 }
475
476 1;