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 'sdn/subnets.cfg' => 1,
74 'virtual-guest/cpu-models.conf' => 1,
77 sub prepare_observed_file_basedirs
{
79 if (!check_cfs_is_mounted
(1)) {
80 warn "pmxcfs isn't mounted (/etc/pve), chickening out..\n";
84 for my $f (sort keys %$observed) {
85 next if $f !~ m!^(.*)/[^/]+$!;
86 my $dir = "$basedir/$1";
87 next if -e
$dir; # can also be a link, so just use -e xist check
88 print "creating directory '$dir' for observerd files\n";
101 sub check_cfs_quorum
{
104 # note: -w filename always return 1 for root, so wee need
105 # to use File::lstat here
106 my $st = File
::stat::lstat("$basedir/local");
107 my $quorate = ($st && (($st->mode & 0200) != 0));
109 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
114 sub check_cfs_is_mounted
{
117 my $res = -l
"$basedir/local";
119 die "pve configuration filesystem not mounted\n"
129 my $ipcc_send_rec = sub {
130 my ($msgid, $data) = @_;
132 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
134 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
139 my $ipcc_send_rec_json = sub {
140 my ($msgid, $data) = @_;
142 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
144 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
146 return decode_json
($res);
149 my $ipcc_get_config = sub {
152 my $bindata = pack "Z*", $path;
153 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_CONFIG
, $bindata);
154 if (!defined($res)) {
156 return undef if $! == ENOENT
;
165 my $ipcc_get_status = sub {
166 my ($name, $nodename) = @_;
168 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
169 return PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_GET_STATUS
, $bindata);
172 my $ipcc_remove_status = sub {
174 # we just omit the data payload, pmxcfs takes this as hint and removes this
175 # key from the status hashtable
176 my $bindata = pack "Z[256]", $name;
177 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
180 my $ipcc_update_status = sub {
181 my ($name, $data) = @_;
183 my $raw = ref($data) ? encode_json
($data) : $data;
185 my $bindata = pack "Z[256]Z*", $name, $raw;
187 return &$ipcc_send_rec(CFS_IPC_SET_STATUS
, $bindata);
191 my ($priority, $ident, $tag, $msg) = @_;
193 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
194 bytes
::length($tag) + 1, $ident, $tag, $msg;
196 return &$ipcc_send_rec(CFS_IPC_LOG_CLUSTER_MSG
, $bindata);
199 my $ipcc_get_cluster_log = sub {
200 my ($user, $max) = @_;
202 $max = 0 if !defined($max);
204 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
205 return &$ipcc_send_rec(CFS_IPC_GET_CLUSTER_LOG
, $bindata);
208 my $ipcc_verify_token = sub {
209 my ($full_token) = @_;
211 my $bindata = pack "Z*", $full_token;
212 my $res = PVE
::IPCC
::ipcc_send_rec
(CFS_IPC_VERIFY_TOKEN
, $bindata);
215 return 0 if $! == ENOENT
;
225 my $res = &$ipcc_send_rec_json(CFS_IPC_GET_FS_VERSION
);
226 die "no starttime\n" if !$res->{starttime
};
228 if (!$res->{starttime
} || !$versions->{starttime
} ||
229 $res->{starttime
} != $versions->{starttime
}) {
230 #print "detected changed starttime\n";
249 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
250 #warn "detected new clinfo\n";
251 $clinfo = &$ipcc_send_rec_json(CFS_IPC_GET_CLUSTER_INFO
);
262 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
263 #warn "detected new vmlist1\n";
264 $vmlist = &$ipcc_send_rec_json(CFS_IPC_GET_GUEST_LIST
);
284 return $clinfo->{nodelist
};
288 my $nodelist = $clinfo->{nodelist
};
290 my $nodename = PVE
::INotify
::nodename
();
292 if (!$nodelist || !$nodelist->{$nodename}) {
293 return [ $nodename ];
296 return [ keys %$nodelist ];
299 # only stored in a in-memory hashtable inside pmxcfs, local data is gone after
300 # a restart (of pmxcfs or the node), peer data is still available then
301 # best used for status data, like running (ceph) services, package versions, ...
302 sub broadcast_node_kv
{
303 my ($key, $data) = @_;
305 if (!defined($data)) {
307 $ipcc_remove_status->("kv/$key");
310 die "cannot send a reference\n" if ref($data);
311 my $size = length($data);
312 die "data for '$key' too big\n" if $size >= (32 * 1024); # limit from pmxfs
315 $ipcc_update_status->("kv/$key", $data);
322 # nodename is optional
324 my ($key, $nodename) = @_;
327 my $get_node_data = sub {
329 my $raw = $ipcc_get_status->("kv/$key", $node);
330 $res->{$node} = unpack("Z*", $raw) if $raw;
334 $get_node_data->($nodename);
336 my $nodelist = get_nodelist
();
338 foreach my $node (@$nodelist) {
339 $get_node_data->($node);
346 # property: a config property you want to get, e.g., this is perfect to get
347 # the 'lock' entry of a guest _fast_ (>100 faster than manual parsing here)
348 # vmid: optipnal, if a valid is passed we only check that one, else return all
349 # NOTE: does *not* searches snapshot and PENDING entries sections!
350 sub get_guest_config_property
{
351 my ($property, $vmid) = @_;
353 die "property is required" if !defined($property);
355 my $bindata = pack "VZ*", $vmid // 0, $property;
356 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTY
, $bindata);
361 # $data must be a chronological descending ordered array of tasks
362 sub broadcast_tasklist
{
365 # the serialized list may not get bigger than 32kb (CFS_MAX_STATUS_SIZE
366 # from pmxcfs) - drop older items until we satisfy this constraint
367 my $size = length(encode_json
($data));
368 while ($size >= (32 * 1024)) {
370 $size = length(encode_json
($data));
374 &$ipcc_update_status("tasklist", $data);
380 my $tasklistcache = {};
385 my $kvstore = $versions->{kvstore
} || {};
387 my $nodelist = get_nodelist
();
390 foreach my $node (@$nodelist) {
391 next if $nodename && ($nodename ne $node);
393 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
394 my $cd = $tasklistcache->{$node};
395 if (!$cd || !$ver || !$cd->{version
} ||
396 ($cd->{version
} != $ver)) {
397 my $raw = &$ipcc_get_status("tasklist", $node) || '[]';
398 my $data = decode_json
($raw);
400 $cd = $tasklistcache->{$node} = {
404 } elsif ($cd && $cd->{data
}) {
405 push @$res, @{$cd->{data
}};
409 syslog
('err', $err) if $err;
416 my ($rrdid, $data) = @_;
419 &$ipcc_update_status("rrd/$rrdid", $data);
426 my $last_rrd_dump = 0;
427 my $last_rrd_data = "";
433 my $diff = $ctime - $last_rrd_dump;
435 return $last_rrd_data;
440 $raw = &$ipcc_send_rec(CFS_IPC_GET_RRD_DUMP
);
452 while ($raw =~ s/^(.*)\n//) {
453 my ($key, @ela) = split(/:/, $1);
455 next if !(scalar(@ela) > 1);
456 $res->{$key} = [ map { $_ eq 'U' ?
undef : $_ } @ela ];
460 $last_rrd_dump = $ctime;
461 $last_rrd_data = $res;
467 # a fast way to read files (avoid fuse overhead)
471 return &$ipcc_get_config($path);
474 sub get_cluster_log
{
475 my ($user, $max) = @_;
477 return &$ipcc_get_cluster_log($user, $max);
481 my ($userid, $token) = @_;
483 return &$ipcc_verify_token("$userid $token");
488 sub cfs_register_file
{
489 my ($filename, $parser, $writer) = @_;
491 $observed->{$filename} || die "unknown file '$filename'";
493 die "file '$filename' already registered" if $file_info->{$filename};
495 $file_info->{$filename} = {
501 my $ccache_read = sub {
502 my ($filename, $parser, $version) = @_;
504 $ccache->{$filename} = {} if !$ccache->{$filename};
506 my $ci = $ccache->{$filename};
508 if (!$ci->{version
} || !$version || $ci->{version
} != $version) {
509 # we always call the parser, even when the file does not exist
510 # (in that case $data is undef)
511 my $data = get_config
($filename);
512 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
513 $ci->{version
} = $version;
516 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
521 sub cfs_file_version
{
526 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
527 my ($type, $vmid) = ($1, $2);
528 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
529 $version = $vmlist->{ids
}->{$vmid}->{version
};
531 $infotag = "/$type/";
533 $infotag = $filename;
534 $version = $versions->{$filename};
537 my $info = $file_info->{$infotag} ||
538 die "unknown file type '$filename'\n";
540 return wantarray ?
($version, $info) : $version;
546 my ($version, $info) = cfs_file_version
($filename);
547 my $parser = $info->{parser
};
549 return &$ccache_read($filename, $parser, $version);
553 my ($filename, $data) = @_;
555 my ($version, $info) = cfs_file_version
($filename);
557 my $writer = $info->{writer
} || die "no writer defined";
559 my $fsname = "/etc/pve/$filename";
561 my $raw = &$writer($fsname, $data);
563 if (my $ci = $ccache->{$filename}) {
564 $ci->{version
} = undef;
567 PVE
::Tools
::file_set_contents
($fsname, $raw);
571 my ($lockid, $timeout, $code, @param) = @_;
573 my $prev_alarm = alarm(0); # suspend outer alarm early
578 # this timeout is for acquire the lock
579 $timeout = 10 if !$timeout;
581 my $filename = "$lockdir/$lockid";
588 die "pve cluster filesystem not online.\n";
591 my $timeout_err = sub { die "got lock request timeout\n"; };
592 local $SIG{ALRM
} = $timeout_err;
596 $got_lock = mkdir($filename);
597 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
601 $timeout_err->() if $timeout <= 0;
603 print STDERR
"trying to acquire cfs lock '$lockid' ...\n";
604 utime (0, 0, $filename); # cfs unlock request
608 # fixed command timeout: cfs locks have a timeout of 120
609 # using 60 gives us another 60 seconds to abort the task
610 local $SIG{ALRM
} = sub { die "got lock timeout - aborting command\n"; };
613 cfs_update
(); # make sure we read latest versions inside code()
615 $res = &$code(@param);
622 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum
(1);
624 rmdir $filename if $got_lock; # if we held the lock always unlock again
629 if (ref($err) eq 'PVE::Exception') {
630 # re-raise defined exceptions
633 # add lock info for plain errors
634 $@ = "error during cfs-locked '$lockid' operation: $err";
645 my ($filename, $timeout, $code, @param) = @_;
647 my $info = $observed->{$filename} || die "unknown file '$filename'";
649 my $lockid = "file-$filename";
650 $lockid =~ s/[.\/]/_
/g
;
652 &$cfs_lock($lockid, $timeout, $code, @param);
655 sub cfs_lock_storage
{
656 my ($storeid, $timeout, $code, @param) = @_;
658 my $lockid = "storage-$storeid";
660 &$cfs_lock($lockid, $timeout, $code, @param);
663 sub cfs_lock_domain
{
664 my ($domainname, $timeout, $code, @param) = @_;
666 my $lockid = "domain-$domainname";
668 &$cfs_lock($lockid, $timeout, $code, @param);
672 my ($account, $timeout, $code, @param) = @_;
674 my $lockid = "acme-$account";
676 &$cfs_lock($lockid, $timeout, $code, @param);
679 sub cfs_lock_authkey
{
680 my ($timeout, $code, @param) = @_;
682 $cfs_lock->('authkey', $timeout, $code, @param);
685 sub cfs_lock_firewall
{
686 my ($scope, $timeout, $code, @param) = @_;
688 my $lockid = "firewall-$scope";
690 $cfs_lock->($lockid, $timeout, $code, @param);
708 my ($priority, $ident, $msg) = @_;
710 if (my $tmp = $log_levels->{$priority}) {
714 die "need numeric log priority" if $priority !~ /^\d+$/;
716 my $tag = PVE
::SafeSyslog
::tag
();
718 $msg = "empty message" if !$msg;
720 $ident = "" if !$ident;
721 $ident = encode
("ascii", $ident,
722 sub { sprintf "\\u%04x", shift });
724 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
727 syslog
($priority, "<%s> %s", $ident, $ascii);
729 syslog
($priority, "%s", $ascii);
732 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
734 syslog
("err", "writing cluster log failed: $@") if $@;
737 sub check_vmid_unused
{
738 my ($vmid, $noerr) = @_;
740 my $vmlist = get_vmlist
();
742 my $d = $vmlist->{ids
}->{$vmid};
743 return 1 if !defined($d);
745 return undef if $noerr;
747 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
748 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
751 sub check_node_exists
{
752 my ($nodename, $noerr) = @_;
754 my $nodelist = $clinfo->{nodelist
};
755 return 1 if $nodelist && $nodelist->{$nodename};
757 return undef if $noerr;
759 die "no such cluster node '$nodename'\n";
762 # this is also used to get the IP of the local node
764 my ($nodename, $noerr) = @_;
766 my $nodelist = $clinfo->{nodelist
};
767 if ($nodelist && $nodelist->{$nodename}) {
768 if (my $ip = $nodelist->{$nodename}->{ip
}) {
769 return $ip if !wantarray;
770 my $family = $nodelist->{$nodename}->{address_family
};
772 $nodelist->{$nodename}->{address_family
} =
774 PVE
::Tools
::get_host_address_family
($ip);
776 return wantarray ?
($ip, $family) : $ip;
780 # fallback: try to get IP by other means
781 return PVE
::Network
::get_ip_from_hostname
($nodename, $noerr);
784 sub get_node_fingerprint
{
787 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
788 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
790 $cert_path = $custom_cert_path if -f
$custom_cert_path;
792 return PVE
::Certificate
::get_certificate_fingerprint
($cert_path);
795 # bash completion helpers
797 sub complete_next_vmid
{
799 my $vmlist = get_vmlist
() || {};
800 my $idlist = $vmlist->{ids
} || {};
802 for (my $i = 100; $i < 10000; $i++) {
803 return [$i] if !defined($idlist->{$i});
811 my $vmlist = get_vmlist
();
812 my $ids = $vmlist->{ids
} || {};
814 return [ keys %$ids ];
817 sub complete_local_vmid
{
819 my $vmlist = get_vmlist
();
820 my $ids = $vmlist->{ids
} || {};
822 my $nodename = PVE
::INotify
::nodename
();
825 foreach my $vmid (keys %$ids) {
826 my $d = $ids->{$vmid};
827 next if !$d->{node
} || $d->{node
} ne $nodename;
834 sub complete_migration_target
{
838 my $nodename = PVE
::INotify
::nodename
();
840 my $nodelist = get_nodelist
();
841 foreach my $node (@$nodelist) {
842 next if $node eq $nodename;
850 # NOTE: filesystem must be offline here, no DB changes allowed
851 sub cfs_backup_database
{
855 my $backup_fn = "$dbbackupdir/config-$ctime.sql.gz";
857 print "backup old database to '$backup_fn'\n";
859 my $cmd = [ ['sqlite3', $dbfile, '.dump'], ['gzip', '-', \
">${backup_fn}"] ];
860 run_command
($cmd, 'errmsg' => "cannot backup old database\n");
862 my $maxfiles = 10; # purge older backup
863 my $backups = [ sort { $b cmp $a } <$dbbackupdir/config-*.sql
.gz
> ];
865 if ((my $count = scalar(@$backups)) > $maxfiles) {
866 foreach my $f (@$backups[$maxfiles..$count-1]) {
867 next if $f !~ m/^(\S+)$/; # untaint
868 print "delete old backup '$1'\n";