8 use File
::Path
qw(make_path);
13 use Storable
qw(dclone);
21 use PVE
::Tools
qw(run_command);
23 use PVE
::Cluster
::IPCConst
;
33 # x509 certificate utils
35 my $basedir = "/etc/pve";
36 my $authdir = "$basedir/priv";
37 my $lockdir = "/etc/pve/priv/lock";
39 # cfs and corosync files
40 my $dbfile = "/var/lib/pve-cluster/config.db";
41 my $dbbackupdir = "/var/lib/pve-cluster/backup";
43 # this is just a readonly copy, the relevant one is in status.c from pmxcfs
44 # observed files are the one we can get directly through IPCC, they are cached
45 # using a computed version and only those can be used by the cfs_*_file methods
49 'datacenter.cfg' => 1,
50 'replication.cfg' => 1,
52 'corosync.conf.new' => 1,
55 'priv/shadow.cfg' => 1,
57 'priv/token.cfg' => 1,
58 'priv/acme/plugins.cfg' => 1,
63 'ha/crm_commands' => 1,
64 'ha/manager_status' => 1,
65 'ha/resources.cfg' => 1,
72 'sdn/controllers.cfg' => 1,
73 'sdn/subnets.cfg' => 1,
76 'sdn/.running-config' => 1,
77 'virtual-guest/cpu-models.conf' => 1,
80 sub prepare_observed_file_basedirs
{
82 if (!check_cfs_is_mounted
(1)) {
83 warn "pmxcfs isn't mounted (/etc/pve), chickening out..\n";
87 for my $f (sort keys %$observed) {
88 next if $f !~ m!^(.*)/[^/]+$!;
89 my $dir = "$basedir/$1";
90 next if -e
$dir; # can also be a link, so just use -e xist check
91 print "creating directory '$dir' for observerd files\n";
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"
132 my $ipcc_send_rec = sub {
133 my ($msgid, $data) = @_;
135 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
137 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
142 my $ipcc_send_rec_json = sub {
143 my ($msgid, $data) = @_;
145 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
147 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
149 return decode_json
($res);
152 my $ipcc_get_config = sub {
155 my $bindata = pack "Z*", $path;
156 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_CONFIG
, $bindata);
157 if (!defined($res)) {
159 return undef if $! == ENOENT
;
168 my $ipcc_get_status = sub {
169 my ($name, $nodename) = @_;
171 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
172 return PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_STATUS
, $bindata);
175 my $ipcc_remove_status = sub {
177 # we just omit the data payload, pmxcfs takes this as hint and removes this
178 # key from the status hashtable
179 my $bindata = pack "Z[256]", $name;
180 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
183 my $ipcc_update_status = sub {
184 my ($name, $data) = @_;
186 my $raw = ref($data) ? encode_json
($data) : $data;
188 my $bindata = pack "Z[256]Z*", $name, $raw;
190 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
194 my ($priority, $ident, $tag, $msg) = @_;
196 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
197 bytes
::length($tag) + 1, $ident, $tag, $msg;
199 return &$ipcc_send_rec(CFS_IPC_LOG_CLUSTER_MSG
, $bindata);
202 my $ipcc_get_cluster_log = sub {
203 my ($user, $max) = @_;
205 $max = 0 if !defined($max);
207 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
208 return &$ipcc_send_rec(CFS_IPC_GET_CLUSTER_LOG
, $bindata);
211 my $ipcc_verify_token = sub {
212 my ($full_token) = @_;
214 my $bindata = pack "Z*", $full_token;
215 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_VERIFY_TOKEN
, $bindata);
218 return 0 if $! == ENOENT
;
228 my $res = &$ipcc_send_rec_json(CFS_IPC_GET_FS_VERSION
);
229 die "no starttime\n" if !$res->{starttime
};
231 if (!$res->{starttime
} || !$versions->{starttime
} ||
232 $res->{starttime
} != $versions->{starttime
}) {
233 #print "detected changed starttime\n";
252 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
253 #warn "detected new clinfo\n";
254 $clinfo = &$ipcc_send_rec_json(CFS_IPC_GET_CLUSTER_INFO
);
265 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
266 #warn "detected new vmlist1\n";
267 $vmlist = &$ipcc_send_rec_json(CFS_IPC_GET_GUEST_LIST
);
287 return $clinfo->{nodelist
};
291 my $nodelist = $clinfo->{nodelist
};
293 my $nodename = PVE
::INotify
::nodename
();
295 if (!$nodelist || !$nodelist->{$nodename}) {
296 return [ $nodename ];
299 return [ keys %$nodelist ];
302 # only stored in a in-memory hashtable inside pmxcfs, local data is gone after
303 # a restart (of pmxcfs or the node), peer data is still available then
304 # best used for status data, like running (ceph) services, package versions, ...
305 sub broadcast_node_kv
{
306 my ($key, $data) = @_;
308 if (!defined($data)) {
310 $ipcc_remove_status->("kv/$key");
313 die "cannot send a reference\n" if ref($data);
314 my $size = length($data);
315 die "data for '$key' too big\n" if $size >= (32 * 1024); # limit from pmxfs
318 $ipcc_update_status->("kv/$key", $data);
325 # nodename is optional
327 my ($key, $nodename) = @_;
330 my $get_node_data = sub {
332 my $raw = $ipcc_get_status->("kv/$key", $node);
333 $res->{$node} = unpack("Z*", $raw) if $raw;
337 $get_node_data->($nodename);
339 my $nodelist = get_nodelist
();
341 foreach my $node (@$nodelist) {
342 $get_node_data->($node);
349 # property: a config property you want to get, e.g., this is perfect to get
350 # the 'lock' entry of a guest _fast_ (>100 faster than manual parsing here)
351 # vmid: optipnal, if a valid is passed we only check that one, else return all
352 # NOTE: does *not* searches snapshot and PENDING entries sections!
353 sub get_guest_config_property
{
354 my ($property, $vmid) = @_;
356 die "property is required" if !defined($property);
358 my $bindata = pack "VZ*", $vmid // 0, $property;
359 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTY
, $bindata);
364 # $data must be a chronological descending ordered array of tasks
365 sub broadcast_tasklist
{
368 # the serialized list may not get bigger than 32kb (CFS_MAX_STATUS_SIZE
369 # from pmxcfs) - drop older items until we satisfy this constraint
370 my $size = length(encode_json
($data));
371 while ($size >= (32 * 1024)) {
373 $size = length(encode_json
($data));
377 &$ipcc_update_status("tasklist", $data);
383 my $tasklistcache = {};
388 my $kvstore = $versions->{kvstore
} || {};
390 my $nodelist = get_nodelist
();
393 foreach my $node (@$nodelist) {
394 next if $nodename && ($nodename ne $node);
396 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
397 my $cache = $tasklistcache->{$node};
398 if (!$cache || !$ver || !$cache->{version
} || ($cache->{version
} != $ver)) {
400 if (my $raw = $ipcc_get_status->("tasklist", $node)) {
401 $tasks = decode_json
($raw);
404 $tasklistcache->{$node} = {
408 } elsif ($cache && $cache->{data
}) {
409 push @$res, $cache->{data
}->@*;
413 syslog
('err', $err) if $err;
420 my ($rrdid, $data) = @_;
423 &$ipcc_update_status("rrd/$rrdid", $data);
430 my $last_rrd_dump = 0;
431 my $last_rrd_data = "";
437 my $diff = $ctime - $last_rrd_dump;
439 return $last_rrd_data;
444 $raw = &$ipcc_send_rec(CFS_IPC_GET_RRD_DUMP
);
456 while ($raw =~ s/^(.*)\n//) {
457 my ($key, @ela) = split(/:/, $1);
459 next if !(scalar(@ela) > 1);
460 $res->{$key} = [ map { $_ eq 'U' ?
undef : $_ } @ela ];
464 $last_rrd_dump = $ctime;
465 $last_rrd_data = $res;
471 # a fast way to read files (avoid fuse overhead)
475 return &$ipcc_get_config($path);
478 sub get_cluster_log
{
479 my ($user, $max) = @_;
481 return &$ipcc_get_cluster_log($user, $max);
485 my ($userid, $token) = @_;
487 return &$ipcc_verify_token("$userid $token");
492 sub cfs_register_file
{
493 my ($filename, $parser, $writer) = @_;
495 $observed->{$filename} || die "unknown file '$filename'";
497 die "file '$filename' already registered" if $file_info->{$filename};
499 $file_info->{$filename} = {
505 my $ccache_read = sub {
506 my ($filename, $parser, $version) = @_;
508 $ccache->{$filename} = {} if !$ccache->{$filename};
510 my $ci = $ccache->{$filename};
512 if (!$ci->{version
} || !$version || $ci->{version
} != $version) {
513 # we always call the parser, even when the file does not exist
514 # (in that case $data is undef)
515 my $data = get_config
($filename);
516 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
517 $ci->{version
} = $version;
520 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
525 sub cfs_file_version
{
530 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
531 my ($type, $vmid) = ($1, $2);
532 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
533 $version = $vmlist->{ids
}->{$vmid}->{version
};
535 $infotag = "/$type/";
537 $infotag = $filename;
538 $version = $versions->{$filename};
541 my $info = $file_info->{$infotag} ||
542 die "unknown file type '$filename'\n";
544 return wantarray ?
($version, $info) : $version;
550 my ($version, $info) = cfs_file_version
($filename);
551 my $parser = $info->{parser
};
553 return &$ccache_read($filename, $parser, $version);
557 my ($filename, $data) = @_;
559 my ($version, $info) = cfs_file_version
($filename);
561 my $writer = $info->{writer
} || die "no writer defined";
563 my $fsname = "/etc/pve/$filename";
565 my $raw = &$writer($fsname, $data);
567 if (my $ci = $ccache->{$filename}) {
568 $ci->{version
} = undef;
571 PVE
::Tools
::file_set_contents
($fsname, $raw);
575 my ($lockid, $timeout, $code, @param) = @_;
577 my $prev_alarm = alarm(0); # suspend outer alarm early
582 # this timeout is for acquire the lock
583 $timeout = 10 if !$timeout;
585 my $filename = "$lockdir/$lockid";
593 die "pve cluster filesystem not online.\n";
596 my $timeout_err = sub { die "got lock request timeout\n"; };
597 local $SIG{ALRM
} = $timeout_err;
601 $got_lock = mkdir($filename);
602 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
606 $timeout_err->() if $timeout <= 0;
608 print STDERR
"trying to acquire cfs lock '$lockid' ...\n";
609 utime (0, 0, $filename); # cfs unlock request
613 # fixed command timeout: cfs locks have a timeout of 120
614 # using 60 gives us another 60 seconds to abort the task
615 local $SIG{ALRM
} = sub { die "'$lockid'-locked command timed out - aborting\n"; };
618 cfs_update
(); # make sure we read latest versions inside code()
620 $is_code_err = 1; # allows to differ between locking and actual-work errors
622 $res = &$code(@param);
629 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum
(1);
631 rmdir $filename if $got_lock; # if we held the lock always unlock again
636 if (ref($err) eq 'PVE::Exception' || $is_code_err) {
637 # re-raise defined exceptions
640 # add lock info for plain errors comming from the locking itself
641 $@ = "cfs-lock '$lockid' error: $err";
652 my ($filename, $timeout, $code, @param) = @_;
654 my $info = $observed->{$filename} || die "unknown file '$filename'";
656 my $lockid = "file-$filename";
657 $lockid =~ s/[.\/]/_
/g
;
659 &$cfs_lock($lockid, $timeout, $code, @param);
662 sub cfs_lock_storage
{
663 my ($storeid, $timeout, $code, @param) = @_;
665 my $lockid = "storage-$storeid";
667 &$cfs_lock($lockid, $timeout, $code, @param);
670 sub cfs_lock_domain
{
671 my ($domainname, $timeout, $code, @param) = @_;
673 my $lockid = "domain-$domainname";
675 &$cfs_lock($lockid, $timeout, $code, @param);
679 my ($account, $timeout, $code, @param) = @_;
681 my $lockid = "acme-$account";
683 &$cfs_lock($lockid, $timeout, $code, @param);
686 sub cfs_lock_authkey
{
687 my ($timeout, $code, @param) = @_;
689 $cfs_lock->('authkey', $timeout, $code, @param);
692 sub cfs_lock_firewall
{
693 my ($scope, $timeout, $code, @param) = @_;
695 my $lockid = "firewall-$scope";
697 $cfs_lock->($lockid, $timeout, $code, @param);
715 my ($priority, $ident, $msg) = @_;
717 if (my $tmp = $log_levels->{$priority}) {
721 die "need numeric log priority" if $priority !~ /^\d+$/;
723 my $tag = PVE
::SafeSyslog
::tag
();
725 $msg = "empty message" if !$msg;
727 $ident = "" if !$ident;
728 $ident = encode
("ascii", $ident,
729 sub { sprintf "\\u%04x", shift });
731 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
734 syslog
($priority, "<%s> %s", $ident, $ascii);
736 syslog
($priority, "%s", $ascii);
739 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
741 syslog
("err", "writing cluster log failed: $@") if $@;
744 sub check_vmid_unused
{
745 my ($vmid, $noerr) = @_;
747 my $vmlist = get_vmlist
();
749 my $d = $vmlist->{ids
}->{$vmid};
750 return 1 if !defined($d);
752 return undef if $noerr;
754 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
755 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
758 sub check_node_exists
{
759 my ($nodename, $noerr) = @_;
761 my $nodelist = $clinfo->{nodelist
};
762 return 1 if $nodelist && $nodelist->{$nodename};
764 return undef if $noerr;
766 die "no such cluster node '$nodename'\n";
769 # this is also used to get the IP of the local node
771 my ($nodename, $noerr) = @_;
773 my $nodelist = $clinfo->{nodelist
};
774 if ($nodelist && $nodelist->{$nodename}) {
775 if (my $ip = $nodelist->{$nodename}->{ip
}) {
776 return $ip if !wantarray;
777 my $family = $nodelist->{$nodename}->{address_family
};
779 $nodelist->{$nodename}->{address_family
} =
781 PVE
::Tools
::get_host_address_family
($ip);
783 return wantarray ?
($ip, $family) : $ip;
787 # fallback: try to get IP by other means
788 return PVE
::Network
::get_ip_from_hostname
($nodename, $noerr);
791 sub get_node_fingerprint
{
794 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
795 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
797 $cert_path = $custom_cert_path if -f
$custom_cert_path;
799 return PVE
::Certificate
::get_certificate_fingerprint
($cert_path);
802 # bash completion helpers
804 sub complete_next_vmid
{
806 my $vmlist = get_vmlist
() || {};
807 my $idlist = $vmlist->{ids
} || {};
809 for (my $i = 100; $i < 10000; $i++) {
810 return [$i] if !defined($idlist->{$i});
818 my $vmlist = get_vmlist
();
819 my $ids = $vmlist->{ids
} || {};
821 return [ keys %$ids ];
824 sub complete_local_vmid
{
826 my $vmlist = get_vmlist
();
827 my $ids = $vmlist->{ids
} || {};
829 my $nodename = PVE
::INotify
::nodename
();
832 foreach my $vmid (keys %$ids) {
833 my $d = $ids->{$vmid};
834 next if !$d->{node
} || $d->{node
} ne $nodename;
841 sub complete_migration_target
{
845 my $nodename = PVE
::INotify
::nodename
();
847 my $nodelist = get_nodelist
();
848 foreach my $node (@$nodelist) {
849 next if $node eq $nodename;
857 # NOTE: filesystem must be offline here, no DB changes allowed
858 sub cfs_backup_database
{
862 my $backup_fn = "$dbbackupdir/config-$ctime.sql.gz";
864 print "backup old database to '$backup_fn'\n";
866 my $cmd = [ ['sqlite3', $dbfile, '.dump'], ['gzip', '-', \
">${backup_fn}"] ];
867 run_command
($cmd, 'errmsg' => "cannot backup old database\n");
869 my $maxfiles = 10; # purge older backup
870 my $backups = [ sort { $b cmp $a } <$dbbackupdir/config-*.sql
.gz
> ];
872 if ((my $count = scalar(@$backups)) > $maxfiles) {
873 foreach my $f (@$backups[$maxfiles..$count-1]) {
874 next if $f !~ m/^(\S+)$/; # untaint
875 print "delete old backup '$1'\n";