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