8 use Storable
qw(dclone);
13 use Digest
::HMAC_SHA1
;
31 use Data
::Dumper
; # fixme: remove
33 # x509 certificate utils
35 my $basedir = "/etc/pve";
36 my $authdir = "$basedir/priv";
37 my $lockdir = "/etc/pve/priv/lock";
39 my $authprivkeyfn = "$authdir/authkey.key";
40 my $authpubkeyfn = "$basedir/authkey.pub";
41 my $pveca_key_fn = "$authdir/pve-root-ca.key";
42 my $pveca_srl_fn = "$authdir/pve-root-ca.srl";
43 my $pveca_cert_fn = "$basedir/pve-root-ca.pem";
44 # this is just a secret accessable by the web browser
45 # and is used for CSRF prevention
46 my $pvewww_key_fn = "$basedir/pve-www.key";
49 my $ssh_rsa_id_priv = "/root/.ssh/id_rsa";
50 my $ssh_rsa_id = "/root/.ssh/id_rsa.pub";
51 my $ssh_host_rsa_id = "/etc/ssh/ssh_host_rsa_key.pub";
52 my $sshglobalknownhosts = "/etc/ssh/ssh_known_hosts";
53 my $sshknownhosts = "/etc/pve/priv/known_hosts";
54 my $sshauthkeys = "/etc/pve/priv/authorized_keys";
55 my $sshd_config_fn = "/etc/ssh/sshd_config";
56 my $rootsshauthkeys = "/root/.ssh/authorized_keys";
57 my $rootsshauthkeysbackup = "${rootsshauthkeys}.org";
58 my $rootsshconfig = "/root/.ssh/config";
63 'datacenter.cfg' => 1,
65 'corosync.conf.new' => 1,
68 'priv/shadow.cfg' => 1,
72 'ha/crm_commands' => 1,
73 'ha/manager_status' => 1,
74 'ha/resources.cfg' => 1,
80 # only write output if something fails
86 my $record_output = sub {
92 PVE
::Tools
::run_command
($cmd, outfunc
=> $record_output,
93 errfunc
=> $record_output);
104 sub check_cfs_quorum
{
107 # note: -w filename always return 1 for root, so wee need
108 # to use File::lstat here
109 my $st = File
::stat::lstat("$basedir/local");
110 my $quorate = ($st && (($st->mode & 0200) != 0));
112 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
117 sub check_cfs_is_mounted
{
120 my $res = -l
"$basedir/local";
122 die "pve configuration filesystem not mounted\n"
131 check_cfs_is_mounted
();
133 my @required_dirs = (
136 "$basedir/nodes/$nodename",
137 "$basedir/nodes/$nodename/lxc",
138 "$basedir/nodes/$nodename/qemu-server",
139 "$basedir/nodes/$nodename/openvz",
140 "$basedir/nodes/$nodename/priv");
142 foreach my $dir (@required_dirs) {
144 mkdir($dir) || $! == EEXIST
|| die "unable to create directory '$dir' - $!\n";
151 return if -f
"$authprivkeyfn";
153 check_cfs_is_mounted
();
155 mkdir $authdir || $! == EEXIST
|| die "unable to create dir '$authdir' - $!\n";
157 run_silent_cmd
(['openssl', 'genrsa -out', $authprivkeyfn, '2048']);
159 run_silent_cmd
(['openssl', 'rsa', '-in', $authprivkeyfn, '-pubout', '-out', $authpubkeyfn]);
164 return if -f
$pveca_key_fn;
167 run_silent_cmd
(['openssl', 'genrsa', '-out', $pveca_key_fn, '4096']);
170 die "unable to generate pve ca key:\n$@" if $@;
175 if (-f
$pveca_key_fn && -f
$pveca_cert_fn) {
181 # we try to generate an unique 'subject' to avoid browser problems
182 # (reused serial numbers, ..)
184 UUID
::generate
($uuid);
186 UUID
::unparse
($uuid, $uuid_str);
189 # wrap openssl with faketime to prevent bug #904
190 run_silent_cmd
(['faketime', 'yesterday', 'openssl', 'req', '-batch',
191 '-days', '3650', '-new', '-x509', '-nodes', '-key',
192 $pveca_key_fn, '-out', $pveca_cert_fn, '-subj',
193 "/CN=Proxmox Virtual Environment/OU=$uuid_str/O=PVE Cluster Manager CA/"]);
196 die "generating pve root certificate failed:\n$@" if $@;
201 sub gen_pve_ssl_key
{
204 die "no node name specified" if !$nodename;
206 my $pvessl_key_fn = "$basedir/nodes/$nodename/pve-ssl.key";
208 return if -f
$pvessl_key_fn;
211 run_silent_cmd
(['openssl', 'genrsa', '-out', $pvessl_key_fn, '2048']);
214 die "unable to generate pve ssl key for node '$nodename':\n$@" if $@;
217 sub gen_pve_www_key
{
219 return if -f
$pvewww_key_fn;
222 run_silent_cmd
(['openssl', 'genrsa', '-out', $pvewww_key_fn, '2048']);
225 die "unable to generate pve www key:\n$@" if $@;
231 PVE
::Tools
::file_set_contents
($pveca_srl_fn, $serial);
234 sub gen_pve_ssl_cert
{
235 my ($force, $nodename, $ip) = @_;
237 die "no node name specified" if !$nodename;
238 die "no IP specified" if !$ip;
240 my $pvessl_cert_fn = "$basedir/nodes/$nodename/pve-ssl.pem";
242 return if !$force && -f
$pvessl_cert_fn;
244 my $names = "IP:127.0.0.1,IP:::1,DNS:localhost";
246 my $rc = PVE
::INotify
::read_file
('resolvconf');
250 my $fqdn = $nodename;
252 $names .= ",DNS:$nodename";
254 if ($rc && $rc->{search
}) {
255 $fqdn = $nodename . "." . $rc->{search
};
256 $names .= ",DNS:$fqdn";
259 my $sslconf = <<__EOD;
260 RANDFILE = /root/.rnd
265 distinguished_name = req_distinguished_name
266 req_extensions = v3_req
268 string_mask = nombstr
270 [ req_distinguished_name ]
271 organizationalUnitName = PVE Cluster Node
272 organizationName = Proxmox Virtual Environment
276 basicConstraints = CA:FALSE
277 extendedKeyUsage = serverAuth
278 subjectAltName = $names
281 my $cfgfn = "/tmp/pvesslconf-$$.tmp";
282 my $fh = IO
::File-
>new ($cfgfn, "w");
286 my $reqfn = "/tmp/pvecertreq-$$.tmp";
289 my $pvessl_key_fn = "$basedir/nodes/$nodename/pve-ssl.key";
291 run_silent_cmd
(['openssl', 'req', '-batch', '-new', '-config', $cfgfn,
292 '-key', $pvessl_key_fn, '-out', $reqfn]);
298 die "unable to generate pve certificate request:\n$err";
301 update_serial
("0000000000000000") if ! -f
$pveca_srl_fn;
304 # wrap openssl with faketime to prevent bug #904
305 run_silent_cmd
(['faketime', 'yesterday', 'openssl', 'x509', '-req',
306 '-in', $reqfn, '-days', '3650', '-out', $pvessl_cert_fn,
307 '-CAkey', $pveca_key_fn, '-CA', $pveca_cert_fn,
308 '-CAserial', $pveca_srl_fn, '-extfile', $cfgfn]);
314 die "unable to generate pve ssl certificate:\n$err";
321 sub gen_pve_node_files
{
322 my ($nodename, $ip, $opt_force) = @_;
324 gen_local_dirs
($nodename);
328 # make sure we have a (cluster wide) secret
329 # for CSRFR prevention
332 # make sure we have a (per node) private key
333 gen_pve_ssl_key
($nodename);
335 # make sure we have a CA
336 my $force = gen_pveca_cert
();
338 $force = 1 if $opt_force;
340 gen_pve_ssl_cert
($force, $nodename, $ip);
343 my $vzdump_cron_dummy = <<__EOD;
344 # cluster wide vzdump cron schedule
345 # Atomatically generated file - do not edit
347 PATH="/usr/sbin:/usr/bin:/sbin:/bin"
351 sub gen_pve_vzdump_symlink
{
353 my $filename = "/etc/pve/vzdump.cron";
355 my $link_fn = "/etc/cron.d/vzdump";
357 if ((-f
$filename) && (! -l
$link_fn)) {
358 rename($link_fn, "/root/etc_cron_vzdump.org"); # make backup if file exists
359 symlink($filename, $link_fn);
363 sub gen_pve_vzdump_files
{
365 my $filename = "/etc/pve/vzdump.cron";
367 PVE
::Tools
::file_set_contents
($filename, $vzdump_cron_dummy)
370 gen_pve_vzdump_symlink
();
377 my $ipcc_send_rec = sub {
378 my ($msgid, $data) = @_;
380 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
382 die "ipcc_send_rec failed: $!\n" if !defined($res) && ($! != 0);
387 my $ipcc_send_rec_json = sub {
388 my ($msgid, $data) = @_;
390 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
392 die "ipcc_send_rec failed: $!\n" if !defined($res) && ($! != 0);
394 return decode_json
($res);
397 my $ipcc_get_config = sub {
400 my $bindata = pack "Z*", $path;
401 my $res = PVE
::IPCC
::ipcc_send_rec
(6, $bindata);
402 if (!defined($res)) {
403 return undef if ($! != 0);
410 my $ipcc_get_status = sub {
411 my ($name, $nodename) = @_;
413 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
414 return PVE
::IPCC
::ipcc_send_rec
(5, $bindata);
417 my $ipcc_update_status = sub {
418 my ($name, $data) = @_;
420 my $raw = ref($data) ? encode_json
($data) : $data;
422 my $bindata = pack "Z[256]Z*", $name, $raw;
424 return &$ipcc_send_rec(4, $bindata);
428 my ($priority, $ident, $tag, $msg) = @_;
430 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
431 bytes
::length($tag) + 1, $ident, $tag, $msg;
433 return &$ipcc_send_rec(7, $bindata);
436 my $ipcc_get_cluster_log = sub {
437 my ($user, $max) = @_;
439 $max = 0 if !defined($max);
441 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
442 return &$ipcc_send_rec(8, $bindata);
449 my $res = &$ipcc_send_rec_json(1);
450 #warn "GOT1: " . Dumper($res);
451 die "no starttime\n" if !$res->{starttime
};
453 if (!$res->{starttime
} || !$versions->{starttime
} ||
454 $res->{starttime
} != $versions->{starttime
}) {
455 #print "detected changed starttime\n";
473 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
474 #warn "detected new clinfo\n";
475 $clinfo = &$ipcc_send_rec_json(2);
485 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
486 #warn "detected new vmlist1\n";
487 $vmlist = &$ipcc_send_rec_json(3);
506 return $clinfo->{nodelist
};
511 my $nodelist = $clinfo->{nodelist
};
515 my $nodename = PVE
::INotify
::nodename
();
517 if (!$nodelist || !$nodelist->{$nodename}) {
518 return [ $nodename ];
521 return [ keys %$nodelist ];
524 sub broadcast_tasklist
{
528 &$ipcc_update_status("tasklist", $data);
534 my $tasklistcache = {};
539 my $kvstore = $versions->{kvstore
} || {};
541 my $nodelist = get_nodelist
();
544 foreach my $node (@$nodelist) {
545 next if $nodename && ($nodename ne $node);
547 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
548 my $cd = $tasklistcache->{$node};
549 if (!$cd || !$ver || !$cd->{version
} ||
550 ($cd->{version
} != $ver)) {
551 my $raw = &$ipcc_get_status("tasklist", $node) || '[]';
552 my $data = decode_json
($raw);
554 $cd = $tasklistcache->{$node} = {
558 } elsif ($cd && $cd->{data
}) {
559 push @$res, @{$cd->{data
}};
563 syslog
('err', $err) if $err;
570 my ($rrdid, $data) = @_;
573 &$ipcc_update_status("rrd/$rrdid", $data);
580 my $last_rrd_dump = 0;
581 my $last_rrd_data = "";
587 my $diff = $ctime - $last_rrd_dump;
589 return $last_rrd_data;
594 $raw = &$ipcc_send_rec(10);
606 while ($raw =~ s/^(.*)\n//) {
607 my ($key, @ela) = split(/:/, $1);
609 next if !(scalar(@ela) > 1);
610 $res->{$key} = \
@ela;
614 $last_rrd_dump = $ctime;
615 $last_rrd_data = $res;
620 sub create_rrd_data
{
621 my ($rrdname, $timeframe, $cf) = @_;
623 my $rrddir = "/var/lib/rrdcached/db";
625 my $rrd = "$rrddir/$rrdname";
629 day
=> [ 60*30, 70 ],
630 week
=> [ 60*180, 70 ],
631 month
=> [ 60*720, 70 ],
632 year
=> [ 60*10080, 70 ],
635 my ($reso, $count) = @{$setup->{$timeframe}};
636 my $ctime = $reso*int(time()/$reso);
637 my $req_start = $ctime - $reso*$count;
639 $cf = "AVERAGE" if !$cf;
647 my $socket = "/var/run/rrdcached.sock";
648 push @args, "--daemon" => "unix:$socket" if -S
$socket;
650 my ($start, $step, $names, $data) = RRDs
::fetch
($rrd, $cf, @args);
652 my $err = RRDs
::error
;
653 die "RRD error: $err\n" if $err;
655 die "got wrong time resolution ($step != $reso)\n"
659 my $fields = scalar(@$names);
660 for my $line (@$data) {
661 my $entry = { 'time' => $start };
663 for (my $i = 0; $i < $fields; $i++) {
664 my $name = $names->[$i];
665 if (defined(my $val = $line->[$i])) {
666 $entry->{$name} = $val;
668 # leave empty fields undefined
669 # maybe make this configurable?
678 sub create_rrd_graph
{
679 my ($rrdname, $timeframe, $ds, $cf) = @_;
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).
685 my $rrddir = "/var/lib/rrdcached/db";
687 my $rrd = "$rrddir/$rrdname";
689 my @ids = PVE
::Tools
::split_list
($ds);
691 my $ds_txt = join('_', @ids);
693 my $filename = "${rrd}_${ds_txt}.png";
697 day
=> [ 60*30, 70 ],
698 week
=> [ 60*180, 70 ],
699 month
=> [ 60*720, 70 ],
700 year
=> [ 60*10080, 70 ],
703 my ($reso, $count) = @{$setup->{$timeframe}};
706 "--imgformat" => "PNG",
710 "--start" => - $reso*$count,
712 "--lower-limit" => 0,
715 my $socket = "/var/run/rrdcached.sock";
716 push @args, "--daemon" => "unix:$socket" if -S
$socket;
718 my @coldef = ('#00ddff', '#ff0000');
720 $cf = "AVERAGE" if !$cf;
723 foreach my $id (@ids) {
724 my $col = $coldef[$i++] || die "fixme: no color definition";
725 push @args, "DEF:${id}=$rrd:${id}:$cf";
727 if ($id eq 'cpu' || $id eq 'iowait') {
728 push @args, "CDEF:${id}_per=${id},100,*";
729 $dataid = "${id}_per";
731 push @args, "LINE2:${dataid}${col}:${id}";
734 push @args, '--full-size-mode';
736 # we do not really store data into the file
737 my $res = RRDs
::graphv
('', @args);
739 my $err = RRDs
::error
;
740 die "RRD error: $err\n" if $err;
742 return { filename
=> $filename, image
=> $res->{image
} };
745 # a fast way to read files (avoid fuse overhead)
749 return &$ipcc_get_config($path);
752 sub get_cluster_log
{
753 my ($user, $max) = @_;
755 return &$ipcc_get_cluster_log($user, $max);
760 sub cfs_register_file
{
761 my ($filename, $parser, $writer) = @_;
763 $observed->{$filename} || die "unknown file '$filename'";
765 die "file '$filename' already registered" if $file_info->{$filename};
767 $file_info->{$filename} = {
773 my $ccache_read = sub {
774 my ($filename, $parser, $version) = @_;
776 $ccache->{$filename} = {} if !$ccache->{$filename};
778 my $ci = $ccache->{$filename};
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)
783 my $data = get_config
($filename);
784 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
785 $ci->{version
} = $version;
788 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
793 sub cfs_file_version
{
798 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
799 my ($type, $vmid) = ($1, $2);
800 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
801 $version = $vmlist->{ids
}->{$vmid}->{version
};
803 $infotag = "/$type/";
805 $infotag = $filename;
806 $version = $versions->{$filename};
809 my $info = $file_info->{$infotag} ||
810 die "unknown file type '$filename'\n";
812 return wantarray ?
($version, $info) : $version;
818 my ($version, $info) = cfs_file_version
($filename);
819 my $parser = $info->{parser
};
821 return &$ccache_read($filename, $parser, $version);
825 my ($filename, $data) = @_;
827 my ($version, $info) = cfs_file_version
($filename);
829 my $writer = $info->{writer
} || die "no writer defined";
831 my $fsname = "/etc/pve/$filename";
833 my $raw = &$writer($fsname, $data);
835 if (my $ci = $ccache->{$filename}) {
836 $ci->{version
} = undef;
839 PVE
::Tools
::file_set_contents
($fsname, $raw);
843 my ($lockid, $timeout, $code, @param) = @_;
847 # this timeout is for aquire the lock
848 $timeout = 10 if !$timeout;
850 my $filename = "$lockdir/$lockid";
852 my $msg = "can't aquire cfs lock '$lockid'";
859 die "$msg: pve cluster filesystem not online.\n";
862 local $SIG{ALRM
} = sub { die "got lock request timeout\n"; };
866 if (!(mkdir $filename)) {
867 print STDERR
"trying to aquire cfs lock '$lockid' ...";
869 if (!(mkdir $filename)) {
870 (utime 0, 0, $filename); # cfs unlock request
872 print STDERR
" OK\n";
879 # fixed command timeout: cfs locks have a timeout of 120
880 # using 60 gives us another 60 seconds to abort the task
882 local $SIG{ALRM
} = sub { die "got lock timeout - aborting command\n"; };
884 cfs_update
(); # make sure we read latest versions inside code()
886 $res = &$code(@param);
895 if ($err && ($err eq "got lock request timeout\n") &&
896 !check_cfs_quorum
()){
897 $err = "$msg: no quorum!\n";
900 if (!$err || $err !~ /^got lock timeout -/) {
901 rmdir $filename; # cfs unlock
915 my ($filename, $timeout, $code, @param) = @_;
917 my $info = $observed->{$filename} || die "unknown file '$filename'";
919 my $lockid = "file-$filename";
920 $lockid =~ s/[.\/]/_
/g
;
922 &$cfs_lock($lockid, $timeout, $code, @param);
925 sub cfs_lock_storage
{
926 my ($storeid, $timeout, $code, @param) = @_;
928 my $lockid = "storage-$storeid";
930 &$cfs_lock($lockid, $timeout, $code, @param);
933 sub cfs_lock_domain
{
934 my ($domainname, $timeout, $code, @param) = @_;
936 my $lockid = "domain-$domainname";
938 &$cfs_lock($lockid, $timeout, $code, @param);
956 my ($priority, $ident, $msg) = @_;
958 if (my $tmp = $log_levels->{$priority}) {
962 die "need numeric log priority" if $priority !~ /^\d+$/;
964 my $tag = PVE
::SafeSyslog
::tag
();
966 $msg = "empty message" if !$msg;
968 $ident = "" if !$ident;
969 $ident = encode
("ascii", $ident,
970 sub { sprintf "\\u%04x", shift });
972 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
975 syslog
($priority, "<%s> %s", $ident, $ascii);
977 syslog
($priority, "%s", $ascii);
980 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
982 syslog
("err", "writing cluster log failed: $@") if $@;
985 sub check_vmid_unused
{
986 my ($vmid, $noerr) = @_;
988 my $vmlist = get_vmlist
();
990 my $d = $vmlist->{ids
}->{$vmid};
991 return 1 if !defined($d);
993 return undef if $noerr;
995 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
996 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
999 sub check_node_exists
{
1000 my ($nodename, $noerr) = @_;
1002 my $nodelist = $clinfo->{nodelist
};
1003 return 1 if $nodelist && $nodelist->{$nodename};
1005 return undef if $noerr;
1007 die "no such cluster node '$nodename'\n";
1010 # this is also used to get the IP of the local node
1011 sub remote_node_ip
{
1012 my ($nodename, $noerr) = @_;
1014 my $nodelist = $clinfo->{nodelist
};
1015 if ($nodelist && $nodelist->{$nodename}) {
1016 if (my $ip = $nodelist->{$nodename}->{ip
}) {
1017 return $ip if !wantarray;
1018 my $family = $nodelist->{$nodename}->{address_family
};
1020 $nodelist->{$nodename}->{address_family
} =
1022 PVE
::Tools
::get_host_address_family
($ip);
1024 return ($ip, $family);
1028 # fallback: try to get IP by other means
1029 my ($family, $packed_ip);
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];
1038 die "hostname lookup failed:\n$@" if !$noerr;
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;
1048 return wantarray ?
($ip, $family) : $ip;
1051 # ssh related utility functions
1053 sub ssh_merge_keys
{
1054 # remove duplicate keys in $sshauthkeys
1055 # ssh-copy-id simply add keys, so the file can grow to large
1058 if (-f
$sshauthkeys) {
1059 $data = PVE
::Tools
::file_get_contents
($sshauthkeys, 128*1024);
1064 if (-f
$rootsshauthkeysbackup) {
1066 $data .= PVE
::Tools
::file_get_contents
($rootsshauthkeysbackup, 128*1024);
1071 # always add ourself
1072 if (-f
$ssh_rsa_id) {
1073 my $pub = PVE
::Tools
::file_get_contents
($ssh_rsa_id);
1075 $data .= "\n$pub\n";
1080 my @lines = split(/\n/, $data);
1081 foreach my $line (@lines) {
1082 if ($line !~ /^#/ && $line =~ m/(^|\s)ssh-(rsa|dsa)\s+(\S+)\s+\S+$/) {
1083 next if $vhash->{$3}++;
1085 $newdata .= "$line\n";
1088 PVE
::Tools
::file_set_contents
($sshauthkeys, $newdata, 0600);
1090 if ($found_backup && -l
$rootsshauthkeys) {
1091 # everything went well, so we can remove the backup
1092 unlink $rootsshauthkeysbackup;
1096 sub setup_sshd_config
{
1098 my $conf = PVE
::Tools
::file_get_contents
($sshd_config_fn);
1100 return if $conf =~ m/^PermitRootLogin\s+yes\s*$/m;
1102 if ($conf !~ s/^#?PermitRootLogin.*$/PermitRootLogin yes/m) {
1104 $conf .= "\nPermitRootLogin yes\n";
1107 PVE
::Tools
::file_set_contents
($sshd_config_fn, $conf);
1109 PVE
::Tools
::run_command
(['systemctl', 'reload-or-restart', 'sshd']);
1112 sub setup_rootsshconfig
{
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}");
1120 # create ssh config if it does not exist
1121 if (! -f
$rootsshconfig) {
1123 if (my $fh = IO
::File-
>new($rootsshconfig, O_CREAT
|O_WRONLY
|O_EXCL
, 0640)) {
1124 # this is the default ciphers list from debian openssl0.9.8 except blowfish is added as prefered
1125 print $fh "Ciphers blowfish-cbc,aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc\n";
1131 sub setup_ssh_keys
{
1137 if (! -f
$sshauthkeys) {
1139 if (-f
$rootsshauthkeys) {
1140 $old = PVE
::Tools
::file_get_contents
($rootsshauthkeys, 128*1024);
1142 if (my $fh = IO
::File-
>new ($sshauthkeys, O_CREAT
|O_WRONLY
|O_EXCL
, 0400)) {
1143 PVE
::Tools
::safe_print
($sshauthkeys, $fh, $old) if $old;
1149 warn "can't create shared ssh key database '$sshauthkeys'\n"
1150 if ! -f
$sshauthkeys;
1152 if (-f
$rootsshauthkeys && ! -l
$rootsshauthkeys) {
1153 if (!rename($rootsshauthkeys , $rootsshauthkeysbackup)) {
1154 warn "rename $rootsshauthkeys failed - $!\n";
1158 if (! -l
$rootsshauthkeys) {
1159 symlink $sshauthkeys, $rootsshauthkeys;
1162 if (! -l
$rootsshauthkeys) {
1163 warn "can't create symlink for ssh keys '$rootsshauthkeys' -> '$sshauthkeys'\n";
1165 unlink $rootsshauthkeysbackup if $import_ok;
1169 sub ssh_unmerge_known_hosts
{
1170 return if ! -l
$sshglobalknownhosts;
1173 $old = PVE
::Tools
::file_get_contents
($sshknownhosts, 128*1024)
1174 if -f
$sshknownhosts;
1176 PVE
::Tools
::file_set_contents
($sshglobalknownhosts, $old);
1179 sub ssh_merge_known_hosts
{
1180 my ($nodename, $ip_address, $createLink) = @_;
1182 die "no node name specified" if !$nodename;
1183 die "no ip address specified" if !$ip_address;
1187 if (! -f
$sshknownhosts) {
1188 if (my $fh = IO
::File-
>new($sshknownhosts, O_CREAT
|O_WRONLY
|O_EXCL
, 0600)) {
1193 my $old = PVE
::Tools
::file_get_contents
($sshknownhosts, 128*1024);
1197 if ((! -l
$sshglobalknownhosts) && (-f
$sshglobalknownhosts)) {
1198 $new = PVE
::Tools
::file_get_contents
($sshglobalknownhosts, 128*1024);
1201 my $hostkey = PVE
::Tools
::file_get_contents
($ssh_host_rsa_id);
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;
1212 my $merge_line = sub {
1213 my ($line, $all) = @_;
1215 if ($line =~ m/^(\S+)\s(ssh-rsa\s\S+)(\s.*)?$/) {
1218 if (!$vhash->{$key}) {
1220 if ($key =~ m/\|1\|([^\|\s]+)\|([^\|\s]+)$/) {
1221 my $salt = decode_base64
($1);
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;
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;
1251 while ($old && $old =~ s/^((.*?)(\n|$))//) {
1253 next if $line =~ m/^\s*$/; # skip empty lines
1254 next if $line =~ m/^#/; # skip comments
1255 &$merge_line($line, 1);
1258 while ($new && $new =~ s/^((.*?)(\n|$))//) {
1260 next if $line =~ m/^\s*$/; # skip empty lines
1261 next if $line =~ m/^#/; # skip comments
1262 &$merge_line($line);
1266 my $add_known_hosts_entry = sub {
1267 my ($name, $hostkey) = @_;
1269 my $hmac = Digest
::HMAC_SHA1-
>new("$addIndex" . time());
1270 my $b64salt = $hmac->b64digest . '=';
1271 $hmac = Digest
::HMAC_SHA1-
>new(decode_base64
($b64salt));
1273 my $digest = $hmac->b64digest . '=';
1274 $data .= "|1|$b64salt|$digest $hostkey\n";
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;
1282 PVE
::Tools
::file_set_contents
($sshknownhosts, $data);
1284 return if !$createLink;
1286 unlink $sshglobalknownhosts;
1287 symlink $sshknownhosts, $sshglobalknownhosts;
1289 warn "can't create symlink for ssh known hosts '$sshglobalknownhosts' -> '$sshknownhosts'\n"
1290 if ! -l
$sshglobalknownhosts;
1294 my $datacenter_schema = {
1296 additionalProperties
=> 0,
1301 description
=> "Default keybord layout for vnc server.",
1302 enum
=> PVE
::Tools
::kvmkeymaplist
(),
1307 description
=> "Default GUI language.",
1308 enum
=> [ 'en', 'de' ],
1313 description
=> "Specify external http proxy which is used for downloads (example: 'http://username:password\@host:port/')",
1314 pattern
=> "http://.*",
1316 migration_unsecure
=> {
1319 description
=> "Migration is secure using SSH tunnel by default. For secure private networks you can disable it to speed up migration.",
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'],
1330 format
=> 'email-opt',
1331 description
=> "Specify email address to send notification from (default is root@\$hostname)",
1337 description
=> "Defines how many workers (per node) are maximal started ".
1338 " on actions like 'stopall VMs' or task from the ha-manager.",
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 "\n\nWARNING: 'hardware' and 'both' are EXPERIMENTAL & WIP",
1353 # make schema accessible from outside (for documentation)
1354 sub get_datacenter_schema
{ return $datacenter_schema };
1356 sub parse_datacenter_config
{
1357 my ($filename, $raw) = @_;
1359 return PVE
::JSONSchema
::parse_config
($datacenter_schema, $filename, $raw // '');
1362 sub write_datacenter_config
{
1363 my ($filename, $cfg) = @_;
1365 return PVE
::JSONSchema
::dump_config
($datacenter_schema, $filename, $cfg);
1368 cfs_register_file
('datacenter.cfg',
1369 \
&parse_datacenter_config
,
1370 \
&write_datacenter_config
);
1372 # a very simply parser ...
1373 sub parse_corosync_conf
{
1374 my ($filename, $raw) = @_;
1378 my $digest = Digest
::SHA
::sha1_hex
(defined($raw) ?
$raw : '');
1381 $raw =~ s/\r?\n/ /g;
1386 my @tokens = split(/\s/, $raw);
1388 my $conf = { section
=> 'main', children
=> [] };
1391 my $section = $conf;
1393 while (defined(my $token = shift @tokens)) {
1394 my $nexttok = $tokens[0];
1396 if ($nexttok && ($nexttok eq '{')) {
1397 shift @tokens; # skip '{'
1402 push @{$section->{children
}}, $new_section;
1403 push @$stack, $section;
1404 $section = $new_section;
1408 if ($token eq '}') {
1409 $section = pop @$stack;
1410 die "parse error - uncexpected '}'\n" if !$section;
1415 die "missing ':' after key '$key'\n" if ! ($key =~ s/:$//);
1417 die "parse error - no value for '$key'\n" if !defined($nexttok);
1418 my $value = shift @tokens;
1420 push @{$section->{children
}}, { key
=> $key, value
=> $value };
1423 $conf->{digest
} = $digest;
1428 my $dump_corosync_section;
1429 $dump_corosync_section = sub {
1430 my ($section, $prefix) = @_;
1432 my $raw = $prefix . $section->{section
} . " {\n";
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";
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 ");
1444 $raw .= $prefix . "}\n\n";
1450 sub write_corosync_conf
{
1451 my ($filename, $conf) = @_;
1457 die "no main section" if $conf->{section
} ne 'main';
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";
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);
1472 sub corosync_conf_version
{
1473 my ($conf, $noerr, $new_value) = @_;
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') {
1482 $e->{value
} = $new_value;
1484 } elsif (my $version = int($e->{value
})) {
1493 return undef if $noerr;
1495 die "invalid corosync config - unable to read version\n";
1498 # read only - use "rename corosync.conf.new corosync.conf" to write
1499 PVE
::Cluster
::cfs_register_file
('corosync.conf', \
&parse_corosync_conf
);
1500 # this is read/write
1501 PVE
::Cluster
::cfs_register_file
('corosync.conf.new', \
&parse_corosync_conf
,
1502 \
&write_corosync_conf
);
1504 sub check_corosync_conf_exists
{
1507 $silent = $silent // 0;
1509 my $exists = -f
"$basedir/corosync.conf";
1511 warn "Corosync config '$basedir/corosync.conf' does not exist - is this node part of a cluster?\n"
1512 if !$silent && !$exists;
1517 # bash completion helpers
1519 sub complete_next_vmid
{
1521 my $vmlist = get_vmlist
() || {};
1522 my $idlist = $vmlist->{ids
} || {};
1524 for (my $i = 100; $i < 10000; $i++) {
1525 return [$i] if !defined($idlist->{$i});
1533 my $vmlist = get_vmlist
();
1534 my $ids = $vmlist->{ids
} || {};
1536 return [ keys %$ids ];
1539 sub complete_local_vmid
{
1541 my $vmlist = get_vmlist
();
1542 my $ids = $vmlist->{ids
} || {};
1544 my $nodename = PVE
::INotify
::nodename
();
1547 foreach my $vmid (keys %$ids) {
1548 my $d = $ids->{$vmid};
1549 next if !$d->{node
} || $d->{node
} ne $nodename;
1556 sub complete_migration_target
{
1560 my $nodename = PVE
::INotify
::nodename
();
1562 my $nodelist = get_nodelist
();
1563 foreach my $node (@$nodelist) {
1564 next if $node eq $nodename;