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