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,
70 'sdn/vnets.cfg.new' => 1,
72 'sdn/zones.cfg.new' => 1,
73 'sdn/controllers.cfg' => 1,
74 'sdn/controllers.cfg.new' => 1,
75 'virtual-guest/cpu-models.conf' => 1,
78 sub prepare_observed_file_basedirs
{
80 if (check_cfs_is_mounted
(1)) {
81 warn "pmxcfs isn't mounted (/etc/pve), chickening out..\n";
85 for my $f (sort keys %$observed) {
86 next if $f !~ m!^(.*)/[^/]+$!;
87 my $dir = "$basedir/$1";
88 next if -e
$dir; # can also be a link, so just use -e xist check
89 print "creating directory '$dir' for observerd files\n";
102 sub check_cfs_quorum
{
105 # note: -w filename always return 1 for root, so wee need
106 # to use File::lstat here
107 my $st = File
::stat::lstat("$basedir/local");
108 my $quorate = ($st && (($st->mode & 0200) != 0));
110 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
115 sub check_cfs_is_mounted
{
118 my $res = -l
"$basedir/local";
120 die "pve configuration filesystem not mounted\n"
130 my $ipcc_send_rec = sub {
131 my ($msgid, $data) = @_;
133 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
135 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
140 my $ipcc_send_rec_json = sub {
141 my ($msgid, $data) = @_;
143 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
145 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
147 return decode_json
($res);
150 my $ipcc_get_config = sub {
153 my $bindata = pack "Z*", $path;
154 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_CONFIG
, $bindata);
155 if (!defined($res)) {
157 return undef if $! == ENOENT
;
166 my $ipcc_get_status = sub {
167 my ($name, $nodename) = @_;
169 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
170 return PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_STATUS
, $bindata);
173 my $ipcc_remove_status = sub {
175 # we just omit the data payload, pmxcfs takes this as hint and removes this
176 # key from the status hashtable
177 my $bindata = pack "Z[256]", $name;
178 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
181 my $ipcc_update_status = sub {
182 my ($name, $data) = @_;
184 my $raw = ref($data) ? encode_json
($data) : $data;
186 my $bindata = pack "Z[256]Z*", $name, $raw;
188 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
192 my ($priority, $ident, $tag, $msg) = @_;
194 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
195 bytes
::length($tag) + 1, $ident, $tag, $msg;
197 return &$ipcc_send_rec(CFS_IPC_LOG_CLUSTER_MSG
, $bindata);
200 my $ipcc_get_cluster_log = sub {
201 my ($user, $max) = @_;
203 $max = 0 if !defined($max);
205 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
206 return &$ipcc_send_rec(CFS_IPC_GET_CLUSTER_LOG
, $bindata);
209 my $ipcc_verify_token = sub {
210 my ($full_token) = @_;
212 my $bindata = pack "Z*", $full_token;
213 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_VERIFY_TOKEN
, $bindata);
216 return 0 if $! == ENOENT
;
226 my $res = &$ipcc_send_rec_json(CFS_IPC_GET_FS_VERSION
);
227 die "no starttime\n" if !$res->{starttime
};
229 if (!$res->{starttime
} || !$versions->{starttime
} ||
230 $res->{starttime
} != $versions->{starttime
}) {
231 #print "detected changed starttime\n";
250 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
251 #warn "detected new clinfo\n";
252 $clinfo = &$ipcc_send_rec_json(CFS_IPC_GET_CLUSTER_INFO
);
263 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
264 #warn "detected new vmlist1\n";
265 $vmlist = &$ipcc_send_rec_json(CFS_IPC_GET_GUEST_LIST
);
285 return $clinfo->{nodelist
};
289 my $nodelist = $clinfo->{nodelist
};
291 my $nodename = PVE
::INotify
::nodename
();
293 if (!$nodelist || !$nodelist->{$nodename}) {
294 return [ $nodename ];
297 return [ keys %$nodelist ];
300 # only stored in a in-memory hashtable inside pmxcfs, local data is gone after
301 # a restart (of pmxcfs or the node), peer data is still available then
302 # best used for status data, like running (ceph) services, package versions, ...
303 sub broadcast_node_kv
{
304 my ($key, $data) = @_;
306 if (!defined($data)) {
308 $ipcc_remove_status->("kv/$key");
311 die "cannot send a reference\n" if ref($data);
312 my $size = length($data);
313 die "data for '$key' too big\n" if $size >= (32 * 1024); # limit from pmxfs
316 $ipcc_update_status->("kv/$key", $data);
323 # nodename is optional
325 my ($key, $nodename) = @_;
328 my $get_node_data = sub {
330 my $raw = $ipcc_get_status->("kv/$key", $node);
331 $res->{$node} = unpack("Z*", $raw) if $raw;
335 $get_node_data->($nodename);
337 my $nodelist = get_nodelist
();
339 foreach my $node (@$nodelist) {
340 $get_node_data->($node);
347 # property: a config property you want to get, e.g., this is perfect to get
348 # the 'lock' entry of a guest _fast_ (>100 faster than manual parsing here)
349 # vmid: optipnal, if a valid is passed we only check that one, else return all
350 # NOTE: does *not* searches snapshot and PENDING entries sections!
351 sub get_guest_config_property
{
352 my ($property, $vmid) = @_;
354 die "property is required" if !defined($property);
356 my $bindata = pack "VZ*", $vmid // 0, $property;
357 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTY
, $bindata);
362 # $data must be a chronological descending ordered array of tasks
363 sub broadcast_tasklist
{
366 # the serialized list may not get bigger than 32kb (CFS_MAX_STATUS_SIZE
367 # from pmxcfs) - drop older items until we satisfy this constraint
368 my $size = length(encode_json
($data));
369 while ($size >= (32 * 1024)) {
371 $size = length(encode_json
($data));
375 &$ipcc_update_status("tasklist", $data);
381 my $tasklistcache = {};
386 my $kvstore = $versions->{kvstore
} || {};
388 my $nodelist = get_nodelist
();
391 foreach my $node (@$nodelist) {
392 next if $nodename && ($nodename ne $node);
394 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
395 my $cd = $tasklistcache->{$node};
396 if (!$cd || !$ver || !$cd->{version
} ||
397 ($cd->{version
} != $ver)) {
398 my $raw = &$ipcc_get_status("tasklist", $node) || '[]';
399 my $data = decode_json
($raw);
401 $cd = $tasklistcache->{$node} = {
405 } elsif ($cd && $cd->{data
}) {
406 push @$res, @{$cd->{data
}};
410 syslog
('err', $err) if $err;
417 my ($rrdid, $data) = @_;
420 &$ipcc_update_status("rrd/$rrdid", $data);
427 my $last_rrd_dump = 0;
428 my $last_rrd_data = "";
434 my $diff = $ctime - $last_rrd_dump;
436 return $last_rrd_data;
441 $raw = &$ipcc_send_rec(CFS_IPC_GET_RRD_DUMP
);
453 while ($raw =~ s/^(.*)\n//) {
454 my ($key, @ela) = split(/:/, $1);
456 next if !(scalar(@ela) > 1);
457 $res->{$key} = [ map { $_ eq 'U' ?
undef : $_ } @ela ];
461 $last_rrd_dump = $ctime;
462 $last_rrd_data = $res;
468 # a fast way to read files (avoid fuse overhead)
472 return &$ipcc_get_config($path);
475 sub get_cluster_log
{
476 my ($user, $max) = @_;
478 return &$ipcc_get_cluster_log($user, $max);
482 my ($userid, $token) = @_;
484 return &$ipcc_verify_token("$userid $token");
489 sub cfs_register_file
{
490 my ($filename, $parser, $writer) = @_;
492 $observed->{$filename} || die "unknown file '$filename'";
494 die "file '$filename' already registered" if $file_info->{$filename};
496 $file_info->{$filename} = {
502 my $ccache_read = sub {
503 my ($filename, $parser, $version) = @_;
505 $ccache->{$filename} = {} if !$ccache->{$filename};
507 my $ci = $ccache->{$filename};
509 if (!$ci->{version
} || !$version || $ci->{version
} != $version) {
510 # we always call the parser, even when the file does not exist
511 # (in that case $data is undef)
512 my $data = get_config
($filename);
513 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
514 $ci->{version
} = $version;
517 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
522 sub cfs_file_version
{
527 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
528 my ($type, $vmid) = ($1, $2);
529 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
530 $version = $vmlist->{ids
}->{$vmid}->{version
};
532 $infotag = "/$type/";
534 $infotag = $filename;
535 $version = $versions->{$filename};
538 my $info = $file_info->{$infotag} ||
539 die "unknown file type '$filename'\n";
541 return wantarray ?
($version, $info) : $version;
547 my ($version, $info) = cfs_file_version
($filename);
548 my $parser = $info->{parser
};
550 return &$ccache_read($filename, $parser, $version);
554 my ($filename, $data) = @_;
556 my ($version, $info) = cfs_file_version
($filename);
558 my $writer = $info->{writer
} || die "no writer defined";
560 my $fsname = "/etc/pve/$filename";
562 my $raw = &$writer($fsname, $data);
564 if (my $ci = $ccache->{$filename}) {
565 $ci->{version
} = undef;
568 PVE
::Tools
::file_set_contents
($fsname, $raw);
572 my ($lockid, $timeout, $code, @param) = @_;
574 my $prev_alarm = alarm(0); # suspend outer alarm early
579 # this timeout is for acquire the lock
580 $timeout = 10 if !$timeout;
582 my $filename = "$lockdir/$lockid";
589 die "pve cluster filesystem not online.\n";
592 my $timeout_err = sub { die "got lock request timeout\n"; };
593 local $SIG{ALRM
} = $timeout_err;
597 $got_lock = mkdir($filename);
598 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
602 $timeout_err->() if $timeout <= 0;
604 print STDERR
"trying to acquire cfs lock '$lockid' ...\n";
605 utime (0, 0, $filename); # cfs unlock request
609 # fixed command timeout: cfs locks have a timeout of 120
610 # using 60 gives us another 60 seconds to abort the task
611 local $SIG{ALRM
} = sub { die "got lock timeout - aborting command\n"; };
614 cfs_update
(); # make sure we read latest versions inside code()
616 $res = &$code(@param);
623 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum
(1);
625 rmdir $filename if $got_lock; # if we held the lock always unlock again
630 if (ref($err) eq 'PVE::Exception') {
631 # re-raise defined exceptions
634 # add lock info for plain errors
635 $@ = "error during cfs-locked '$lockid' operation: $err";
646 my ($filename, $timeout, $code, @param) = @_;
648 my $info = $observed->{$filename} || die "unknown file '$filename'";
650 my $lockid = "file-$filename";
651 $lockid =~ s/[.\/]/_
/g
;
653 &$cfs_lock($lockid, $timeout, $code, @param);
656 sub cfs_lock_storage
{
657 my ($storeid, $timeout, $code, @param) = @_;
659 my $lockid = "storage-$storeid";
661 &$cfs_lock($lockid, $timeout, $code, @param);
664 sub cfs_lock_domain
{
665 my ($domainname, $timeout, $code, @param) = @_;
667 my $lockid = "domain-$domainname";
669 &$cfs_lock($lockid, $timeout, $code, @param);
673 my ($account, $timeout, $code, @param) = @_;
675 my $lockid = "acme-$account";
677 &$cfs_lock($lockid, $timeout, $code, @param);
680 sub cfs_lock_authkey
{
681 my ($timeout, $code, @param) = @_;
683 $cfs_lock->('authkey', $timeout, $code, @param);
686 sub cfs_lock_firewall
{
687 my ($scope, $timeout, $code, @param) = @_;
689 my $lockid = "firewall-$scope";
691 $cfs_lock->($lockid, $timeout, $code, @param);
709 my ($priority, $ident, $msg) = @_;
711 if (my $tmp = $log_levels->{$priority}) {
715 die "need numeric log priority" if $priority !~ /^\d+$/;
717 my $tag = PVE
::SafeSyslog
::tag
();
719 $msg = "empty message" if !$msg;
721 $ident = "" if !$ident;
722 $ident = encode
("ascii", $ident,
723 sub { sprintf "\\u%04x", shift });
725 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
728 syslog
($priority, "<%s> %s", $ident, $ascii);
730 syslog
($priority, "%s", $ascii);
733 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
735 syslog
("err", "writing cluster log failed: $@") if $@;
738 sub check_vmid_unused
{
739 my ($vmid, $noerr) = @_;
741 my $vmlist = get_vmlist
();
743 my $d = $vmlist->{ids
}->{$vmid};
744 return 1 if !defined($d);
746 return undef if $noerr;
748 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
749 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
752 sub check_node_exists
{
753 my ($nodename, $noerr) = @_;
755 my $nodelist = $clinfo->{nodelist
};
756 return 1 if $nodelist && $nodelist->{$nodename};
758 return undef if $noerr;
760 die "no such cluster node '$nodename'\n";
763 # this is also used to get the IP of the local node
765 my ($nodename, $noerr) = @_;
767 my $nodelist = $clinfo->{nodelist
};
768 if ($nodelist && $nodelist->{$nodename}) {
769 if (my $ip = $nodelist->{$nodename}->{ip
}) {
770 return $ip if !wantarray;
771 my $family = $nodelist->{$nodename}->{address_family
};
773 $nodelist->{$nodename}->{address_family
} =
775 PVE
::Tools
::get_host_address_family
($ip);
777 return wantarray ?
($ip, $family) : $ip;
781 # fallback: try to get IP by other means
782 return PVE
::Network
::get_ip_from_hostname
($nodename, $noerr);
785 sub get_node_fingerprint
{
788 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
789 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
791 $cert_path = $custom_cert_path if -f
$custom_cert_path;
793 return PVE
::Certificate
::get_certificate_fingerprint
($cert_path);
796 # bash completion helpers
798 sub complete_next_vmid
{
800 my $vmlist = get_vmlist
() || {};
801 my $idlist = $vmlist->{ids
} || {};
803 for (my $i = 100; $i < 10000; $i++) {
804 return [$i] if !defined($idlist->{$i});
812 my $vmlist = get_vmlist
();
813 my $ids = $vmlist->{ids
} || {};
815 return [ keys %$ids ];
818 sub complete_local_vmid
{
820 my $vmlist = get_vmlist
();
821 my $ids = $vmlist->{ids
} || {};
823 my $nodename = PVE
::INotify
::nodename
();
826 foreach my $vmid (keys %$ids) {
827 my $d = $ids->{$vmid};
828 next if !$d->{node
} || $d->{node
} ne $nodename;
835 sub complete_migration_target
{
839 my $nodename = PVE
::INotify
::nodename
();
841 my $nodelist = get_nodelist
();
842 foreach my $node (@$nodelist) {
843 next if $node eq $nodename;
851 # NOTE: filesystem must be offline here, no DB changes allowed
852 sub cfs_backup_database
{
856 my $backup_fn = "$dbbackupdir/config-$ctime.sql.gz";
858 print "backup old database to '$backup_fn'\n";
860 my $cmd = [ ['sqlite3', $dbfile, '.dump'], ['gzip', '-', \
">${backup_fn}"] ];
861 run_command
($cmd, 'errmsg' => "cannot backup old database\n");
863 my $maxfiles = 10; # purge older backup
864 my $backups = [ sort { $b cmp $a } <$dbbackupdir/config-*.sql
.gz
> ];
866 if ((my $count = scalar(@$backups)) > $maxfiles) {
867 foreach my $f (@$backups[$maxfiles..$count-1]) {
868 next if $f !~ m/^(\S+)$/; # untaint
869 print "delete old backup '$1'\n";