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