12 use Storable
qw(dclone);
20 use PVE
::Tools
qw(run_command);
22 use PVE
::Cluster
::IPCConst
;
32 # x509 certificate utils
34 my $basedir = "/etc/pve";
35 my $authdir = "$basedir/priv";
36 my $lockdir = "/etc/pve/priv/lock";
38 # cfs and corosync files
39 my $dbfile = "/var/lib/pve-cluster/config.db";
40 my $dbbackupdir = "/var/lib/pve-cluster/backup";
42 # this is just a readonly copy, the relevant one is in status.c from pmxcfs
43 # observed files are the one we can get directly through IPCC, they are cached
44 # using a computed version and only those can be used by the cfs_*_file methods
48 'datacenter.cfg' => 1,
49 'replication.cfg' => 1,
51 'corosync.conf.new' => 1,
54 'priv/shadow.cfg' => 1,
56 'priv/token.cfg' => 1,
60 'ha/crm_commands' => 1,
61 'ha/manager_status' => 1,
62 'ha/resources.cfg' => 1,
68 'sdn/vnets.cfg.new' => 1,
70 'sdn/zones.cfg.new' => 1,
71 'sdn/controllers.cfg' => 1,
72 'sdn/controllers.cfg.new' => 1,
73 'virtual-guest/cpu-models.conf' => 1,
84 sub check_cfs_quorum
{
87 # note: -w filename always return 1 for root, so wee need
88 # to use File::lstat here
89 my $st = File
::stat::lstat("$basedir/local");
90 my $quorate = ($st && (($st->mode & 0200) != 0));
92 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
97 sub check_cfs_is_mounted
{
100 my $res = -l
"$basedir/local";
102 die "pve configuration filesystem not mounted\n"
112 my $ipcc_send_rec = sub {
113 my ($msgid, $data) = @_;
115 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
117 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
122 my $ipcc_send_rec_json = sub {
123 my ($msgid, $data) = @_;
125 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
127 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
129 return decode_json
($res);
132 my $ipcc_get_config = sub {
135 my $bindata = pack "Z*", $path;
136 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_CONFIG
, $bindata);
137 if (!defined($res)) {
139 return undef if $! == ENOENT
;
148 my $ipcc_get_status = sub {
149 my ($name, $nodename) = @_;
151 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
152 return PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_STATUS
, $bindata);
155 my $ipcc_remove_status = sub {
157 # we just omit the data payload, pmxcfs takes this as hint and removes this
158 # key from the status hashtable
159 my $bindata = pack "Z[256]", $name;
160 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
163 my $ipcc_update_status = sub {
164 my ($name, $data) = @_;
166 my $raw = ref($data) ? encode_json
($data) : $data;
168 my $bindata = pack "Z[256]Z*", $name, $raw;
170 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
174 my ($priority, $ident, $tag, $msg) = @_;
176 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
177 bytes
::length($tag) + 1, $ident, $tag, $msg;
179 return &$ipcc_send_rec(CFS_IPC_LOG_CLUSTER_MSG
, $bindata);
182 my $ipcc_get_cluster_log = sub {
183 my ($user, $max) = @_;
185 $max = 0 if !defined($max);
187 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
188 return &$ipcc_send_rec(CFS_IPC_GET_CLUSTER_LOG
, $bindata);
191 my $ipcc_verify_token = sub {
192 my ($full_token) = @_;
194 my $bindata = pack "Z*", $full_token;
195 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_VERIFY_TOKEN
, $bindata);
198 return 0 if $! == ENOENT
;
208 my $res = &$ipcc_send_rec_json(CFS_IPC_GET_FS_VERSION
);
209 die "no starttime\n" if !$res->{starttime
};
211 if (!$res->{starttime
} || !$versions->{starttime
} ||
212 $res->{starttime
} != $versions->{starttime
}) {
213 #print "detected changed starttime\n";
232 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
233 #warn "detected new clinfo\n";
234 $clinfo = &$ipcc_send_rec_json(CFS_IPC_GET_CLUSTER_INFO
);
245 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
246 #warn "detected new vmlist1\n";
247 $vmlist = &$ipcc_send_rec_json(CFS_IPC_GET_GUEST_LIST
);
267 return $clinfo->{nodelist
};
271 my $nodelist = $clinfo->{nodelist
};
273 my $nodename = PVE
::INotify
::nodename
();
275 if (!$nodelist || !$nodelist->{$nodename}) {
276 return [ $nodename ];
279 return [ keys %$nodelist ];
282 # only stored in a in-memory hashtable inside pmxcfs, local data is gone after
283 # a restart (of pmxcfs or the node), peer data is still available then
284 # best used for status data, like running (ceph) services, package versions, ...
285 sub broadcast_node_kv
{
286 my ($key, $data) = @_;
288 if (!defined($data)) {
290 $ipcc_remove_status->("kv/$key");
293 die "cannot send a reference\n" if ref($data);
294 my $size = length($data);
295 die "data for '$key' too big\n" if $size >= (32 * 1024); # limit from pmxfs
298 $ipcc_update_status->("kv/$key", $data);
305 # nodename is optional
307 my ($key, $nodename) = @_;
310 my $get_node_data = sub {
312 my $raw = $ipcc_get_status->("kv/$key", $node);
313 $res->{$node} = unpack("Z*", $raw) if $raw;
317 $get_node_data->($nodename);
319 my $nodelist = get_nodelist
();
321 foreach my $node (@$nodelist) {
322 $get_node_data->($node);
329 # property: a config property you want to get, e.g., this is perfect to get
330 # the 'lock' entry of a guest _fast_ (>100 faster than manual parsing here)
331 # vmid: optipnal, if a valid is passed we only check that one, else return all
332 # NOTE: does *not* searches snapshot and PENDING entries sections!
333 sub get_guest_config_property
{
334 my ($property, $vmid) = @_;
336 die "property is required" if !defined($property);
338 my $bindata = pack "VZ*", $vmid // 0, $property;
339 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTY
, $bindata);
344 # $data must be a chronological descending ordered array of tasks
345 sub broadcast_tasklist
{
348 # the serialized list may not get bigger than 32kb (CFS_MAX_STATUS_SIZE
349 # from pmxcfs) - drop older items until we satisfy this constraint
350 my $size = length(encode_json
($data));
351 while ($size >= (32 * 1024)) {
353 $size = length(encode_json
($data));
357 &$ipcc_update_status("tasklist", $data);
363 my $tasklistcache = {};
368 my $kvstore = $versions->{kvstore
} || {};
370 my $nodelist = get_nodelist
();
373 foreach my $node (@$nodelist) {
374 next if $nodename && ($nodename ne $node);
376 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
377 my $cd = $tasklistcache->{$node};
378 if (!$cd || !$ver || !$cd->{version
} ||
379 ($cd->{version
} != $ver)) {
380 my $raw = &$ipcc_get_status("tasklist", $node) || '[]';
381 my $data = decode_json
($raw);
383 $cd = $tasklistcache->{$node} = {
387 } elsif ($cd && $cd->{data
}) {
388 push @$res, @{$cd->{data
}};
392 syslog
('err', $err) if $err;
399 my ($rrdid, $data) = @_;
402 &$ipcc_update_status("rrd/$rrdid", $data);
409 my $last_rrd_dump = 0;
410 my $last_rrd_data = "";
416 my $diff = $ctime - $last_rrd_dump;
418 return $last_rrd_data;
423 $raw = &$ipcc_send_rec(CFS_IPC_GET_RRD_DUMP
);
435 while ($raw =~ s/^(.*)\n//) {
436 my ($key, @ela) = split(/:/, $1);
438 next if !(scalar(@ela) > 1);
439 $res->{$key} = [ map { $_ eq 'U' ?
undef : $_ } @ela ];
443 $last_rrd_dump = $ctime;
444 $last_rrd_data = $res;
450 # a fast way to read files (avoid fuse overhead)
454 return &$ipcc_get_config($path);
457 sub get_cluster_log
{
458 my ($user, $max) = @_;
460 return &$ipcc_get_cluster_log($user, $max);
464 my ($userid, $token) = @_;
466 return &$ipcc_verify_token("$userid $token");
471 sub cfs_register_file
{
472 my ($filename, $parser, $writer) = @_;
474 $observed->{$filename} || die "unknown file '$filename'";
476 die "file '$filename' already registered" if $file_info->{$filename};
478 $file_info->{$filename} = {
484 my $ccache_read = sub {
485 my ($filename, $parser, $version) = @_;
487 $ccache->{$filename} = {} if !$ccache->{$filename};
489 my $ci = $ccache->{$filename};
491 if (!$ci->{version
} || !$version || $ci->{version
} != $version) {
492 # we always call the parser, even when the file does not exist
493 # (in that case $data is undef)
494 my $data = get_config
($filename);
495 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
496 $ci->{version
} = $version;
499 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
504 sub cfs_file_version
{
509 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
510 my ($type, $vmid) = ($1, $2);
511 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
512 $version = $vmlist->{ids
}->{$vmid}->{version
};
514 $infotag = "/$type/";
516 $infotag = $filename;
517 $version = $versions->{$filename};
520 my $info = $file_info->{$infotag} ||
521 die "unknown file type '$filename'\n";
523 return wantarray ?
($version, $info) : $version;
529 my ($version, $info) = cfs_file_version
($filename);
530 my $parser = $info->{parser
};
532 return &$ccache_read($filename, $parser, $version);
536 my ($filename, $data) = @_;
538 my ($version, $info) = cfs_file_version
($filename);
540 my $writer = $info->{writer
} || die "no writer defined";
542 my $fsname = "/etc/pve/$filename";
544 my $raw = &$writer($fsname, $data);
546 if (my $ci = $ccache->{$filename}) {
547 $ci->{version
} = undef;
550 PVE
::Tools
::file_set_contents
($fsname, $raw);
554 my ($lockid, $timeout, $code, @param) = @_;
556 my $prev_alarm = alarm(0); # suspend outer alarm early
561 # this timeout is for acquire the lock
562 $timeout = 10 if !$timeout;
564 my $filename = "$lockdir/$lockid";
571 die "pve cluster filesystem not online.\n";
574 my $timeout_err = sub { die "got lock request timeout\n"; };
575 local $SIG{ALRM
} = $timeout_err;
579 $got_lock = mkdir($filename);
580 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
584 $timeout_err->() if $timeout <= 0;
586 print STDERR
"trying to acquire cfs lock '$lockid' ...\n";
587 utime (0, 0, $filename); # cfs unlock request
591 # fixed command timeout: cfs locks have a timeout of 120
592 # using 60 gives us another 60 seconds to abort the task
593 local $SIG{ALRM
} = sub { die "got lock timeout - aborting command\n"; };
596 cfs_update
(); # make sure we read latest versions inside code()
598 $res = &$code(@param);
605 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum
(1);
607 rmdir $filename if $got_lock; # if we held the lock always unlock again
612 if (ref($err) eq 'PVE::Exception') {
613 # re-raise defined exceptions
616 # add lock info for plain errors
617 $@ = "error with cfs lock '$lockid': $err";
628 my ($filename, $timeout, $code, @param) = @_;
630 my $info = $observed->{$filename} || die "unknown file '$filename'";
632 my $lockid = "file-$filename";
633 $lockid =~ s/[.\/]/_
/g
;
635 &$cfs_lock($lockid, $timeout, $code, @param);
638 sub cfs_lock_storage
{
639 my ($storeid, $timeout, $code, @param) = @_;
641 my $lockid = "storage-$storeid";
643 &$cfs_lock($lockid, $timeout, $code, @param);
646 sub cfs_lock_domain
{
647 my ($domainname, $timeout, $code, @param) = @_;
649 my $lockid = "domain-$domainname";
651 &$cfs_lock($lockid, $timeout, $code, @param);
655 my ($account, $timeout, $code, @param) = @_;
657 my $lockid = "acme-$account";
659 &$cfs_lock($lockid, $timeout, $code, @param);
662 sub cfs_lock_authkey
{
663 my ($timeout, $code, @param) = @_;
665 $cfs_lock->('authkey', $timeout, $code, @param);
668 sub cfs_lock_firewall
{
669 my ($scope, $timeout, $code, @param) = @_;
671 my $lockid = "firewall-$scope";
673 $cfs_lock->($lockid, $timeout, $code, @param);
691 my ($priority, $ident, $msg) = @_;
693 if (my $tmp = $log_levels->{$priority}) {
697 die "need numeric log priority" if $priority !~ /^\d+$/;
699 my $tag = PVE
::SafeSyslog
::tag
();
701 $msg = "empty message" if !$msg;
703 $ident = "" if !$ident;
704 $ident = encode
("ascii", $ident,
705 sub { sprintf "\\u%04x", shift });
707 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
710 syslog
($priority, "<%s> %s", $ident, $ascii);
712 syslog
($priority, "%s", $ascii);
715 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
717 syslog
("err", "writing cluster log failed: $@") if $@;
720 sub check_vmid_unused
{
721 my ($vmid, $noerr) = @_;
723 my $vmlist = get_vmlist
();
725 my $d = $vmlist->{ids
}->{$vmid};
726 return 1 if !defined($d);
728 return undef if $noerr;
730 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
731 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
734 sub check_node_exists
{
735 my ($nodename, $noerr) = @_;
737 my $nodelist = $clinfo->{nodelist
};
738 return 1 if $nodelist && $nodelist->{$nodename};
740 return undef if $noerr;
742 die "no such cluster node '$nodename'\n";
745 # this is also used to get the IP of the local node
747 my ($nodename, $noerr) = @_;
749 my $nodelist = $clinfo->{nodelist
};
750 if ($nodelist && $nodelist->{$nodename}) {
751 if (my $ip = $nodelist->{$nodename}->{ip
}) {
752 return $ip if !wantarray;
753 my $family = $nodelist->{$nodename}->{address_family
};
755 $nodelist->{$nodename}->{address_family
} =
757 PVE
::Tools
::get_host_address_family
($ip);
759 return wantarray ?
($ip, $family) : $ip;
763 # fallback: try to get IP by other means
764 return PVE
::Network
::get_ip_from_hostname
($nodename, $noerr);
767 sub get_node_fingerprint
{
770 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
771 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
773 $cert_path = $custom_cert_path if -f
$custom_cert_path;
775 return PVE
::Certificate
::get_certificate_fingerprint
($cert_path);
778 # bash completion helpers
780 sub complete_next_vmid
{
782 my $vmlist = get_vmlist
() || {};
783 my $idlist = $vmlist->{ids
} || {};
785 for (my $i = 100; $i < 10000; $i++) {
786 return [$i] if !defined($idlist->{$i});
794 my $vmlist = get_vmlist
();
795 my $ids = $vmlist->{ids
} || {};
797 return [ keys %$ids ];
800 sub complete_local_vmid
{
802 my $vmlist = get_vmlist
();
803 my $ids = $vmlist->{ids
} || {};
805 my $nodename = PVE
::INotify
::nodename
();
808 foreach my $vmid (keys %$ids) {
809 my $d = $ids->{$vmid};
810 next if !$d->{node
} || $d->{node
} ne $nodename;
817 sub complete_migration_target
{
821 my $nodename = PVE
::INotify
::nodename
();
823 my $nodelist = get_nodelist
();
824 foreach my $node (@$nodelist) {
825 next if $node eq $nodename;
833 # NOTE: filesystem must be offline here, no DB changes allowed
834 sub cfs_backup_database
{
838 my $backup_fn = "$dbbackupdir/config-$ctime.sql.gz";
840 print "backup old database to '$backup_fn'\n";
842 my $cmd = [ ['sqlite3', $dbfile, '.dump'], ['gzip', '-', \
">${backup_fn}"] ];
843 run_command
($cmd, 'errmsg' => "cannot backup old database\n");
845 my $maxfiles = 10; # purge older backup
846 my $backups = [ sort { $b cmp $a } <$dbbackupdir/config-*.sql
.gz
> ];
848 if ((my $count = scalar(@$backups)) > $maxfiles) {
849 foreach my $f (@$backups[$maxfiles..$count-1]) {
850 next if $f !~ m/^(\S+)$/; # untaint
851 print "delete old backup '$1'\n";