]> git.proxmox.com Git - pve-cluster.git/blame - data/PVE/Cluster.pm
handle Net::SSLeay errors correctly
[pve-cluster.git] / data / PVE / Cluster.pm
CommitLineData
fe000966
DM
1package PVE::Cluster;
2
3use strict;
7181f622 4use warnings;
7bac9ca5 5use POSIX qw(EEXIST ENOENT);
fe000966
DM
6use File::stat qw();
7use Socket;
8use Storable qw(dclone);
9use IO::File;
10use MIME::Base64;
440121dc 11use Digest::SHA;
fe000966 12use Digest::HMAC_SHA1;
26784563 13use Net::SSLeay;
fe000966
DM
14use PVE::Tools;
15use PVE::INotify;
16use PVE::IPCC;
17use PVE::SafeSyslog;
d0ad18e8 18use PVE::JSONSchema;
54d487bf 19use PVE::Network;
fe000966
DM
20use JSON;
21use RRDs;
22use Encode;
ed8eb70d 23use UUID;
fe000966
DM
24use base 'Exporter';
25
26our @EXPORT_OK = qw(
27cfs_read_file
28cfs_write_file
29cfs_register_file
30cfs_lock_file);
31
32use Data::Dumper; # fixme: remove
33
34# x509 certificate utils
35
36my $basedir = "/etc/pve";
37my $authdir = "$basedir/priv";
38my $lockdir = "/etc/pve/priv/lock";
39
40my $authprivkeyfn = "$authdir/authkey.key";
41my $authpubkeyfn = "$basedir/authkey.pub";
42my $pveca_key_fn = "$authdir/pve-root-ca.key";
43my $pveca_srl_fn = "$authdir/pve-root-ca.srl";
44my $pveca_cert_fn = "$basedir/pve-root-ca.pem";
45# this is just a secret accessable by the web browser
46# and is used for CSRF prevention
47my $pvewww_key_fn = "$basedir/pve-www.key";
48
49# ssh related files
50my $ssh_rsa_id_priv = "/root/.ssh/id_rsa";
51my $ssh_rsa_id = "/root/.ssh/id_rsa.pub";
52my $ssh_host_rsa_id = "/etc/ssh/ssh_host_rsa_key.pub";
53my $sshglobalknownhosts = "/etc/ssh/ssh_known_hosts";
54my $sshknownhosts = "/etc/pve/priv/known_hosts";
55my $sshauthkeys = "/etc/pve/priv/authorized_keys";
ac50b36d 56my $sshd_config_fn = "/etc/ssh/sshd_config";
fe000966 57my $rootsshauthkeys = "/root/.ssh/authorized_keys";
6056578e 58my $rootsshauthkeysbackup = "${rootsshauthkeys}.org";
f666cdde 59my $rootsshconfig = "/root/.ssh/config";
fe000966
DM
60
61my $observed = {
e1735a61 62 'vzdump.cron' => 1,
fe000966
DM
63 'storage.cfg' => 1,
64 'datacenter.cfg' => 1,
f6de131a 65 'replication.cfg' => 1,
cafc7309
DM
66 'corosync.conf' => 1,
67 'corosync.conf.new' => 1,
fe000966
DM
68 'user.cfg' => 1,
69 'domains.cfg' => 1,
70 'priv/shadow.cfg' => 1,
71 '/qemu-server/' => 1,
f71eee41 72 '/openvz/' => 1,
7f66b436 73 '/lxc/' => 1,
5a5417e6
DM
74 'ha/crm_commands' => 1,
75 'ha/manager_status' => 1,
76 'ha/resources.cfg' => 1,
77 'ha/groups.cfg' => 1,
e9af3eb7 78 'ha/fence.cfg' => 1,
9d4f69ff 79 'status.cfg' => 1,
fe000966
DM
80};
81
82# only write output if something fails
83sub run_silent_cmd {
84 my ($cmd) = @_;
85
86 my $outbuf = '';
87
88 my $record_output = sub {
89 $outbuf .= shift;
90 $outbuf .= "\n";
91 };
92
93 eval {
c53b111f 94 PVE::Tools::run_command($cmd, outfunc => $record_output,
fe000966
DM
95 errfunc => $record_output);
96 };
97
98 my $err = $@;
99
100 if ($err) {
101 print STDERR $outbuf;
102 die $err;
103 }
104}
105
106sub check_cfs_quorum {
01dddfb9
DM
107 my ($noerr) = @_;
108
fe000966
DM
109 # note: -w filename always return 1 for root, so wee need
110 # to use File::lstat here
111 my $st = File::stat::lstat("$basedir/local");
01dddfb9
DM
112 my $quorate = ($st && (($st->mode & 0200) != 0));
113
114 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
115
116 return $quorate;
fe000966
DM
117}
118
119sub check_cfs_is_mounted {
120 my ($noerr) = @_;
121
122 my $res = -l "$basedir/local";
123
124 die "pve configuration filesystem not mounted\n"
125 if !$res && !$noerr;
126
127 return $res;
128}
129
130sub gen_local_dirs {
131 my ($nodename) = @_;
132
133 check_cfs_is_mounted();
134
135 my @required_dirs = (
136 "$basedir/priv",
c53b111f 137 "$basedir/nodes",
fe000966 138 "$basedir/nodes/$nodename",
7f66b436 139 "$basedir/nodes/$nodename/lxc",
a1c08cfa
DM
140 "$basedir/nodes/$nodename/qemu-server",
141 "$basedir/nodes/$nodename/openvz",
fe000966 142 "$basedir/nodes/$nodename/priv");
c53b111f 143
fe000966
DM
144 foreach my $dir (@required_dirs) {
145 if (! -d $dir) {
62613060 146 mkdir($dir) || $! == EEXIST || die "unable to create directory '$dir' - $!\n";
fe000966
DM
147 }
148 }
149}
150
151sub gen_auth_key {
152
153 return if -f "$authprivkeyfn";
154
155 check_cfs_is_mounted();
156
62613060 157 mkdir $authdir || $! == EEXIST || die "unable to create dir '$authdir' - $!\n";
fe000966 158
2d899b19 159 run_silent_cmd(['openssl', 'genrsa', '-out', $authprivkeyfn, '2048']);
fe000966 160
de4b4155 161 run_silent_cmd(['openssl', 'rsa', '-in', $authprivkeyfn, '-pubout', '-out', $authpubkeyfn]);
fe000966
DM
162}
163
164sub gen_pveca_key {
165
166 return if -f $pveca_key_fn;
167
168 eval {
147661a8 169 run_silent_cmd(['openssl', 'genrsa', '-out', $pveca_key_fn, '4096']);
fe000966
DM
170 };
171
172 die "unable to generate pve ca key:\n$@" if $@;
173}
174
175sub gen_pveca_cert {
176
177 if (-f $pveca_key_fn && -f $pveca_cert_fn) {
178 return 0;
179 }
180
181 gen_pveca_key();
182
183 # we try to generate an unique 'subject' to avoid browser problems
184 # (reused serial numbers, ..)
ed8eb70d
FG
185 my $uuid;
186 UUID::generate($uuid);
187 my $uuid_str;
188 UUID::unparse($uuid, $uuid_str);
fe000966
DM
189
190 eval {
f5566fc6
FG
191 # wrap openssl with faketime to prevent bug #904
192 run_silent_cmd(['faketime', 'yesterday', 'openssl', 'req', '-batch',
193 '-days', '3650', '-new', '-x509', '-nodes', '-key',
fe000966 194 $pveca_key_fn, '-out', $pveca_cert_fn, '-subj',
ed8eb70d 195 "/CN=Proxmox Virtual Environment/OU=$uuid_str/O=PVE Cluster Manager CA/"]);
fe000966
DM
196 };
197
198 die "generating pve root certificate failed:\n$@" if $@;
199
200 return 1;
201}
202
203sub gen_pve_ssl_key {
204 my ($nodename) = @_;
205
206 die "no node name specified" if !$nodename;
207
208 my $pvessl_key_fn = "$basedir/nodes/$nodename/pve-ssl.key";
209
210 return if -f $pvessl_key_fn;
211
212 eval {
213 run_silent_cmd(['openssl', 'genrsa', '-out', $pvessl_key_fn, '2048']);
214 };
215
216 die "unable to generate pve ssl key for node '$nodename':\n$@" if $@;
217}
218
219sub gen_pve_www_key {
220
221 return if -f $pvewww_key_fn;
222
223 eval {
224 run_silent_cmd(['openssl', 'genrsa', '-out', $pvewww_key_fn, '2048']);
225 };
226
227 die "unable to generate pve www key:\n$@" if $@;
228}
229
230sub update_serial {
231 my ($serial) = @_;
232
233 PVE::Tools::file_set_contents($pveca_srl_fn, $serial);
234}
235
236sub gen_pve_ssl_cert {
237 my ($force, $nodename, $ip) = @_;
238
239 die "no node name specified" if !$nodename;
240 die "no IP specified" if !$ip;
241
242 my $pvessl_cert_fn = "$basedir/nodes/$nodename/pve-ssl.pem";
243
244 return if !$force && -f $pvessl_cert_fn;
245
8acde170 246 my $names = "IP:127.0.0.1,IP:::1,DNS:localhost";
fe000966
DM
247
248 my $rc = PVE::INotify::read_file('resolvconf');
249
250 $names .= ",IP:$ip";
c53b111f 251
fe000966
DM
252 my $fqdn = $nodename;
253
254 $names .= ",DNS:$nodename";
255
256 if ($rc && $rc->{search}) {
257 $fqdn = $nodename . "." . $rc->{search};
258 $names .= ",DNS:$fqdn";
259 }
260
261 my $sslconf = <<__EOD;
262RANDFILE = /root/.rnd
263extensions = v3_req
264
265[ req ]
266default_bits = 2048
267distinguished_name = req_distinguished_name
268req_extensions = v3_req
269prompt = no
270string_mask = nombstr
271
272[ req_distinguished_name ]
273organizationalUnitName = PVE Cluster Node
274organizationName = Proxmox Virtual Environment
275commonName = $fqdn
276
277[ v3_req ]
278basicConstraints = CA:FALSE
e544d064 279extendedKeyUsage = serverAuth
fe000966
DM
280subjectAltName = $names
281__EOD
282
283 my $cfgfn = "/tmp/pvesslconf-$$.tmp";
284 my $fh = IO::File->new ($cfgfn, "w");
285 print $fh $sslconf;
286 close ($fh);
287
288 my $reqfn = "/tmp/pvecertreq-$$.tmp";
289 unlink $reqfn;
290
291 my $pvessl_key_fn = "$basedir/nodes/$nodename/pve-ssl.key";
292 eval {
293 run_silent_cmd(['openssl', 'req', '-batch', '-new', '-config', $cfgfn,
294 '-key', $pvessl_key_fn, '-out', $reqfn]);
295 };
296
297 if (my $err = $@) {
298 unlink $reqfn;
299 unlink $cfgfn;
300 die "unable to generate pve certificate request:\n$err";
301 }
302
303 update_serial("0000000000000000") if ! -f $pveca_srl_fn;
304
305 eval {
f5566fc6
FG
306 # wrap openssl with faketime to prevent bug #904
307 run_silent_cmd(['faketime', 'yesterday', 'openssl', 'x509', '-req',
308 '-in', $reqfn, '-days', '3650', '-out', $pvessl_cert_fn,
309 '-CAkey', $pveca_key_fn, '-CA', $pveca_cert_fn,
310 '-CAserial', $pveca_srl_fn, '-extfile', $cfgfn]);
fe000966
DM
311 };
312
313 if (my $err = $@) {
314 unlink $reqfn;
315 unlink $cfgfn;
316 die "unable to generate pve ssl certificate:\n$err";
317 }
318
319 unlink $cfgfn;
320 unlink $reqfn;
321}
322
323sub gen_pve_node_files {
324 my ($nodename, $ip, $opt_force) = @_;
325
326 gen_local_dirs($nodename);
327
328 gen_auth_key();
329
330 # make sure we have a (cluster wide) secret
331 # for CSRFR prevention
332 gen_pve_www_key();
333
334 # make sure we have a (per node) private key
335 gen_pve_ssl_key($nodename);
336
337 # make sure we have a CA
338 my $force = gen_pveca_cert();
339
340 $force = 1 if $opt_force;
341
342 gen_pve_ssl_cert($force, $nodename, $ip);
343}
344
bd0ae7ff
DM
345my $vzdump_cron_dummy = <<__EOD;
346# cluster wide vzdump cron schedule
347# Atomatically generated file - do not edit
348
349PATH="/usr/sbin:/usr/bin:/sbin:/bin"
350
351__EOD
352
353sub gen_pve_vzdump_symlink {
354
e1735a61 355 my $filename = "/etc/pve/vzdump.cron";
bd0ae7ff
DM
356
357 my $link_fn = "/etc/cron.d/vzdump";
358
359 if ((-f $filename) && (! -l $link_fn)) {
360 rename($link_fn, "/root/etc_cron_vzdump.org"); # make backup if file exists
361 symlink($filename, $link_fn);
362 }
363}
364
365sub gen_pve_vzdump_files {
366
e1735a61 367 my $filename = "/etc/pve/vzdump.cron";
bd0ae7ff
DM
368
369 PVE::Tools::file_set_contents($filename, $vzdump_cron_dummy)
370 if ! -f $filename;
371
372 gen_pve_vzdump_symlink();
373};
374
fe000966
DM
375my $versions = {};
376my $vmlist = {};
377my $clinfo = {};
378
379my $ipcc_send_rec = sub {
380 my ($msgid, $data) = @_;
381
382 my $res = PVE::IPCC::ipcc_send_rec($msgid, $data);
383
dd856b4d 384 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
fe000966
DM
385
386 return $res;
387};
388
389my $ipcc_send_rec_json = sub {
390 my ($msgid, $data) = @_;
391
392 my $res = PVE::IPCC::ipcc_send_rec($msgid, $data);
393
dd856b4d 394 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
fe000966
DM
395
396 return decode_json($res);
397};
398
399my $ipcc_get_config = sub {
400 my ($path) = @_;
401
402 my $bindata = pack "Z*", $path;
2db32d95
DM
403 my $res = PVE::IPCC::ipcc_send_rec(6, $bindata);
404 if (!defined($res)) {
7bac9ca5
WB
405 if ($! != 0) {
406 return undef if $! == ENOENT;
407 die "$!\n";
408 }
2db32d95
DM
409 return '';
410 }
411
412 return $res;
fe000966
DM
413};
414
415my $ipcc_get_status = sub {
416 my ($name, $nodename) = @_;
417
418 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
419 return PVE::IPCC::ipcc_send_rec(5, $bindata);
420};
421
422my $ipcc_update_status = sub {
423 my ($name, $data) = @_;
424
425 my $raw = ref($data) ? encode_json($data) : $data;
426 # update status
427 my $bindata = pack "Z[256]Z*", $name, $raw;
428
429 return &$ipcc_send_rec(4, $bindata);
430};
431
432my $ipcc_log = sub {
433 my ($priority, $ident, $tag, $msg) = @_;
434
435 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes::length($ident) + 1,
436 bytes::length($tag) + 1, $ident, $tag, $msg;
437
438 return &$ipcc_send_rec(7, $bindata);
439};
440
441my $ipcc_get_cluster_log = sub {
442 my ($user, $max) = @_;
443
444 $max = 0 if !defined($max);
445
446 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
447 return &$ipcc_send_rec(8, $bindata);
448};
449
450my $ccache = {};
451
452sub cfs_update {
686801e4 453 my ($fail) = @_;
fe000966
DM
454 eval {
455 my $res = &$ipcc_send_rec_json(1);
456 #warn "GOT1: " . Dumper($res);
457 die "no starttime\n" if !$res->{starttime};
458
459 if (!$res->{starttime} || !$versions->{starttime} ||
460 $res->{starttime} != $versions->{starttime}) {
461 #print "detected changed starttime\n";
462 $vmlist = {};
463 $clinfo = {};
464 $ccache = {};
465 }
466
467 $versions = $res;
468 };
469 my $err = $@;
470 if ($err) {
471 $versions = {};
472 $vmlist = {};
473 $clinfo = {};
474 $ccache = {};
686801e4 475 die $err if $fail;
fe000966
DM
476 warn $err;
477 }
478
479 eval {
480 if (!$clinfo->{version} || $clinfo->{version} != $versions->{clinfo}) {
481 #warn "detected new clinfo\n";
482 $clinfo = &$ipcc_send_rec_json(2);
483 }
484 };
485 $err = $@;
486 if ($err) {
487 $clinfo = {};
686801e4 488 die $err if $fail;
fe000966
DM
489 warn $err;
490 }
491
492 eval {
493 if (!$vmlist->{version} || $vmlist->{version} != $versions->{vmlist}) {
494 #warn "detected new vmlist1\n";
495 $vmlist = &$ipcc_send_rec_json(3);
496 }
497 };
498 $err = $@;
499 if ($err) {
500 $vmlist = {};
686801e4 501 die $err if $fail;
fe000966
DM
502 warn $err;
503 }
504}
505
506sub get_vmlist {
507 return $vmlist;
508}
509
510sub get_clinfo {
511 return $clinfo;
512}
513
9ddd4ae9
DM
514sub get_members {
515 return $clinfo->{nodelist};
516}
517
fe000966
DM
518sub get_nodelist {
519
520 my $nodelist = $clinfo->{nodelist};
521
522 my $result = [];
523
524 my $nodename = PVE::INotify::nodename();
525
526 if (!$nodelist || !$nodelist->{$nodename}) {
527 return [ $nodename ];
528 }
529
530 return [ keys %$nodelist ];
531}
532
1b36b6b1 533# $data must be a chronological descending ordered array of tasks
fe000966
DM
534sub broadcast_tasklist {
535 my ($data) = @_;
536
1b36b6b1
TL
537 # the serialized list may not get bigger than 32kb (CFS_MAX_STATUS_SIZE
538 # from pmxcfs) - drop older items until we satisfy this constraint
539 my $size = length(encode_json($data));
540 while ($size >= (32 * 1024)) {
541 pop @$data;
542 $size = length(encode_json($data));
543 }
544
fe000966
DM
545 eval {
546 &$ipcc_update_status("tasklist", $data);
547 };
548
549 warn $@ if $@;
550}
551
552my $tasklistcache = {};
553
554sub get_tasklist {
555 my ($nodename) = @_;
556
557 my $kvstore = $versions->{kvstore} || {};
558
559 my $nodelist = get_nodelist();
560
561 my $res = [];
562 foreach my $node (@$nodelist) {
563 next if $nodename && ($nodename ne $node);
564 eval {
565 my $ver = $kvstore->{$node}->{tasklist} if $kvstore->{$node};
566 my $cd = $tasklistcache->{$node};
c53b111f 567 if (!$cd || !$ver || !$cd->{version} ||
cebe16ec 568 ($cd->{version} != $ver)) {
fe000966
DM
569 my $raw = &$ipcc_get_status("tasklist", $node) || '[]';
570 my $data = decode_json($raw);
571 push @$res, @$data;
572 $cd = $tasklistcache->{$node} = {
573 data => $data,
574 version => $ver,
575 };
576 } elsif ($cd && $cd->{data}) {
577 push @$res, @{$cd->{data}};
578 }
579 };
580 my $err = $@;
581 syslog('err', $err) if $err;
582 }
583
584 return $res;
585}
586
587sub broadcast_rrd {
588 my ($rrdid, $data) = @_;
589
590 eval {
591 &$ipcc_update_status("rrd/$rrdid", $data);
592 };
593 my $err = $@;
594
595 warn $err if $err;
596}
597
598my $last_rrd_dump = 0;
599my $last_rrd_data = "";
600
601sub rrd_dump {
602
603 my $ctime = time();
604
605 my $diff = $ctime - $last_rrd_dump;
606 if ($diff < 2) {
607 return $last_rrd_data;
608 }
609
610 my $raw;
611 eval {
612 $raw = &$ipcc_send_rec(10);
613 };
614 my $err = $@;
615
616 if ($err) {
617 warn $err;
618 return {};
619 }
620
621 my $res = {};
622
c3fabca7
DM
623 if ($raw) {
624 while ($raw =~ s/^(.*)\n//) {
625 my ($key, @ela) = split(/:/, $1);
626 next if !$key;
627 next if !(scalar(@ela) > 1);
d2aae33e 628 $res->{$key} = [ map { $_ eq 'U' ? undef : $_ } @ela ];
c3fabca7 629 }
fe000966
DM
630 }
631
632 $last_rrd_dump = $ctime;
633 $last_rrd_data = $res;
634
635 return $res;
636}
637
638sub create_rrd_data {
639 my ($rrdname, $timeframe, $cf) = @_;
640
641 my $rrddir = "/var/lib/rrdcached/db";
642
643 my $rrd = "$rrddir/$rrdname";
644
645 my $setup = {
646 hour => [ 60, 70 ],
647 day => [ 60*30, 70 ],
648 week => [ 60*180, 70 ],
649 month => [ 60*720, 70 ],
650 year => [ 60*10080, 70 ],
651 };
652
653 my ($reso, $count) = @{$setup->{$timeframe}};
654 my $ctime = $reso*int(time()/$reso);
655 my $req_start = $ctime - $reso*$count;
656
657 $cf = "AVERAGE" if !$cf;
658
659 my @args = (
660 "-s" => $req_start,
661 "-e" => $ctime - 1,
662 "-r" => $reso,
663 );
664
665 my $socket = "/var/run/rrdcached.sock";
666 push @args, "--daemon" => "unix:$socket" if -S $socket;
667
668 my ($start, $step, $names, $data) = RRDs::fetch($rrd, $cf, @args);
669
670 my $err = RRDs::error;
671 die "RRD error: $err\n" if $err;
c53b111f
DM
672
673 die "got wrong time resolution ($step != $reso)\n"
fe000966
DM
674 if $step != $reso;
675
676 my $res = [];
677 my $fields = scalar(@$names);
678 for my $line (@$data) {
679 my $entry = { 'time' => $start };
680 $start += $step;
fe000966
DM
681 for (my $i = 0; $i < $fields; $i++) {
682 my $name = $names->[$i];
683 if (defined(my $val = $line->[$i])) {
684 $entry->{$name} = $val;
685 } else {
fba7c78c
DC
686 # leave empty fields undefined
687 # maybe make this configurable?
fe000966
DM
688 }
689 }
fba7c78c 690 push @$res, $entry;
fe000966
DM
691 }
692
693 return $res;
694}
695
696sub create_rrd_graph {
697 my ($rrdname, $timeframe, $ds, $cf) = @_;
698
699 # Using RRD graph is clumsy - maybe it
700 # is better to simply fetch the data, and do all display
701 # related things with javascript (new extjs html5 graph library).
c53b111f 702
fe000966
DM
703 my $rrddir = "/var/lib/rrdcached/db";
704
705 my $rrd = "$rrddir/$rrdname";
706
31938ad4
DM
707 my @ids = PVE::Tools::split_list($ds);
708
709 my $ds_txt = join('_', @ids);
710
711 my $filename = "${rrd}_${ds_txt}.png";
fe000966
DM
712
713 my $setup = {
714 hour => [ 60, 60 ],
715 day => [ 60*30, 70 ],
716 week => [ 60*180, 70 ],
717 month => [ 60*720, 70 ],
718 year => [ 60*10080, 70 ],
719 };
720
721 my ($reso, $count) = @{$setup->{$timeframe}};
722
723 my @args = (
724 "--imgformat" => "PNG",
725 "--border" => 0,
726 "--height" => 200,
727 "--width" => 800,
728 "--start" => - $reso*$count,
729 "--end" => 'now' ,
8daa8f04 730 "--lower-limit" => 0,
fe000966
DM
731 );
732
733 my $socket = "/var/run/rrdcached.sock";
734 push @args, "--daemon" => "unix:$socket" if -S $socket;
735
fe000966
DM
736 my @coldef = ('#00ddff', '#ff0000');
737
738 $cf = "AVERAGE" if !$cf;
739
740 my $i = 0;
741 foreach my $id (@ids) {
742 my $col = $coldef[$i++] || die "fixme: no color definition";
743 push @args, "DEF:${id}=$rrd:${id}:$cf";
744 my $dataid = $id;
745 if ($id eq 'cpu' || $id eq 'iowait') {
746 push @args, "CDEF:${id}_per=${id},100,*";
747 $dataid = "${id}_per";
748 }
749 push @args, "LINE2:${dataid}${col}:${id}";
750 }
751
a665376e
DM
752 push @args, '--full-size-mode';
753
31938ad4 754 # we do not really store data into the file
f7baa598 755 my $res = RRDs::graphv('-', @args);
fe000966
DM
756
757 my $err = RRDs::error;
758 die "RRD error: $err\n" if $err;
759
31938ad4 760 return { filename => $filename, image => $res->{image} };
fe000966
DM
761}
762
763# a fast way to read files (avoid fuse overhead)
764sub get_config {
765 my ($path) = @_;
766
d3a92ba7 767 return &$ipcc_get_config($path);
fe000966
DM
768}
769
770sub get_cluster_log {
771 my ($user, $max) = @_;
772
773 return &$ipcc_get_cluster_log($user, $max);
774}
775
776my $file_info = {};
777
778sub cfs_register_file {
779 my ($filename, $parser, $writer) = @_;
780
781 $observed->{$filename} || die "unknown file '$filename'";
782
783 die "file '$filename' already registered" if $file_info->{$filename};
784
785 $file_info->{$filename} = {
786 parser => $parser,
787 writer => $writer,
788 };
789}
790
791my $ccache_read = sub {
792 my ($filename, $parser, $version) = @_;
793
794 $ccache->{$filename} = {} if !$ccache->{$filename};
795
796 my $ci = $ccache->{$filename};
797
d3a92ba7
DM
798 if (!$ci->{version} || !$version || $ci->{version} != $version) {
799 # we always call the parser, even when the file does not exists
800 # (in that case $data is undef)
fe000966 801 my $data = get_config($filename);
fe000966
DM
802 $ci->{data} = &$parser("/etc/pve/$filename", $data);
803 $ci->{version} = $version;
804 }
805
806 my $res = ref($ci->{data}) ? dclone($ci->{data}) : $ci->{data};
807
808 return $res;
809};
810
811sub cfs_file_version {
812 my ($filename) = @_;
813
814 my $version;
815 my $infotag;
6e73d5c2 816 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
f71eee41 817 my ($type, $vmid) = ($1, $2);
fe000966
DM
818 if ($vmlist && $vmlist->{ids} && $vmlist->{ids}->{$vmid}) {
819 $version = $vmlist->{ids}->{$vmid}->{version};
820 }
f71eee41 821 $infotag = "/$type/";
fe000966
DM
822 } else {
823 $infotag = $filename;
824 $version = $versions->{$filename};
825 }
826
827 my $info = $file_info->{$infotag} ||
828 die "unknown file type '$filename'\n";
829
830 return wantarray ? ($version, $info) : $version;
831}
832
833sub cfs_read_file {
834 my ($filename) = @_;
835
c53b111f 836 my ($version, $info) = cfs_file_version($filename);
fe000966
DM
837 my $parser = $info->{parser};
838
839 return &$ccache_read($filename, $parser, $version);
840}
841
842sub cfs_write_file {
843 my ($filename, $data) = @_;
844
c53b111f 845 my ($version, $info) = cfs_file_version($filename);
fe000966
DM
846
847 my $writer = $info->{writer} || die "no writer defined";
848
849 my $fsname = "/etc/pve/$filename";
850
851 my $raw = &$writer($fsname, $data);
852
853 if (my $ci = $ccache->{$filename}) {
854 $ci->{version} = undef;
855 }
856
857 PVE::Tools::file_set_contents($fsname, $raw);
858}
859
860my $cfs_lock = sub {
861 my ($lockid, $timeout, $code, @param) = @_;
862
00ea8428
TL
863 my $prev_alarm = alarm(0); # suspend outer alarm early
864
fe000966 865 my $res;
bcdb1b3a 866 my $got_lock = 0;
fe000966
DM
867
868 # this timeout is for aquire the lock
869 $timeout = 10 if !$timeout;
870
871 my $filename = "$lockdir/$lockid";
872
fe000966
DM
873 eval {
874
875 mkdir $lockdir;
876
877 if (! -d $lockdir) {
6e13e20a 878 die "pve cluster filesystem not online.\n";
fe000966
DM
879 }
880
6e13e20a 881 my $timeout_err = sub { die "got lock request timeout\n"; };
bcdb1b3a 882 local $SIG{ALRM} = $timeout_err;
fe000966 883
bcdb1b3a
TL
884 while (1) {
885 alarm ($timeout);
886 $got_lock = mkdir($filename);
3fb23b5b 887 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
bcdb1b3a
TL
888
889 last if $got_lock;
890
3fb23b5b 891 $timeout_err->() if $timeout <= 0;
fe000966 892
02cd5e00 893 print STDERR "trying to aquire cfs lock '$lockid' ...\n";
bcdb1b3a
TL
894 utime (0, 0, $filename); # cfs unlock request
895 sleep(1);
fe000966
DM
896 }
897
898 # fixed command timeout: cfs locks have a timeout of 120
899 # using 60 gives us another 60 seconds to abort the task
fe000966 900 local $SIG{ALRM} = sub { die "got lock timeout - aborting command\n"; };
00ea8428 901 alarm(60);
fe000966 902
9c206b2b
DM
903 cfs_update(); # make sure we read latest versions inside code()
904
fe000966
DM
905 $res = &$code(@param);
906
907 alarm(0);
908 };
909
910 my $err = $@;
911
6e13e20a 912 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum(1);
fe000966 913
96857ee4 914 rmdir $filename if $got_lock; # if we held the lock always unlock again
fe000966 915
00ea8428
TL
916 alarm($prev_alarm);
917
fe000966 918 if ($err) {
6e13e20a 919 $@ = "error with cfs lock '$lockid': $err";
fe000966
DM
920 return undef;
921 }
922
923 $@ = undef;
924
925 return $res;
926};
927
928sub cfs_lock_file {
929 my ($filename, $timeout, $code, @param) = @_;
930
931 my $info = $observed->{$filename} || die "unknown file '$filename'";
932
933 my $lockid = "file-$filename";
934 $lockid =~ s/[.\/]/_/g;
935
936 &$cfs_lock($lockid, $timeout, $code, @param);
937}
938
939sub cfs_lock_storage {
940 my ($storeid, $timeout, $code, @param) = @_;
941
942 my $lockid = "storage-$storeid";
943
944 &$cfs_lock($lockid, $timeout, $code, @param);
945}
946
78897707
TL
947sub cfs_lock_domain {
948 my ($domainname, $timeout, $code, @param) = @_;
949
950 my $lockid = "domain-$domainname";
951
952 &$cfs_lock($lockid, $timeout, $code, @param);
953}
954
fe000966
DM
955my $log_levels = {
956 "emerg" => 0,
957 "alert" => 1,
958 "crit" => 2,
959 "critical" => 2,
960 "err" => 3,
961 "error" => 3,
962 "warn" => 4,
963 "warning" => 4,
964 "notice" => 5,
965 "info" => 6,
966 "debug" => 7,
967};
968
969sub log_msg {
970 my ($priority, $ident, $msg) = @_;
971
972 if (my $tmp = $log_levels->{$priority}) {
973 $priority = $tmp;
974 }
975
976 die "need numeric log priority" if $priority !~ /^\d+$/;
977
978 my $tag = PVE::SafeSyslog::tag();
979
980 $msg = "empty message" if !$msg;
981
982 $ident = "" if !$ident;
8f2d54ff 983 $ident = encode("ascii", $ident,
fe000966
DM
984 sub { sprintf "\\u%04x", shift });
985
8f2d54ff 986 my $ascii = encode("ascii", $msg, sub { sprintf "\\u%04x", shift });
fe000966
DM
987
988 if ($ident) {
989 syslog($priority, "<%s> %s", $ident, $ascii);
990 } else {
991 syslog($priority, "%s", $ascii);
992 }
993
994 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
995
996 syslog("err", "writing cluster log failed: $@") if $@;
997}
998
9d76a1bb
DM
999sub check_vmid_unused {
1000 my ($vmid, $noerr) = @_;
c53b111f 1001
9d76a1bb
DM
1002 my $vmlist = get_vmlist();
1003
1004 my $d = $vmlist->{ids}->{$vmid};
1005 return 1 if !defined($d);
c53b111f 1006
9d76a1bb
DM
1007 return undef if $noerr;
1008
4f66b109 1009 my $vmtypestr = $d->{type} eq 'qemu' ? 'VM' : 'CT';
e75ccbee 1010 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
9d76a1bb
DM
1011}
1012
65ff467f
DM
1013sub check_node_exists {
1014 my ($nodename, $noerr) = @_;
1015
1016 my $nodelist = $clinfo->{nodelist};
1017 return 1 if $nodelist && $nodelist->{$nodename};
1018
1019 return undef if $noerr;
1020
1021 die "no such cluster node '$nodename'\n";
1022}
1023
fe000966
DM
1024# this is also used to get the IP of the local node
1025sub remote_node_ip {
1026 my ($nodename, $noerr) = @_;
1027
1028 my $nodelist = $clinfo->{nodelist};
1029 if ($nodelist && $nodelist->{$nodename}) {
1030 if (my $ip = $nodelist->{$nodename}->{ip}) {
fc31f517
WB
1031 return $ip if !wantarray;
1032 my $family = $nodelist->{$nodename}->{address_family};
1033 if (!$family) {
1034 $nodelist->{$nodename}->{address_family} =
1035 $family =
1036 PVE::Tools::get_host_address_family($ip);
1037 }
14830160 1038 return wantarray ? ($ip, $family) : $ip;
fe000966
DM
1039 }
1040 }
1041
1042 # fallback: try to get IP by other means
e064c9b0 1043 return PVE::Network::get_ip_from_hostname($nodename, $noerr);
fe000966
DM
1044}
1045
54d487bf
TL
1046sub get_local_migration_ip {
1047 my ($migration_network, $noerr) = @_;
1048
1049 my $cidr = $migration_network;
1050
1051 if (!defined($cidr)) {
1052 my $dc_conf = cfs_read_file('datacenter.cfg');
1053 $cidr = $dc_conf->{migration}->{network}
1054 if defined($dc_conf->{migration}->{network});
1055 }
1056
1057 if (defined($cidr)) {
1058 my $ips = PVE::Network::get_local_ip_from_cidr($cidr);
1059
cb8c3bc6
TL
1060 die "could not get migration ip: no IP address configured on local " .
1061 "node for network '$cidr'\n" if !$noerr && (scalar(@$ips) == 0);
54d487bf 1062
cb8c3bc6
TL
1063 die "could not get migration ip: multiple IP address configured for " .
1064 "network '$cidr'\n" if !$noerr && (scalar(@$ips) > 1);
54d487bf
TL
1065
1066 return @$ips[0];
1067 }
1068
1069 return undef;
1070};
1071
fe000966
DM
1072# ssh related utility functions
1073
1074sub ssh_merge_keys {
1075 # remove duplicate keys in $sshauthkeys
1076 # ssh-copy-id simply add keys, so the file can grow to large
1077
1078 my $data = '';
1079 if (-f $sshauthkeys) {
1080 $data = PVE::Tools::file_get_contents($sshauthkeys, 128*1024);
1081 chomp($data);
1082 }
1083
6056578e
DM
1084 my $found_backup;
1085 if (-f $rootsshauthkeysbackup) {
404343d7 1086 $data .= "\n";
6056578e
DM
1087 $data .= PVE::Tools::file_get_contents($rootsshauthkeysbackup, 128*1024);
1088 chomp($data);
1089 $found_backup = 1;
1090 }
1091
fe000966
DM
1092 # always add ourself
1093 if (-f $ssh_rsa_id) {
1094 my $pub = PVE::Tools::file_get_contents($ssh_rsa_id);
1095 chomp($pub);
1096 $data .= "\n$pub\n";
1097 }
1098
1099 my $newdata = "";
1100 my $vhash = {};
2055b0a9
DM
1101 my @lines = split(/\n/, $data);
1102 foreach my $line (@lines) {
7eb37d8d
SP
1103 if ($line !~ /^#/ && $line =~ m/(^|\s)ssh-(rsa|dsa)\s+(\S+)\s+\S+$/) {
1104 next if $vhash->{$3}++;
fe000966 1105 }
2055b0a9 1106 $newdata .= "$line\n";
fe000966 1107 }
fe000966
DM
1108
1109 PVE::Tools::file_set_contents($sshauthkeys, $newdata, 0600);
6056578e
DM
1110
1111 if ($found_backup && -l $rootsshauthkeys) {
1112 # everything went well, so we can remove the backup
1113 unlink $rootsshauthkeysbackup;
1114 }
fe000966
DM
1115}
1116
ac50b36d 1117sub setup_sshd_config {
99fc0847 1118 my () = @_;
ac50b36d
DM
1119
1120 my $conf = PVE::Tools::file_get_contents($sshd_config_fn);
c53b111f 1121
ac50b36d
DM
1122 return if $conf =~ m/^PermitRootLogin\s+yes\s*$/m;
1123
1124 if ($conf !~ s/^#?PermitRootLogin.*$/PermitRootLogin yes/m) {
1125 chomp $conf;
1126 $conf .= "\nPermitRootLogin yes\n";
c53b111f 1127 }
ac50b36d
DM
1128
1129 PVE::Tools::file_set_contents($sshd_config_fn, $conf);
1130
99fc0847 1131 PVE::Tools::run_command(['systemctl', 'reload-or-restart', 'sshd']);
ac50b36d
DM
1132}
1133
f666cdde
SP
1134sub setup_rootsshconfig {
1135
39df71df
DM
1136 # create ssh key if it does not exist
1137 if (! -f $ssh_rsa_id) {
1138 mkdir '/root/.ssh/';
1139 system ("echo|ssh-keygen -t rsa -N '' -b 2048 -f ${ssh_rsa_id_priv}");
1140 }
1141
f666cdde
SP
1142 # create ssh config if it does not exist
1143 if (! -f $rootsshconfig) {
9aabc24b
DM
1144 mkdir '/root/.ssh';
1145 if (my $fh = IO::File->new($rootsshconfig, O_CREAT|O_WRONLY|O_EXCL, 0640)) {
61fa3c34
FG
1146 # this is the default ciphers list from Debian's OpenSSH package (OpenSSH_7.4p1 Debian-10, OpenSSL 1.0.2k 26 Jan 2017)
1147 # changed order to put AES before Chacha20 (most hardware has AESNI)
4833829a 1148 print $fh "Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm\@openssh.com,aes256-gcm\@openssh.com,chacha20-poly1305\@openssh.com\n";
f666cdde
SP
1149 close($fh);
1150 }
1151 }
1152}
1153
fe000966
DM
1154sub setup_ssh_keys {
1155
fe000966
DM
1156 mkdir $authdir;
1157
6056578e
DM
1158 my $import_ok;
1159
fe000966 1160 if (! -f $sshauthkeys) {
6056578e
DM
1161 my $old;
1162 if (-f $rootsshauthkeys) {
1163 $old = PVE::Tools::file_get_contents($rootsshauthkeys, 128*1024);
1164 }
fe000966 1165 if (my $fh = IO::File->new ($sshauthkeys, O_CREAT|O_WRONLY|O_EXCL, 0400)) {
6056578e 1166 PVE::Tools::safe_print($sshauthkeys, $fh, $old) if $old;
fe000966 1167 close($fh);
6056578e 1168 $import_ok = 1;
fe000966
DM
1169 }
1170 }
1171
c53b111f 1172 warn "can't create shared ssh key database '$sshauthkeys'\n"
fe000966
DM
1173 if ! -f $sshauthkeys;
1174
404343d7 1175 if (-f $rootsshauthkeys && ! -l $rootsshauthkeys) {
6056578e
DM
1176 if (!rename($rootsshauthkeys , $rootsshauthkeysbackup)) {
1177 warn "rename $rootsshauthkeys failed - $!\n";
1178 }
fe000966
DM
1179 }
1180
1181 if (! -l $rootsshauthkeys) {
1182 symlink $sshauthkeys, $rootsshauthkeys;
1183 }
fe000966 1184
6056578e
DM
1185 if (! -l $rootsshauthkeys) {
1186 warn "can't create symlink for ssh keys '$rootsshauthkeys' -> '$sshauthkeys'\n";
1187 } else {
1188 unlink $rootsshauthkeysbackup if $import_ok;
1189 }
fe000966
DM
1190}
1191
1192sub ssh_unmerge_known_hosts {
1193 return if ! -l $sshglobalknownhosts;
1194
1195 my $old = '';
1196 $old = PVE::Tools::file_get_contents($sshknownhosts, 128*1024)
1197 if -f $sshknownhosts;
1198
1199 PVE::Tools::file_set_contents($sshglobalknownhosts, $old);
1200}
1201
1202sub ssh_merge_known_hosts {
1203 my ($nodename, $ip_address, $createLink) = @_;
1204
1205 die "no node name specified" if !$nodename;
1206 die "no ip address specified" if !$ip_address;
c53b111f 1207
e4f92a20
TL
1208 # ssh lowercases hostnames (aliases) before comparision, so we need too
1209 $nodename = lc($nodename);
1210 $ip_address = lc($ip_address);
1211
fe000966
DM
1212 mkdir $authdir;
1213
1214 if (! -f $sshknownhosts) {
1215 if (my $fh = IO::File->new($sshknownhosts, O_CREAT|O_WRONLY|O_EXCL, 0600)) {
1216 close($fh);
1217 }
1218 }
1219
c53b111f
DM
1220 my $old = PVE::Tools::file_get_contents($sshknownhosts, 128*1024);
1221
fe000966 1222 my $new = '';
c53b111f 1223
fe000966
DM
1224 if ((! -l $sshglobalknownhosts) && (-f $sshglobalknownhosts)) {
1225 $new = PVE::Tools::file_get_contents($sshglobalknownhosts, 128*1024);
1226 }
1227
1228 my $hostkey = PVE::Tools::file_get_contents($ssh_host_rsa_id);
1d182ad3
DM
1229 # Note: file sometimes containe emty lines at start, so we use multiline match
1230 die "can't parse $ssh_host_rsa_id" if $hostkey !~ m/^(ssh-rsa\s\S+)(\s.*)?$/m;
fe000966
DM
1231 $hostkey = $1;
1232
1233 my $data = '';
1234 my $vhash = {};
1235
1236 my $found_nodename;
1237 my $found_local_ip;
1238
1239 my $merge_line = sub {
1240 my ($line, $all) = @_;
1241
53922f63
TL
1242 return if $line =~ m/^\s*$/; # skip empty lines
1243 return if $line =~ m/^#/; # skip comments
1244
fe000966
DM
1245 if ($line =~ m/^(\S+)\s(ssh-rsa\s\S+)(\s.*)?$/) {
1246 my $key = $1;
1247 my $rsakey = $2;
1248 if (!$vhash->{$key}) {
1249 $vhash->{$key} = 1;
1250 if ($key =~ m/\|1\|([^\|\s]+)\|([^\|\s]+)$/) {
1251 my $salt = decode_base64($1);
1252 my $digest = $2;
1253 my $hmac = Digest::HMAC_SHA1->new($salt);
1254 $hmac->add($nodename);
1255 my $hd = $hmac->b64digest . '=';
1256 if ($digest eq $hd) {
1257 if ($rsakey eq $hostkey) {
1258 $found_nodename = 1;
1259 $data .= $line;
1260 }
1261 return;
1262 }
1263 $hmac = Digest::HMAC_SHA1->new($salt);
1264 $hmac->add($ip_address);
1265 $hd = $hmac->b64digest . '=';
1266 if ($digest eq $hd) {
1267 if ($rsakey eq $hostkey) {
1268 $found_local_ip = 1;
1269 $data .= $line;
1270 }
1271 return;
1272 }
e4f92a20
TL
1273 } else {
1274 $key = lc($key); # avoid duplicate entries, ssh compares lowercased
1275 if ($key eq $ip_address) {
fe129500 1276 $found_local_ip = 1 if $rsakey eq $hostkey;
e4f92a20 1277 } elsif ($key eq $nodename) {
fe129500 1278 $found_nodename = 1 if $rsakey eq $hostkey;
e4f92a20 1279 }
fe000966
DM
1280 }
1281 $data .= $line;
1282 }
1283 } elsif ($all) {
1284 $data .= $line;
1285 }
1286 };
1287
1288 while ($old && $old =~ s/^((.*?)(\n|$))//) {
1289 my $line = "$2\n";
fe000966
DM
1290 &$merge_line($line, 1);
1291 }
1292
1293 while ($new && $new =~ s/^((.*?)(\n|$))//) {
1294 my $line = "$2\n";
fe000966
DM
1295 &$merge_line($line);
1296 }
1297
53922f63
TL
1298 # add our own key if not already there
1299 $data .= "$nodename $hostkey\n" if !$found_nodename;
1300 $data .= "$ip_address $hostkey\n" if !$found_local_ip;
fe000966
DM
1301
1302 PVE::Tools::file_set_contents($sshknownhosts, $data);
1303
1304 return if !$createLink;
1305
1306 unlink $sshglobalknownhosts;
1307 symlink $sshknownhosts, $sshglobalknownhosts;
c53b111f
DM
1308
1309 warn "can't create symlink for ssh known hosts '$sshglobalknownhosts' -> '$sshknownhosts'\n"
fe000966
DM
1310 if ! -l $sshglobalknownhosts;
1311
1312}
1313
bba12ad7
TL
1314my $migration_format = {
1315 type => {
1316 default_key => 1,
1317 type => 'string',
1318 enum => ['secure', 'insecure'],
1319 description => "Migration traffic is encrypted using an SSH tunnel by " .
1320 "default. On secure, completely private networks this can be " .
1321 "disabled to increase performance.",
1322 default => 'secure',
bba12ad7
TL
1323 },
1324 network => {
1325 optional => 1,
1326 type => 'string', format => 'CIDR',
1327 format_description => 'CIDR',
1328 description => "CIDR of the (sub) network that is used for migration."
1329 },
1330};
1331
fe000966
DM
1332my $datacenter_schema = {
1333 type => "object",
1334 additionalProperties => 0,
1335 properties => {
1336 keyboard => {
1337 optional => 1,
1338 type => 'string',
1339 description => "Default keybord layout for vnc server.",
c59334cb 1340 enum => PVE::Tools::kvmkeymaplist(),
fe000966
DM
1341 },
1342 language => {
1343 optional => 1,
1344 type => 'string',
1345 description => "Default GUI language.",
1346 enum => [ 'en', 'de' ],
1347 },
1348 http_proxy => {
1349 optional => 1,
1350 type => 'string',
1351 description => "Specify external http proxy which is used for downloads (example: 'http://username:password\@host:port/')",
1352 pattern => "http://.*",
1353 },
a9323ef0
SP
1354 migration_unsecure => {
1355 optional => 1,
1356 type => 'boolean',
bba12ad7
TL
1357 description => "Migration is secure using SSH tunnel by default. " .
1358 "For secure private networks you can disable it to speed up " .
1359 "migration. Deprecated, use the 'migration' property instead!",
1360 },
1361 migration => {
1362 optional => 1,
1363 type => 'string', format => $migration_format,
1364 description => "For cluster wide migration settings.",
a9323ef0 1365 },
dce47328
DM
1366 console => {
1367 optional => 1,
1368 type => 'string',
66a15f27
DM
1369 description => "Select the default Console viewer. You can either use the builtin java applet (VNC), an external virt-viewer comtatible application (SPICE), or an HTML5 based viewer (noVNC).",
1370 enum => ['applet', 'vv', 'html5'],
dce47328 1371 },
8548bd87
SGE
1372 email_from => {
1373 optional => 1,
1374 type => 'string',
a05baf53 1375 format => 'email-opt',
8548bd87
SGE
1376 description => "Specify email address to send notification from (default is root@\$hostname)",
1377 },
66c2b1e9
TL
1378 max_workers => {
1379 optional => 1,
1380 type => 'integer',
1381 minimum => 1,
1382 description => "Defines how many workers (per node) are maximal started ".
1383 " on actions like 'stopall VMs' or task from the ha-manager.",
1384 },
8d762bd6
TL
1385 fencing => {
1386 optional => 1,
1387 type => 'string',
1388 default => 'watchdog',
1389 enum => [ 'watchdog', 'hardware', 'both' ],
1390 description => "Set the fencing mode of the HA cluster. Hardware mode " .
1391 "needs a valid configuration of fence devices in /etc/pve/ha/fence.cfg." .
bd0c003a
FG
1392 " With both all two modes are used." .
1393 "\n\nWARNING: 'hardware' and 'both' are EXPERIMENTAL & WIP",
8d762bd6 1394 },
329da63d
WB
1395 mac_prefix => {
1396 optional => 1,
1397 type => 'string',
1398 pattern => qr/[a-f0-9]{2}(?::[a-f0-9]{2}){0,2}:?/i,
1399 description => 'Prefix for autogenerated MAC addresses.',
1400 },
fe000966
DM
1401 },
1402};
1403
1404# make schema accessible from outside (for documentation)
1405sub get_datacenter_schema { return $datacenter_schema };
1406
1407sub parse_datacenter_config {
1408 my ($filename, $raw) = @_;
1409
bba12ad7
TL
1410 my $res = PVE::JSONSchema::parse_config($datacenter_schema, $filename, $raw // '');
1411
1412 if (my $migration = $res->{migration}) {
1413 $res->{migration} = PVE::JSONSchema::parse_property_string($migration_format, $migration);
1414 }
1415
1416 # for backwards compatibility only, new migration property has precedence
1417 if (defined($res->{migration_unsecure})) {
1418 if (defined($res->{migration}->{type})) {
1419 warn "deprecated setting 'migration_unsecure' and new 'migration: type' " .
1420 "set at same time! Ignore 'migration_unsecure'\n";
1421 } else {
1422 $res->{migration}->{type} = ($res->{migration_unsecure}) ? 'insecure' : 'secure';
1423 }
1424 }
1425
1426 return $res;
fe000966
DM
1427}
1428
1429sub write_datacenter_config {
1430 my ($filename, $cfg) = @_;
bba12ad7
TL
1431
1432 # map deprecated setting to new one
8f706517 1433 if (defined($cfg->{migration_unsecure}) && !defined($cfg->{migration})) {
bba12ad7
TL
1434 my $migration_unsecure = delete $cfg->{migration_unsecure};
1435 $cfg->{migration}->{type} = ($migration_unsecure) ? 'insecure' : 'secure';
1436 }
1437
fe000966
DM
1438 return PVE::JSONSchema::dump_config($datacenter_schema, $filename, $cfg);
1439}
1440
c53b111f
DM
1441cfs_register_file('datacenter.cfg',
1442 \&parse_datacenter_config,
fe000966 1443 \&write_datacenter_config);
ec48ec22 1444
26784563
DM
1445# X509 Certificate cache helper
1446
1447my $cert_cache_nodes = {};
1448my $cert_cache_timestamp = time();
1449my $cert_cache_fingerprints = {};
1450
1451sub update_cert_cache {
1452 my ($update_node, $clear) = @_;
1453
1454 syslog('info', "Clearing outdated entries from certificate cache")
1455 if $clear;
1456
1457 $cert_cache_timestamp = time() if !defined($update_node);
1458
1459 my $node_list = defined($update_node) ?
1460 [ $update_node ] : [ keys %$cert_cache_nodes ];
1461
1462 foreach my $node (@$node_list) {
1463 my $clear_old = sub {
1464 if (my $old_fp = $cert_cache_nodes->{$node}) {
1465 # distrust old fingerprint
1466 delete $cert_cache_fingerprints->{$old_fp};
1467 # ensure reload on next proxied request
1468 delete $cert_cache_nodes->{$node};
1469 }
1470 };
1471
1904862a
TL
1472 my $fp = eval { get_node_fingerprint($node) };
1473 if (my $err = $@) {
1474 warn "$err\n";
26784563
DM
1475 &$clear_old() if $clear;
1476 next;
1477 }
1478
1479 my $old_fp = $cert_cache_nodes->{$node};
1480 $cert_cache_fingerprints->{$fp} = 1;
1481 $cert_cache_nodes->{$node} = $fp;
1482
1483 if (defined($old_fp) && $fp ne $old_fp) {
1484 delete $cert_cache_fingerprints->{$old_fp};
1485 }
1486 }
1487}
1488
ab224148
DM
1489# load and cache cert fingerprint once
1490sub initialize_cert_cache {
1491 my ($node) = @_;
1492
1493 update_cert_cache($node)
1494 if defined($node) && !defined($cert_cache_nodes->{$node});
1495}
1496
1904862a
TL
1497sub read_ssl_cert_fingerprint {
1498 my ($cert_path) = @_;
1499
2a5f4bed
FG
1500 my $bio = Net::SSLeay::BIO_new_file($cert_path, 'r')
1501 or die "unable to read '$cert_path' - $!\n";
1502
1503 my $cert = Net::SSLeay::PEM_read_bio_X509($bio);
1504 if (!$cert) {
1904862a 1505 Net::SSLeay::BIO_free($bio);
2a5f4bed
FG
1506 die "unable to read certificate from '$cert_path'\n";
1507 }
1508
1509 my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
1510 Net::SSLeay::X509_free($cert);
1904862a 1511
1904862a
TL
1512 die "unable to get fingerprint for '$cert_path' - got empty value\n"
1513 if !defined($fp) || $fp eq '';
1514
1515 return $fp;
1516}
1517
1518sub get_node_fingerprint {
1519 my ($node) = @_;
1520
1521 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
1522 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
1523
1524 $cert_path = $custom_cert_path if -f $custom_cert_path;
1525
1526 return read_ssl_cert_fingerprint($cert_path);
1527}
1528
1529
26784563
DM
1530sub check_cert_fingerprint {
1531 my ($cert) = @_;
1532
1533 # clear cache every 30 minutes at least
1534 update_cert_cache(undef, 1) if time() - $cert_cache_timestamp >= 60*30;
1535
1536 # get fingerprint of server certificate
2a5f4bed
FG
1537 my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
1538 return 0 if !defined($fp) || $fp eq ''; # error
26784563
DM
1539
1540 my $check = sub {
1541 for my $expected (keys %$cert_cache_fingerprints) {
1542 return 1 if $fp eq $expected;
1543 }
1544 return 0;
1545 };
1546
1547 return 1 if &$check();
1548
1549 # clear cache and retry at most once every minute
1550 if (time() - $cert_cache_timestamp >= 60) {
1551 syslog ('info', "Could not verify remote node certificate '$fp' with list of pinned certificates, refreshing cache");
1552 update_cert_cache();
1553 return &$check();
1554 }
1555
1556 return 0;
1557}
1558
15df58e6
DM
1559# bash completion helpers
1560
1561sub complete_next_vmid {
1562
1563 my $vmlist = get_vmlist() || {};
1564 my $idlist = $vmlist->{ids} || {};
1565
1566 for (my $i = 100; $i < 10000; $i++) {
1567 return [$i] if !defined($idlist->{$i});
1568 }
1569
1570 return [];
1571}
1572
87515b25
DM
1573sub complete_vmid {
1574
1575 my $vmlist = get_vmlist();
1576 my $ids = $vmlist->{ids} || {};
1577
1578 return [ keys %$ids ];
1579}
1580
15df58e6
DM
1581sub complete_local_vmid {
1582
1583 my $vmlist = get_vmlist();
1584 my $ids = $vmlist->{ids} || {};
1585
1586 my $nodename = PVE::INotify::nodename();
1587
1588 my $res = [];
1589 foreach my $vmid (keys %$ids) {
1590 my $d = $ids->{$vmid};
1591 next if !$d->{node} || $d->{node} ne $nodename;
1592 push @$res, $vmid;
1593 }
1594
1595 return $res;
1596}
1597
4dd189df
DM
1598sub complete_migration_target {
1599
1600 my $res = [];
1601
1602 my $nodename = PVE::INotify::nodename();
1603
1604 my $nodelist = get_nodelist();
1605 foreach my $node (@$nodelist) {
1606 next if $node eq $nodename;
1607 push @$res, $node;
1608 }
1609
1610 return $res;
1611}
1612
aabeedfb
WB
1613sub get_ssh_info {
1614 my ($node, $network_cidr) = @_;
1615
1616 my $ip;
1617 if (defined($network_cidr)) {
1618 # Use mtunnel via to get the remote node's ip inside $network_cidr.
1619 # This goes over the regular network (iow. uses get_ssh_info() with
1620 # $network_cidr undefined.
1621 # FIXME: Use the REST API client for this after creating an API entry
1622 # for get_migration_ip.
1623 my $default_remote = get_ssh_info($node, undef);
1624 my $default_ssh = ssh_info_to_command($default_remote);
1625 my $cmd =[@$default_ssh, 'pvecm', 'mtunnel',
1626 '-migration_network', $network_cidr,
1627 '-get_migration_ip'
1628 ];
1629 PVE::Tools::run_command($cmd, outfunc => sub {
1630 my ($line) = @_;
1631 chomp $line;
1632 die "internal error: unexpected output from mtunnel\n"
1633 if defined($ip);
1634 if ($line =~ /^ip: '(.*)'$/) {
1635 $ip = $1;
1636 } else {
1637 die "internal error: bad output from mtunnel\n"
1638 if defined($ip);
1639 }
1640 });
1641 die "failed to get ip for node '$node' in network '$network_cidr'\n"
1642 if !defined($ip);
1643 } else {
1644 $ip = remote_node_ip($node);
1645 }
1646
1647 return {
1648 ip => $ip,
d7d4c5b8
WB
1649 name => $node,
1650 network => $network_cidr,
aabeedfb
WB
1651 };
1652}
1653
1f1aef8b 1654sub ssh_info_to_command_base {
aabeedfb
WB
1655 my ($info, @extra_options) = @_;
1656 return [
1657 '/usr/bin/ssh',
8529e536 1658 '-e', 'none',
aabeedfb
WB
1659 '-o', 'BatchMode=yes',
1660 '-o', 'HostKeyAlias='.$info->{name},
1f1aef8b 1661 @extra_options
aabeedfb
WB
1662 ];
1663}
1664
1f1aef8b
WB
1665sub ssh_info_to_command {
1666 my ($info, @extra_options) = @_;
1667 my $cmd = ssh_info_to_command_base($info, @extra_options);
1668 push @$cmd, "root\@$info->{ip}";
1669 return $cmd;
1670}
1671
ac68281b 16721;