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,
62 'ha/crm_commands' => 1,
63 'ha/manager_status' => 1,
64 'ha/resources.cfg' => 1,
71 'sdn/controllers.cfg' => 1,
72 'virtual-guest/cpu-models.conf' => 1,
75 sub prepare_observed_file_basedirs
{
77 if (check_cfs_is_mounted
(1)) {
78 warn "pmxcfs isn't mounted (/etc/pve), chickening out..\n";
82 for my $f (sort keys %$observed) {
83 next if $f !~ m!^(.*)/[^/]+$!;
84 my $dir = "$basedir/$1";
85 next if -e
$dir; # can also be a link, so just use -e xist check
86 print "creating directory '$dir' for observerd files\n";
99 sub check_cfs_quorum
{
102 # note: -w filename always return 1 for root, so wee need
103 # to use File::lstat here
104 my $st = File
::stat::lstat("$basedir/local");
105 my $quorate = ($st && (($st->mode & 0200) != 0));
107 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
112 sub check_cfs_is_mounted
{
115 my $res = -l
"$basedir/local";
117 die "pve configuration filesystem not mounted\n"
127 my $ipcc_send_rec = sub {
128 my ($msgid, $data) = @_;
130 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
132 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
137 my $ipcc_send_rec_json = sub {
138 my ($msgid, $data) = @_;
140 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
142 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
144 return decode_json
($res);
147 my $ipcc_get_config = sub {
150 my $bindata = pack "Z*", $path;
151 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_CONFIG
, $bindata);
152 if (!defined($res)) {
154 return undef if $! == ENOENT
;
163 my $ipcc_get_status = sub {
164 my ($name, $nodename) = @_;
166 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
167 return PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_STATUS
, $bindata);
170 my $ipcc_remove_status = sub {
172 # we just omit the data payload, pmxcfs takes this as hint and removes this
173 # key from the status hashtable
174 my $bindata = pack "Z[256]", $name;
175 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
178 my $ipcc_update_status = sub {
179 my ($name, $data) = @_;
181 my $raw = ref($data) ? encode_json
($data) : $data;
183 my $bindata = pack "Z[256]Z*", $name, $raw;
185 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
189 my ($priority, $ident, $tag, $msg) = @_;
191 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
192 bytes
::length($tag) + 1, $ident, $tag, $msg;
194 return &$ipcc_send_rec(CFS_IPC_LOG_CLUSTER_MSG
, $bindata);
197 my $ipcc_get_cluster_log = sub {
198 my ($user, $max) = @_;
200 $max = 0 if !defined($max);
202 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
203 return &$ipcc_send_rec(CFS_IPC_GET_CLUSTER_LOG
, $bindata);
206 my $ipcc_verify_token = sub {
207 my ($full_token) = @_;
209 my $bindata = pack "Z*", $full_token;
210 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_VERIFY_TOKEN
, $bindata);
213 return 0 if $! == ENOENT
;
223 my $res = &$ipcc_send_rec_json(CFS_IPC_GET_FS_VERSION
);
224 die "no starttime\n" if !$res->{starttime
};
226 if (!$res->{starttime
} || !$versions->{starttime
} ||
227 $res->{starttime
} != $versions->{starttime
}) {
228 #print "detected changed starttime\n";
247 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
248 #warn "detected new clinfo\n";
249 $clinfo = &$ipcc_send_rec_json(CFS_IPC_GET_CLUSTER_INFO
);
260 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
261 #warn "detected new vmlist1\n";
262 $vmlist = &$ipcc_send_rec_json(CFS_IPC_GET_GUEST_LIST
);
282 return $clinfo->{nodelist
};
286 my $nodelist = $clinfo->{nodelist
};
288 my $nodename = PVE
::INotify
::nodename
();
290 if (!$nodelist || !$nodelist->{$nodename}) {
291 return [ $nodename ];
294 return [ keys %$nodelist ];
297 # only stored in a in-memory hashtable inside pmxcfs, local data is gone after
298 # a restart (of pmxcfs or the node), peer data is still available then
299 # best used for status data, like running (ceph) services, package versions, ...
300 sub broadcast_node_kv
{
301 my ($key, $data) = @_;
303 if (!defined($data)) {
305 $ipcc_remove_status->("kv/$key");
308 die "cannot send a reference\n" if ref($data);
309 my $size = length($data);
310 die "data for '$key' too big\n" if $size >= (32 * 1024); # limit from pmxfs
313 $ipcc_update_status->("kv/$key", $data);
320 # nodename is optional
322 my ($key, $nodename) = @_;
325 my $get_node_data = sub {
327 my $raw = $ipcc_get_status->("kv/$key", $node);
328 $res->{$node} = unpack("Z*", $raw) if $raw;
332 $get_node_data->($nodename);
334 my $nodelist = get_nodelist
();
336 foreach my $node (@$nodelist) {
337 $get_node_data->($node);
344 # property: a config property you want to get, e.g., this is perfect to get
345 # the 'lock' entry of a guest _fast_ (>100 faster than manual parsing here)
346 # vmid: optipnal, if a valid is passed we only check that one, else return all
347 # NOTE: does *not* searches snapshot and PENDING entries sections!
348 sub get_guest_config_property
{
349 my ($property, $vmid) = @_;
351 die "property is required" if !defined($property);
353 my $bindata = pack "VZ*", $vmid // 0, $property;
354 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTY
, $bindata);
359 # $data must be a chronological descending ordered array of tasks
360 sub broadcast_tasklist
{
363 # the serialized list may not get bigger than 32kb (CFS_MAX_STATUS_SIZE
364 # from pmxcfs) - drop older items until we satisfy this constraint
365 my $size = length(encode_json
($data));
366 while ($size >= (32 * 1024)) {
368 $size = length(encode_json
($data));
372 &$ipcc_update_status("tasklist", $data);
378 my $tasklistcache = {};
383 my $kvstore = $versions->{kvstore
} || {};
385 my $nodelist = get_nodelist
();
388 foreach my $node (@$nodelist) {
389 next if $nodename && ($nodename ne $node);
391 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
392 my $cd = $tasklistcache->{$node};
393 if (!$cd || !$ver || !$cd->{version
} ||
394 ($cd->{version
} != $ver)) {
395 my $raw = &$ipcc_get_status("tasklist", $node) || '[]';
396 my $data = decode_json
($raw);
398 $cd = $tasklistcache->{$node} = {
402 } elsif ($cd && $cd->{data
}) {
403 push @$res, @{$cd->{data
}};
407 syslog
('err', $err) if $err;
414 my ($rrdid, $data) = @_;
417 &$ipcc_update_status("rrd/$rrdid", $data);
424 my $last_rrd_dump = 0;
425 my $last_rrd_data = "";
431 my $diff = $ctime - $last_rrd_dump;
433 return $last_rrd_data;
438 $raw = &$ipcc_send_rec(CFS_IPC_GET_RRD_DUMP
);
450 while ($raw =~ s/^(.*)\n//) {
451 my ($key, @ela) = split(/:/, $1);
453 next if !(scalar(@ela) > 1);
454 $res->{$key} = [ map { $_ eq 'U' ?
undef : $_ } @ela ];
458 $last_rrd_dump = $ctime;
459 $last_rrd_data = $res;
465 # a fast way to read files (avoid fuse overhead)
469 return &$ipcc_get_config($path);
472 sub get_cluster_log
{
473 my ($user, $max) = @_;
475 return &$ipcc_get_cluster_log($user, $max);
479 my ($userid, $token) = @_;
481 return &$ipcc_verify_token("$userid $token");
486 sub cfs_register_file
{
487 my ($filename, $parser, $writer) = @_;
489 $observed->{$filename} || die "unknown file '$filename'";
491 die "file '$filename' already registered" if $file_info->{$filename};
493 $file_info->{$filename} = {
499 my $ccache_read = sub {
500 my ($filename, $parser, $version) = @_;
502 $ccache->{$filename} = {} if !$ccache->{$filename};
504 my $ci = $ccache->{$filename};
506 if (!$ci->{version
} || !$version || $ci->{version
} != $version) {
507 # we always call the parser, even when the file does not exist
508 # (in that case $data is undef)
509 my $data = get_config
($filename);
510 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
511 $ci->{version
} = $version;
514 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
519 sub cfs_file_version
{
524 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
525 my ($type, $vmid) = ($1, $2);
526 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
527 $version = $vmlist->{ids
}->{$vmid}->{version
};
529 $infotag = "/$type/";
531 $infotag = $filename;
532 $version = $versions->{$filename};
535 my $info = $file_info->{$infotag} ||
536 die "unknown file type '$filename'\n";
538 return wantarray ?
($version, $info) : $version;
544 my ($version, $info) = cfs_file_version
($filename);
545 my $parser = $info->{parser
};
547 return &$ccache_read($filename, $parser, $version);
551 my ($filename, $data) = @_;
553 my ($version, $info) = cfs_file_version
($filename);
555 my $writer = $info->{writer
} || die "no writer defined";
557 my $fsname = "/etc/pve/$filename";
559 my $raw = &$writer($fsname, $data);
561 if (my $ci = $ccache->{$filename}) {
562 $ci->{version
} = undef;
565 PVE
::Tools
::file_set_contents
($fsname, $raw);
569 my ($lockid, $timeout, $code, @param) = @_;
571 my $prev_alarm = alarm(0); # suspend outer alarm early
576 # this timeout is for acquire the lock
577 $timeout = 10 if !$timeout;
579 my $filename = "$lockdir/$lockid";
586 die "pve cluster filesystem not online.\n";
589 my $timeout_err = sub { die "got lock request timeout\n"; };
590 local $SIG{ALRM
} = $timeout_err;
594 $got_lock = mkdir($filename);
595 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
599 $timeout_err->() if $timeout <= 0;
601 print STDERR
"trying to acquire cfs lock '$lockid' ...\n";
602 utime (0, 0, $filename); # cfs unlock request
606 # fixed command timeout: cfs locks have a timeout of 120
607 # using 60 gives us another 60 seconds to abort the task
608 local $SIG{ALRM
} = sub { die "got lock timeout - aborting command\n"; };
611 cfs_update
(); # make sure we read latest versions inside code()
613 $res = &$code(@param);
620 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum
(1);
622 rmdir $filename if $got_lock; # if we held the lock always unlock again
627 if (ref($err) eq 'PVE::Exception') {
628 # re-raise defined exceptions
631 # add lock info for plain errors
632 $@ = "error during cfs-locked '$lockid' operation: $err";
643 my ($filename, $timeout, $code, @param) = @_;
645 my $info = $observed->{$filename} || die "unknown file '$filename'";
647 my $lockid = "file-$filename";
648 $lockid =~ s/[.\/]/_
/g
;
650 &$cfs_lock($lockid, $timeout, $code, @param);
653 sub cfs_lock_storage
{
654 my ($storeid, $timeout, $code, @param) = @_;
656 my $lockid = "storage-$storeid";
658 &$cfs_lock($lockid, $timeout, $code, @param);
661 sub cfs_lock_domain
{
662 my ($domainname, $timeout, $code, @param) = @_;
664 my $lockid = "domain-$domainname";
666 &$cfs_lock($lockid, $timeout, $code, @param);
670 my ($account, $timeout, $code, @param) = @_;
672 my $lockid = "acme-$account";
674 &$cfs_lock($lockid, $timeout, $code, @param);
677 sub cfs_lock_authkey
{
678 my ($timeout, $code, @param) = @_;
680 $cfs_lock->('authkey', $timeout, $code, @param);
683 sub cfs_lock_firewall
{
684 my ($scope, $timeout, $code, @param) = @_;
686 my $lockid = "firewall-$scope";
688 $cfs_lock->($lockid, $timeout, $code, @param);
706 my ($priority, $ident, $msg) = @_;
708 if (my $tmp = $log_levels->{$priority}) {
712 die "need numeric log priority" if $priority !~ /^\d+$/;
714 my $tag = PVE
::SafeSyslog
::tag
();
716 $msg = "empty message" if !$msg;
718 $ident = "" if !$ident;
719 $ident = encode
("ascii", $ident,
720 sub { sprintf "\\u%04x", shift });
722 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
725 syslog
($priority, "<%s> %s", $ident, $ascii);
727 syslog
($priority, "%s", $ascii);
730 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
732 syslog
("err", "writing cluster log failed: $@") if $@;
735 sub check_vmid_unused
{
736 my ($vmid, $noerr) = @_;
738 my $vmlist = get_vmlist
();
740 my $d = $vmlist->{ids
}->{$vmid};
741 return 1 if !defined($d);
743 return undef if $noerr;
745 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
746 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
749 sub check_node_exists
{
750 my ($nodename, $noerr) = @_;
752 my $nodelist = $clinfo->{nodelist
};
753 return 1 if $nodelist && $nodelist->{$nodename};
755 return undef if $noerr;
757 die "no such cluster node '$nodename'\n";
760 # this is also used to get the IP of the local node
762 my ($nodename, $noerr) = @_;
764 my $nodelist = $clinfo->{nodelist
};
765 if ($nodelist && $nodelist->{$nodename}) {
766 if (my $ip = $nodelist->{$nodename}->{ip
}) {
767 return $ip if !wantarray;
768 my $family = $nodelist->{$nodename}->{address_family
};
770 $nodelist->{$nodename}->{address_family
} =
772 PVE
::Tools
::get_host_address_family
($ip);
774 return wantarray ?
($ip, $family) : $ip;
778 # fallback: try to get IP by other means
779 return PVE
::Network
::get_ip_from_hostname
($nodename, $noerr);
782 sub get_node_fingerprint
{
785 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
786 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
788 $cert_path = $custom_cert_path if -f
$custom_cert_path;
790 return PVE
::Certificate
::get_certificate_fingerprint
($cert_path);
793 # bash completion helpers
795 sub complete_next_vmid
{
797 my $vmlist = get_vmlist
() || {};
798 my $idlist = $vmlist->{ids
} || {};
800 for (my $i = 100; $i < 10000; $i++) {
801 return [$i] if !defined($idlist->{$i});
809 my $vmlist = get_vmlist
();
810 my $ids = $vmlist->{ids
} || {};
812 return [ keys %$ids ];
815 sub complete_local_vmid
{
817 my $vmlist = get_vmlist
();
818 my $ids = $vmlist->{ids
} || {};
820 my $nodename = PVE
::INotify
::nodename
();
823 foreach my $vmid (keys %$ids) {
824 my $d = $ids->{$vmid};
825 next if !$d->{node
} || $d->{node
} ne $nodename;
832 sub complete_migration_target
{
836 my $nodename = PVE
::INotify
::nodename
();
838 my $nodelist = get_nodelist
();
839 foreach my $node (@$nodelist) {
840 next if $node eq $nodename;
848 # NOTE: filesystem must be offline here, no DB changes allowed
849 sub cfs_backup_database
{
853 my $backup_fn = "$dbbackupdir/config-$ctime.sql.gz";
855 print "backup old database to '$backup_fn'\n";
857 my $cmd = [ ['sqlite3', $dbfile, '.dump'], ['gzip', '-', \
">${backup_fn}"] ];
858 run_command
($cmd, 'errmsg' => "cannot backup old database\n");
860 my $maxfiles = 10; # purge older backup
861 my $backups = [ sort { $b cmp $a } <$dbbackupdir/config-*.sql
.gz
> ];
863 if ((my $count = scalar(@$backups)) > $maxfiles) {
864 foreach my $f (@$backups[$maxfiles..$count-1]) {
865 next if $f !~ m/^(\S+)$/; # untaint
866 print "delete old backup '$1'\n";