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