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
50 'datacenter.cfg' => 1,
51 'replication.cfg' => 1,
53 'corosync.conf.new' => 1,
56 'priv/shadow.cfg' => 1,
58 'priv/token.cfg' => 1,
59 'priv/acme/plugins.cfg' => 1,
64 'ha/crm_commands' => 1,
65 'ha/manager_status' => 1,
66 'ha/resources.cfg' => 1,
73 'sdn/controllers.cfg' => 1,
74 'sdn/subnets.cfg' => 1,
77 'sdn/.running-config' => 1,
78 'virtual-guest/cpu-models.conf' => 1,
79 'nodes/hardware-map.conf' => 1,
82 sub prepare_observed_file_basedirs
{
84 if (!check_cfs_is_mounted
(1)) {
85 warn "pmxcfs isn't mounted (/etc/pve), chickening out..\n";
89 for my $f (sort keys %$observed) {
90 next if $f !~ m!^(.*)/[^/]+$!;
91 my $dir = "$basedir/$1";
92 next if -e
$dir; # can also be a link, so just use -e xist check
93 print "creating directory '$dir' for observerd files\n";
106 sub check_cfs_quorum
{
109 # note: -w filename always return 1 for root, so wee need
110 # to use File::lstat here
111 my $st = File
::stat::lstat("$basedir/local");
112 my $quorate = ($st && (($st->mode & 0200) != 0));
114 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
119 sub check_cfs_is_mounted
{
122 my $res = -l
"$basedir/local";
124 die "pve configuration filesystem (pmxcfs) not mounted\n" if !$res && !$noerr;
133 my $ipcc_send_rec = sub {
134 my ($msgid, $data) = @_;
136 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
138 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
143 my $ipcc_send_rec_json = sub {
144 my ($msgid, $data) = @_;
146 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
148 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
150 return decode_json
($res);
153 my $ipcc_get_config = sub {
156 my $bindata = pack "Z*", $path;
157 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_CONFIG
, $bindata);
158 if (!defined($res)) {
160 return undef if $! == ENOENT
;
169 my $ipcc_get_status = sub {
170 my ($name, $nodename) = @_;
172 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
173 return PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_STATUS
, $bindata);
176 my $ipcc_remove_status = sub {
178 # we just omit the data payload, pmxcfs takes this as hint and removes this
179 # key from the status hashtable
180 my $bindata = pack "Z[256]", $name;
181 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
184 my $ipcc_update_status = sub {
185 my ($name, $data) = @_;
187 my $raw = ref($data) ? encode_json
($data) : $data;
189 my $bindata = pack "Z[256]Z*", $name, $raw;
191 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
195 my ($priority, $ident, $tag, $msg) = @_;
197 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
198 bytes
::length($tag) + 1, $ident, $tag, $msg;
200 return &$ipcc_send_rec(CFS_IPC_LOG_CLUSTER_MSG
, $bindata);
203 my $ipcc_get_cluster_log = sub {
204 my ($user, $max) = @_;
206 $max = 0 if !defined($max);
208 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
209 return &$ipcc_send_rec(CFS_IPC_GET_CLUSTER_LOG
, $bindata);
212 my $ipcc_verify_token = sub {
213 my ($full_token) = @_;
215 my $bindata = pack "Z*", $full_token;
216 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_VERIFY_TOKEN
, $bindata);
219 return 0 if $! == ENOENT
;
229 my $res = &$ipcc_send_rec_json(CFS_IPC_GET_FS_VERSION
);
230 die "no starttime\n" if !$res->{starttime
};
232 if (!$res->{starttime
} || !$versions->{starttime
} ||
233 $res->{starttime
} != $versions->{starttime
}) {
234 #print "detected changed starttime\n";
253 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
254 #warn "detected new clinfo\n";
255 $clinfo = &$ipcc_send_rec_json(CFS_IPC_GET_CLUSTER_INFO
);
266 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
267 #warn "detected new vmlist1\n";
268 $vmlist = &$ipcc_send_rec_json(CFS_IPC_GET_GUEST_LIST
);
288 return $clinfo->{nodelist
};
292 my $nodelist = $clinfo->{nodelist
};
294 my $nodename = PVE
::INotify
::nodename
();
296 if (!$nodelist || !$nodelist->{$nodename}) {
297 return [ $nodename ];
300 return [ keys %$nodelist ];
303 # only stored in a in-memory hashtable inside pmxcfs, local data is gone after
304 # a restart (of pmxcfs or the node), peer data is still available then
305 # best used for status data, like running (ceph) services, package versions, ...
306 sub broadcast_node_kv
{
307 my ($key, $data) = @_;
309 if (!defined($data)) {
310 eval { $ipcc_remove_status->("kv/$key") };
312 die "cannot send a reference\n" if ref($data);
313 my $size = length($data);
314 die "data for '$key' too big\n" if $size >= (32 * 1024); # limit from pmxfs
316 eval { $ipcc_update_status->("kv/$key", $data) };
321 # nodename is optional
323 my ($key, $nodename) = @_;
326 my $get_node_data = sub {
328 my $raw = $ipcc_get_status->("kv/$key", $node);
329 $res->{$node} = unpack("Z*", $raw) if $raw;
333 $get_node_data->($nodename);
335 for my $node (get_nodelist
()->@*) {
336 $get_node_data->($node);
343 # property: a config property you want to get, e.g., this is perfect to get
344 # the 'lock' entry of a guest _fast_ (>100 faster than manual parsing here)
345 # vmid: optional, if a valid is passed we only check that one, else return all
346 # NOTE: does *not* searches snapshot and PENDING entries sections!
347 sub get_guest_config_property
{
348 my ($property, $vmid) = @_;
350 die "property is required" if !defined($property);
352 my $bindata = pack "VZ*", $vmid // 0, $property;
353 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTY
, $bindata);
358 # $data must be a chronological descending ordered array of tasks
359 sub broadcast_tasklist
{
362 # the serialized list may not get bigger than 128 KiB (CFS_MAX_STATUS_SIZE from pmxcfs)
363 # drop older items until we satisfy this constraint
364 my $size = length(encode_json
($data));
365 while ($size >= (32 * 1024)) { # TODO: update to 128 KiB in PVE 8.x
367 $size = length(encode_json
($data));
370 eval { $ipcc_update_status->("tasklist", $data) };
374 my $tasklistcache = {};
379 my $kvstore = $versions->{kvstore
} || {};
381 my $nodelist = get_nodelist
();
384 foreach my $node (@$nodelist) {
385 next if $nodename && ($nodename ne $node);
387 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
388 my $cache = $tasklistcache->{$node};
389 if (!$cache || !$ver || !$cache->{version
} || ($cache->{version
} != $ver)) {
391 if (my $raw = $ipcc_get_status->("tasklist", $node)) {
392 my $json_str = unpack("Z*", $raw);
393 $tasks = decode_json
($json_str);
396 $tasklistcache->{$node} = {
400 } elsif ($cache && $cache->{data
}) {
401 push @$res, $cache->{data
}->@*;
405 syslog
('err', $err) if $err;
412 my ($rrdid, $data) = @_;
415 &$ipcc_update_status("rrd/$rrdid", $data);
422 my $last_rrd_dump = 0;
423 my $last_rrd_data = "";
429 my $diff = $ctime - $last_rrd_dump;
431 return $last_rrd_data;
436 $raw = &$ipcc_send_rec(CFS_IPC_GET_RRD_DUMP
);
448 while ($raw =~ s/^(.*)\n//) {
449 my ($key, @ela) = split(/:/, $1);
451 next if !(scalar(@ela) > 1);
452 $res->{$key} = [ map { $_ eq 'U' ?
undef : $_ } @ela ];
456 $last_rrd_dump = $ctime;
457 $last_rrd_data = $res;
463 # a fast way to read files (avoid fuse overhead)
467 return &$ipcc_get_config($path);
470 sub get_cluster_log
{
471 my ($user, $max) = @_;
473 return &$ipcc_get_cluster_log($user, $max);
477 my ($userid, $token) = @_;
479 return &$ipcc_verify_token("$userid $token");
484 sub cfs_register_file
{
485 my ($filename, $parser, $writer) = @_;
487 $observed->{$filename} || die "unknown file '$filename'";
489 die "file '$filename' already registered" if $file_info->{$filename};
491 $file_info->{$filename} = {
497 my $ccache_read = sub {
498 my ($filename, $parser, $version) = @_;
500 $ccache->{$filename} = {} if !$ccache->{$filename};
502 my $ci = $ccache->{$filename};
504 if (!$ci->{version
} || !$version || $ci->{version
} != $version) {
505 # we always call the parser, even when the file does not exist
506 # (in that case $data is undef)
507 my $data = get_config
($filename);
508 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
509 $ci->{version
} = $version;
512 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
517 sub cfs_file_version
{
522 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
523 my ($type, $vmid) = ($1, $2);
524 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
525 $version = $vmlist->{ids
}->{$vmid}->{version
};
527 $infotag = "/$type/";
529 $infotag = $filename;
530 $version = $versions->{$filename};
533 my $info = $file_info->{$infotag} ||
534 die "unknown file type '$filename'\n";
536 return wantarray ?
($version, $info) : $version;
542 my ($version, $info) = cfs_file_version
($filename);
543 my $parser = $info->{parser
};
545 return &$ccache_read($filename, $parser, $version);
549 my ($filename, $data) = @_;
551 my ($version, $info) = cfs_file_version
($filename);
553 my $writer = $info->{writer
} || die "no writer defined";
555 my $fsname = "/etc/pve/$filename";
557 my $raw = &$writer($fsname, $data);
559 if (my $ci = $ccache->{$filename}) {
560 $ci->{version
} = undef;
563 PVE
::Tools
::file_set_contents
($fsname, $raw);
567 my ($lockid, $timeout, $code, @param) = @_;
569 my $prev_alarm = alarm(0); # suspend outer alarm early
574 # this timeout is for acquire the lock
575 $timeout = 10 if !$timeout;
577 my $filename = "$lockdir/$lockid";
585 die "pve cluster filesystem not online.\n";
588 my $timeout_err = sub { die "got lock request timeout\n"; };
589 local $SIG{ALRM
} = $timeout_err;
593 $got_lock = mkdir($filename);
594 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
598 $timeout_err->() if $timeout <= 0;
600 print STDERR
"trying to acquire cfs lock '$lockid' ...\n";
601 utime (0, 0, $filename); # cfs unlock request
605 # fixed command timeout: cfs locks have a timeout of 120
606 # using 60 gives us another 60 seconds to abort the task
607 local $SIG{ALRM
} = sub { die "'$lockid'-locked command timed out - aborting\n"; };
610 cfs_update
(); # make sure we read latest versions inside code()
612 $is_code_err = 1; # allows to differ between locking and actual-work errors
614 $res = &$code(@param);
621 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum
(1);
623 rmdir $filename if $got_lock; # if we held the lock always unlock again
628 if (ref($err) eq 'PVE::Exception' || $is_code_err) {
629 # re-raise defined exceptions
632 # add lock info for plain errors comming from the locking itself
633 $@ = "cfs-lock '$lockid' error: $err";
644 my ($filename, $timeout, $code, @param) = @_;
646 my $info = $observed->{$filename} || die "unknown file '$filename'";
648 my $lockid = "file-$filename";
649 $lockid =~ s/[.\/]/_
/g
;
651 &$cfs_lock($lockid, $timeout, $code, @param);
654 sub cfs_lock_storage
{
655 my ($storeid, $timeout, $code, @param) = @_;
657 my $lockid = "storage-$storeid";
659 &$cfs_lock($lockid, $timeout, $code, @param);
662 sub cfs_lock_domain
{
663 my ($domainname, $timeout, $code, @param) = @_;
665 my $lockid = "domain-$domainname";
667 &$cfs_lock($lockid, $timeout, $code, @param);
671 my ($account, $timeout, $code, @param) = @_;
673 my $lockid = "acme-$account";
675 &$cfs_lock($lockid, $timeout, $code, @param);
678 sub cfs_lock_authkey
{
679 my ($timeout, $code, @param) = @_;
681 $cfs_lock->('authkey', $timeout, $code, @param);
684 sub cfs_lock_firewall
{
685 my ($scope, $timeout, $code, @param) = @_;
687 my $lockid = "firewall-$scope";
689 $cfs_lock->($lockid, $timeout, $code, @param);
707 my ($priority, $ident, $msg) = @_;
709 if (my $tmp = $log_levels->{$priority}) {
713 die "need numeric log priority" if $priority !~ /^\d+$/;
715 my $tag = PVE
::SafeSyslog
::tag
();
717 $msg = "empty message" if !$msg;
719 $ident = "" if !$ident;
720 $ident = encode
("ascii", $ident,
721 sub { sprintf "\\u%04x", shift });
723 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
726 syslog
($priority, "<%s> %s", $ident, $ascii);
728 syslog
($priority, "%s", $ascii);
731 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
733 syslog
("err", "writing cluster log failed: $@") if $@;
736 sub check_vmid_unused
{
737 my ($vmid, $noerr) = @_;
739 my $vmlist = get_vmlist
();
741 my $d = $vmlist->{ids
}->{$vmid};
742 return 1 if !defined($d);
744 return undef if $noerr;
746 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
747 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
750 sub check_node_exists
{
751 my ($nodename, $noerr) = @_;
753 my $nodelist = $clinfo->{nodelist
};
754 return 1 if $nodelist && $nodelist->{$nodename};
756 return undef if $noerr;
758 die "no such cluster node '$nodename'\n";
761 # this is also used to get the IP of the local node
763 my ($nodename, $noerr) = @_;
765 my $nodelist = $clinfo->{nodelist
};
766 if ($nodelist && $nodelist->{$nodename}) {
767 if (my $ip = $nodelist->{$nodename}->{ip
}) {
768 return $ip if !wantarray;
769 my $family = $nodelist->{$nodename}->{address_family
};
771 $nodelist->{$nodename}->{address_family
} =
773 PVE
::Tools
::get_host_address_family
($ip);
775 return wantarray ?
($ip, $family) : $ip;
779 # fallback: try to get IP by other means
780 return PVE
::Network
::get_ip_from_hostname
($nodename, $noerr);
783 sub get_node_fingerprint
{
786 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
787 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
789 $cert_path = $custom_cert_path if -f
$custom_cert_path;
791 return PVE
::Certificate
::get_certificate_fingerprint
($cert_path);
794 # bash completion helpers
796 sub complete_next_vmid
{
798 my $vmlist = get_vmlist
() || {};
799 my $idlist = $vmlist->{ids
} || {};
801 for (my $i = 100; $i < 10000; $i++) {
802 return [$i] if !defined($idlist->{$i});
810 my $vmlist = get_vmlist
();
811 my $ids = $vmlist->{ids
} || {};
813 return [ keys %$ids ];
816 sub complete_local_vmid
{
818 my $vmlist = get_vmlist
();
819 my $ids = $vmlist->{ids
} || {};
821 my $nodename = PVE
::INotify
::nodename
();
824 foreach my $vmid (keys %$ids) {
825 my $d = $ids->{$vmid};
826 next if !$d->{node
} || $d->{node
} ne $nodename;
833 sub complete_migration_target
{
837 my $nodename = PVE
::INotify
::nodename
();
839 my $nodelist = get_nodelist
();
840 foreach my $node (@$nodelist) {
841 next if $node eq $nodename;
849 # NOTE: filesystem must be offline here, no DB changes allowed
850 sub cfs_backup_database
{
854 my $backup_fn = "$dbbackupdir/config-$ctime.sql.gz";
856 print "backup old database to '$backup_fn'\n";
858 my $cmd = [ ['sqlite3', $dbfile, '.dump'], ['gzip', '-', \
">${backup_fn}"] ];
859 run_command
($cmd, 'errmsg' => "cannot backup old database\n");
861 my $maxfiles = 10; # purge older backup
862 my $backups = [ sort { $b cmp $a } <$dbbackupdir/config-*.sql
.gz
> ];
864 if ((my $count = scalar(@$backups)) > $maxfiles) {
865 foreach my $f (@$backups[$maxfiles..$count-1]) {
866 next if $f !~ m/^(\S+)$/; # untaint
867 print "delete old backup '$1'\n";