Blame SOURCES/bz1872754-pgsqlms-new-ra.patch

27b8ba
diff --color -uNr a/doc/man/Makefile.am b/doc/man/Makefile.am
27b8ba
--- a/doc/man/Makefile.am	2021-04-12 12:51:56.831835953 +0200
27b8ba
+++ b/doc/man/Makefile.am	2021-04-13 13:38:14.198361848 +0200
27b8ba
@@ -154,6 +154,7 @@
27b8ba
                           ocf_heartbeat_ovsmonitor.7 \
27b8ba
                           ocf_heartbeat_pgagent.7 \
27b8ba
                           ocf_heartbeat_pgsql.7 \
27b8ba
+                          ocf_heartbeat_pgsqlms.7 \
27b8ba
                           ocf_heartbeat_pingd.7 \
27b8ba
                           ocf_heartbeat_podman.7 \
27b8ba
                           ocf_heartbeat_portblock.7 \
27b8ba
diff --color -uNr a/heartbeat/Makefile.am b/heartbeat/Makefile.am
27b8ba
--- a/heartbeat/Makefile.am	2021-04-12 12:51:56.831835953 +0200
27b8ba
+++ b/heartbeat/Makefile.am	2021-04-13 13:37:45.741292178 +0200
27b8ba
@@ -149,6 +149,7 @@
27b8ba
 			ovsmonitor		\
27b8ba
 			pgagent			\
27b8ba
 			pgsql			\
27b8ba
+			pgsqlms			\
27b8ba
 			pingd			\
27b8ba
 			podman			\
27b8ba
 			portblock		\
27b8ba
@@ -209,7 +210,10 @@
27b8ba
 			  mysql-common.sh	\
27b8ba
 			  nfsserver-redhat.sh	\
27b8ba
 			  findif.sh		\
27b8ba
-			  ocf.py
27b8ba
+			  ocf.py		\
27b8ba
+			  OCF_Directories.pm	\
27b8ba
+			  OCF_Functions.pm	\
27b8ba
+			  OCF_ReturnCodes.pm
27b8ba
 
27b8ba
 # Legacy locations
27b8ba
 hbdir			= $(sysconfdir)/ha.d
27b8ba
diff --color -uNr a/heartbeat/OCF_Directories.pm b/heartbeat/OCF_Directories.pm
27b8ba
--- a/heartbeat/OCF_Directories.pm	1970-01-01 01:00:00.000000000 +0100
27b8ba
+++ b/heartbeat/OCF_Directories.pm	2021-04-13 13:37:35.621267404 +0200
27b8ba
@@ -0,0 +1,139 @@
27b8ba
+#!/usr/bin/perl
27b8ba
+# This program is open source, licensed under the PostgreSQL License.
27b8ba
+# For license terms, see the LICENSE file.
27b8ba
+#
27b8ba
+# Copyright (C) 2016-2020: Jehan-Guillaume de Rorthais and Mael Rimbault
27b8ba
+
27b8ba
+=head1 NAME
27b8ba
+
27b8ba
+OCF_Directories - Binaries and binary options for use in Resource Agents
27b8ba
+
27b8ba
+=head1 SYNOPSIS
27b8ba
+
27b8ba
+  use FindBin;
27b8ba
+  use lib "$FindBin::RealBin/../../lib/heartbeat/";
27b8ba
+  
27b8ba
+  use OCF_Directories;
27b8ba
+
27b8ba
+=head1 DESCRIPTION
27b8ba
+
27b8ba
+This module has been ported from the ocf-directories shell script of the
27b8ba
+resource-agents project. See L<https://github.com/ClusterLabs/resource-agents/>.
27b8ba
+
27b8ba
+=head1 VARIABLES
27b8ba
+
27b8ba
+Here are the variables exported by this module:
27b8ba
+
27b8ba
+=over
27b8ba
+
27b8ba
+=item $INITDIR
27b8ba
+
27b8ba
+=item $HA_DIR
27b8ba
+
27b8ba
+=item $HA_RCDIR
27b8ba
+
27b8ba
+=item $HA_CONFDIR
27b8ba
+
27b8ba
+=item $HA_CF
27b8ba
+
27b8ba
+=item $HA_VARLIB
27b8ba
+
27b8ba
+=item $HA_RSCTMP
27b8ba
+
27b8ba
+=item $HA_RSCTMP_OLD
27b8ba
+
27b8ba
+=item $HA_FIFO
27b8ba
+
27b8ba
+=item $HA_BIN
27b8ba
+
27b8ba
+=item $HA_SBIN_DIR
27b8ba
+
27b8ba
+=item $HA_DATEFMT
27b8ba
+
27b8ba
+=item $HA_DEBUGLOG
27b8ba
+
27b8ba
+=item $HA_RESOURCEDIR
27b8ba
+
27b8ba
+=item $HA_DOCDIR
27b8ba
+
27b8ba
+=item $__SCRIPT_NAME
27b8ba
+
27b8ba
+=item $HA_VARRUN
27b8ba
+
27b8ba
+=item $HA_VARLOCK
27b8ba
+
27b8ba
+=item $ocf_prefix
27b8ba
+
27b8ba
+=item $ocf_exec_prefix
27b8ba
+
27b8ba
+=back
27b8ba
+
27b8ba
+=cut
27b8ba
+
27b8ba
+package OCF_Directories;
27b8ba
+
27b8ba
+use strict;
27b8ba
+use warnings;
27b8ba
+use 5.008;
27b8ba
+use File::Basename;
27b8ba
+
27b8ba
+BEGIN {
27b8ba
+    use Exporter;
27b8ba
+
27b8ba
+
27b8ba
+    our $VERSION   = 'v2.3.0';
27b8ba
+    our @ISA       = ('Exporter');
27b8ba
+    our @EXPORT    = qw(
27b8ba
+        $INITDIR
27b8ba
+        $HA_DIR
27b8ba
+        $HA_RCDIR
27b8ba
+        $HA_CONFDIR
27b8ba
+        $HA_CF
27b8ba
+        $HA_VARLIB
27b8ba
+        $HA_RSCTMP
27b8ba
+        $HA_RSCTMP_OLD
27b8ba
+        $HA_FIFO
27b8ba
+        $HA_BIN
27b8ba
+        $HA_SBIN_DIR
27b8ba
+        $HA_DATEFMT
27b8ba
+        $HA_DEBUGLOG
27b8ba
+        $HA_RESOURCEDIR
27b8ba
+        $HA_DOCDIR
27b8ba
+        $__SCRIPT_NAME
27b8ba
+        $HA_VARRUN
27b8ba
+        $HA_VARLOCK
27b8ba
+        $ocf_prefix
27b8ba
+        $ocf_exec_prefix
27b8ba
+    );
27b8ba
+    our @EXPORT_OK = ( @EXPORT );
27b8ba
+}
27b8ba
+
27b8ba
+our $INITDIR         = ( $ENV{'INITDIR'}       || '/etc/init.d' );
27b8ba
+our $HA_DIR          = ( $ENV{'HA_DIR'}        || '/etc/ha.d' );
27b8ba
+our $HA_RCDIR        = ( $ENV{'HA_RCDIR'}      || '/etc/ha.d/rc.d' );
27b8ba
+our $HA_CONFDIR      = ( $ENV{'HA_CONFDIR'}    || '/etc/ha.d/conf' );
27b8ba
+our $HA_CF           = ( $ENV{'HA_CF'}         || '/etc/ha.d/ha.cf' );
27b8ba
+our $HA_VARLIB       = ( $ENV{'HA_VARLIB'}     || '/var/lib/heartbeat' );
27b8ba
+our $HA_RSCTMP       = ( $ENV{'HA_RSCTMP'}     || '/run/resource-agents' );
27b8ba
+our $HA_RSCTMP_OLD   = ( $ENV{'HA_RSCTMP_OLD'} || '/var/run/heartbeat/rsctmp' );
27b8ba
+our $HA_FIFO         = ( $ENV{'HA_FIFO'}       || '/var/lib/heartbeat/fifo' );
27b8ba
+our $HA_BIN          = ( $ENV{'HA_BIN'}        || '/usr/libexec/heartbeat' );
27b8ba
+our $HA_SBIN_DIR     = ( $ENV{'HA_SBIN_DIR'}   || '/usr/sbin' );
27b8ba
+our $HA_DATEFMT      = ( $ENV{'HA_DATEFMT'}    || '%b %d %T ' );
27b8ba
+our $HA_DEBUGLOG     = ( $ENV{'HA_DEBUGLOG'}   || '/dev/null' );
27b8ba
+our $HA_RESOURCEDIR  = ( $ENV{'HA_RESOURCEDIR'}|| '/etc/ha.d/resource.d' );
27b8ba
+our $HA_DOCDIR       = ( $ENV{'HA_DOCDIR'}     || '/usr/share/doc/heartbeat' );
27b8ba
+our $__SCRIPT_NAME   = ( $ENV{'__SCRIPT_NAME'} || fileparse($0) );
27b8ba
+our $HA_VARRUN       = ( $ENV{'HA_VARRUN'}     || '/var/run' );
27b8ba
+our $HA_VARLOCK      = ( $ENV{'HA_VARLOCK'}    || '/var/lock/subsys' );
27b8ba
+our $ocf_prefix      = '/usr';
27b8ba
+our $ocf_exec_prefix = '/usr';
27b8ba
+
27b8ba
+1;
27b8ba
+
27b8ba
+=head1 COPYRIGHT AND LICENSE
27b8ba
+
27b8ba
+Copyright (C) 2016: Jehan-Guillaume de Rorthais and Mael Rimbault.
27b8ba
+
27b8ba
+Licensed under the PostgreSQL License.
27b8ba
+
27b8ba
diff --color -uNr a/heartbeat/OCF_Functions.pm b/heartbeat/OCF_Functions.pm
27b8ba
--- a/heartbeat/OCF_Functions.pm	1970-01-01 01:00:00.000000000 +0100
27b8ba
+++ b/heartbeat/OCF_Functions.pm	2021-04-13 13:37:35.621267404 +0200
27b8ba
@@ -0,0 +1,631 @@
27b8ba
+#!/usr/bin/perl
27b8ba
+# This program is open source, licensed under the PostgreSQL License.
27b8ba
+# For license terms, see the LICENSE file.
27b8ba
+#
27b8ba
+# Copyright (C) 2016-2020: Jehan-Guillaume de Rorthais and Mael Rimbault
27b8ba
+
27b8ba
+=head1 NAME
27b8ba
+
27b8ba
+OCF_Functions - helper subroutines for OCF agent
27b8ba
+
27b8ba
+=head1 SYNOPSIS
27b8ba
+
27b8ba
+  use FindBin;
27b8ba
+  use lib "$FindBin::RealBin/../../lib/heartbeat/";
27b8ba
+  
27b8ba
+  use OCF_Functions;
27b8ba
+
27b8ba
+=head1 DESCRIPTION
27b8ba
+
27b8ba
+This module has been ported from the ocf-shellfuncs shell script of the
27b8ba
+resource-agents project. See L<https://github.com/ClusterLabs/resource-agents/>.
27b8ba
+
27b8ba
+=head1 VARIABLE
27b8ba
+
27b8ba
+The only variable exported by this module is C<__OCF_ACTION>.
27b8ba
+
27b8ba
+=head1 SUBROUTINES
27b8ba
+
27b8ba
+Here are the subroutines ported from ocf-shellfuncs and exported by this module:
27b8ba
+
27b8ba
+=over
27b8ba
+
27b8ba
+=item ha_debug
27b8ba
+
27b8ba
+=item ha_log
27b8ba
+
27b8ba
+=item hadate
27b8ba
+
27b8ba
+=item ocf_is_clone
27b8ba
+
27b8ba
+=item ocf_is_ms
27b8ba
+
27b8ba
+=item ocf_is_probe
27b8ba
+
27b8ba
+=item ocf_is_root
27b8ba
+
27b8ba
+=item ocf_is_true
27b8ba
+
27b8ba
+=item ocf_is_ver
27b8ba
+
27b8ba
+=item ocf_local_nodename
27b8ba
+
27b8ba
+=item ocf_log
27b8ba
+
27b8ba
+=item ocf_exit_reason
27b8ba
+
27b8ba
+=item ocf_maybe_random
27b8ba
+
27b8ba
+=item ocf_ver2num
27b8ba
+
27b8ba
+=item ocf_ver_complete_level
27b8ba
+
27b8ba
+=item ocf_ver_level
27b8ba
+
27b8ba
+=item ocf_version_cmp
27b8ba
+
27b8ba
+=item set_logtag
27b8ba
+
27b8ba
+=back
27b8ba
+
27b8ba
+Here are the subroutines only existing in the perl module but not in the
27b8ba
+ocf-shellfuncs script:
27b8ba
+
27b8ba
+=over
27b8ba
+
27b8ba
+=item ocf_notify_env
27b8ba
+
27b8ba
+=back
27b8ba
+
27b8ba
+=cut
27b8ba
+
27b8ba
+package OCF_Functions;
27b8ba
+
27b8ba
+use strict;
27b8ba
+use warnings;
27b8ba
+use 5.008;
27b8ba
+use POSIX qw( strftime setlocale LC_ALL );
27b8ba
+use English;
27b8ba
+
27b8ba
+use FindBin;
27b8ba
+use lib "$FindBin::RealBin/../../lib/heartbeat/";
27b8ba
+
27b8ba
+use OCF_ReturnCodes;
27b8ba
+use OCF_Directories;
27b8ba
+
27b8ba
+BEGIN {
27b8ba
+    use Exporter;
27b8ba
+
27b8ba
+    our $VERSION   = 'v2.3.0';
27b8ba
+    our @ISA       = ('Exporter');
27b8ba
+    our @EXPORT    = qw(
27b8ba
+        $__OCF_ACTION
27b8ba
+        ocf_is_root
27b8ba
+        ocf_maybe_random
27b8ba
+        ocf_is_true
27b8ba
+        hadate
27b8ba
+        set_logtag
27b8ba
+        ha_log
27b8ba
+        ha_debug
27b8ba
+        ocf_log
27b8ba
+        ocf_exit_reason
27b8ba
+        ocf_is_probe
27b8ba
+        ocf_is_clone
27b8ba
+        ocf_is_ms
27b8ba
+        ocf_is_ver
27b8ba
+        ocf_ver2num
27b8ba
+        ocf_ver_level
27b8ba
+        ocf_ver_complete_level
27b8ba
+        ocf_version_cmp
27b8ba
+        ocf_local_nodename
27b8ba
+        ocf_notify_env
27b8ba
+    );
27b8ba
+    our @EXPORT_OK = ( @EXPORT );
27b8ba
+}
27b8ba
+
27b8ba
+our $__OCF_ACTION;
27b8ba
+
27b8ba
+sub ocf_is_root {
27b8ba
+    return $EUID == 0;
27b8ba
+}
27b8ba
+
27b8ba
+sub ocf_maybe_random {
27b8ba
+    return int( rand( 32767 ) );
27b8ba
+}
27b8ba
+
27b8ba
+sub ocf_is_true {
27b8ba
+    my $v = shift;
27b8ba
+    return ( defined $v and $v =~ /^(?:yes|true|1|YES|TRUE|ja|on|ON)$/ );
27b8ba
+}
27b8ba
+
27b8ba
+sub hadate {
27b8ba
+  return strftime( $HA_DATEFMT, localtime );
27b8ba
+}
27b8ba
+
27b8ba
+sub set_logtag {
27b8ba
+
27b8ba
+    return if defined $ENV{'HA_LOGTAG'} and $ENV{'HA_LOGTAG'} ne '';
27b8ba
+
27b8ba
+    if ( defined $ENV{'OCF_RESOURCE_INSTANCE'} and $ENV{'OCF_RESOURCE_INSTANCE'} ne '' ) {
27b8ba
+        $ENV{'HA_LOGTAG'} = "$__SCRIPT_NAME($ENV{'OCF_RESOURCE_INSTANCE'})[$PID]";
27b8ba
+    }
27b8ba
+    else {
27b8ba
+        $ENV{'HA_LOGTAG'}="${__SCRIPT_NAME}[$PID]";
27b8ba
+    }
27b8ba
+}
27b8ba
+
27b8ba
+sub __ha_log {
27b8ba
+    my $ignore_stderr = 0;
27b8ba
+    my $loglevel      = '';
27b8ba
+
27b8ba
+    if ( $_[0] eq '--ignore-stderr' ) {
27b8ba
+        $ignore_stderr = 1;
27b8ba
+        shift;
27b8ba
+    }
27b8ba
+
27b8ba
+    $ENV{'HA_LOGFACILITY'} = '' if not defined $ENV{'HA_LOGFACILITY'}
27b8ba
+        or $ENV{'HA_LOGFACILITY'} eq 'none';
27b8ba
+
27b8ba
+    # if we're connected to a tty, then output to stderr
27b8ba
+    if ( -t STDERR ) {
27b8ba
+        # FIXME
27b8ba
+        # T.N.: this was ported with the bug on $loglevel being empty
27b8ba
+        # and never set before the test here...
27b8ba
+        if ( defined $ENV{'HA_debug'}
27b8ba
+             and $ENV{'HA_debug'} == 0
27b8ba
+             and $loglevel eq 'debug'
27b8ba
+        ) {
27b8ba
+            return 0;
27b8ba
+        }
27b8ba
+        elsif ( $ignore_stderr ) {
27b8ba
+            # something already printed this error to stderr, so ignore
27b8ba
+            return 0;
27b8ba
+        }
27b8ba
+        if ( defined $ENV{'HA_LOGTAG'} and $ENV{'HA_LOGTAG'} ne '' ) {
27b8ba
+            printf STDERR "%s: %s\n", $ENV{'HA_LOGTAG'}, join ' ', @ARG;
27b8ba
+        }
27b8ba
+        else {
27b8ba
+            printf STDERR "%s\n", join ' ', @ARG;
27b8ba
+        }
27b8ba
+        return 0;
27b8ba
+    }
27b8ba
+
27b8ba
+    set_logtag();
27b8ba
+
27b8ba
+    if ( defined $ENV{'HA_LOGD'} and $ENV{'HA_LOGD'} eq 'yes' ) {
27b8ba
+        system 'ha_logger', '-t', $ENV{'HA_LOGTAG'}, @ARG;
27b8ba
+        return 0 if ( $? >> 8 ) == 0;
27b8ba
+    }
27b8ba
+
27b8ba
+    unless ( $ENV{'HA_LOGFACILITY'} eq '' ) {
27b8ba
+        # logging through syslog
27b8ba
+        # loglevel is unknown, use 'notice' for now
27b8ba
+        $loglevel = 'notice';
27b8ba
+        for ( "@ARG" ) {
27b8ba
+            if ( /ERROR/ ) {
27b8ba
+                $loglevel = 'err';
27b8ba
+            }
27b8ba
+            elsif ( /WARN/ ) {
27b8ba
+                $loglevel = 'warning';
27b8ba
+            }
27b8ba
+            elsif (/INFO|info/ ) {
27b8ba
+                $loglevel = 'info';
27b8ba
+            }
27b8ba
+        }
27b8ba
+
27b8ba
+        system 'logger', '-t', $ENV{'HA_LOGTAG'}, '-p',
27b8ba
+            "$ENV{'HA_LOGFACILITY'}.$loglevel", @ARG;
27b8ba
+    }
27b8ba
+
27b8ba
+    if ( defined $ENV{'HA_LOGFILE'} and $ENV{'HA_LOGFILE'} ne '' ) {
27b8ba
+        # appending to $HA_LOGFILE
27b8ba
+        open my $logfile, '>>', $ENV{'HA_LOGFILE'};
27b8ba
+        printf $logfile "%s:	%s %s\n", $ENV{'HA_LOGTAG'}, hadate(),
27b8ba
+            join (' ', @ARG);
27b8ba
+        close $logfile;
27b8ba
+    }
27b8ba
+
27b8ba
+    # appending to stderr
27b8ba
+    printf STDERR "%s %s\n", hadate(), join ' ', @ARG
27b8ba
+        if (not defined $ENV{'HA_LOGFACILITY'} or $ENV{'HA_LOGFACILITY'} eq '')
27b8ba
+            and (not defined $ENV{'HA_LOGFILE'} or $ENV{'HA_LOGFILE'} eq '' )
27b8ba
+            and not $ignore_stderr;
27b8ba
+
27b8ba
+    if ( defined $ENV{'HA_DEBUGLOG'} and $ENV{'HA_DEBUGLOG'} ne ''
27b8ba
+        and $ENV{'HA_LOGFILE'} ne $ENV{'HA_DEBUGLOG'}
27b8ba
+    ) {
27b8ba
+        # appending to $HA_DEBUGLOG
27b8ba
+        open my $logfile, '>>', $ENV{'HA_DEBUGLOG'};
27b8ba
+        printf $logfile "%s:	%s %s\n", $ENV{'HA_LOGTAG'}, hadate(),
27b8ba
+            join (' ', @ARG);
27b8ba
+        close $logfile;
27b8ba
+    }
27b8ba
+}
27b8ba
+
27b8ba
+sub ha_log {
27b8ba
+    return __ha_log( @ARG );
27b8ba
+}
27b8ba
+
27b8ba
+sub ha_debug {
27b8ba
+
27b8ba
+    return 0 if defined $ENV{'HA_debug'} and $ENV{'HA_debug'} == 0;
27b8ba
+
27b8ba
+    if ( -t STDERR ) {
27b8ba
+        if ( defined $ENV{'HA_LOGTAG'} and $ENV{'HA_LOGTAG'} ne '' ) {
27b8ba
+            printf STDERR "%s: %s\n", $ENV{'HA_LOGTAG'}, join ' ', @ARG;
27b8ba
+        }
27b8ba
+        else {
27b8ba
+            printf STDERR "%s\n", join ' ', @ARG;
27b8ba
+        }
27b8ba
+        
27b8ba
+        return 0;
27b8ba
+    }
27b8ba
+
27b8ba
+    set_logtag();
27b8ba
+
27b8ba
+    if ( defined $ENV{'HA_LOGD'} and $ENV{'HA_LOGD'} eq 'yes' ) {
27b8ba
+        system 'ha_logger', '-t', $ENV{'HA_LOGTAG'}, '-D', 'ha-debug', @ARG;
27b8ba
+        return 0 if ( $? >> 8 ) == 0;
27b8ba
+    }
27b8ba
+
27b8ba
+    $ENV{'HA_LOGFACILITY'} = '' if not defined $ENV{'HA_LOGFACILITY'}
27b8ba
+        or $ENV{'HA_LOGFACILITY'} eq 'none';
27b8ba
+
27b8ba
+    unless ( $ENV{'HA_LOGFACILITY'} eq '' ) {
27b8ba
+        # logging through syslog
27b8ba
+
27b8ba
+        system 'logger', '-t', $ENV{'HA_LOGTAG'}, '-p',
27b8ba
+            "$ENV{'HA_LOGFACILITY'}.debug", @ARG;
27b8ba
+    }
27b8ba
+
27b8ba
+    if ( defined $ENV{'HA_DEBUGLOG'} and -f $ENV{'HA_DEBUGLOG'} ) {
27b8ba
+        my $logfile;
27b8ba
+        # appending to $HA_DEBUGLOG
27b8ba
+        open $logfile, '>>', $ENV{'HA_DEBUGLOG'};
27b8ba
+        printf $logfile "%s:	%s %s\n", $ENV{'HA_LOGTAG'}, hadate(),
27b8ba
+            join (' ', @ARG);
27b8ba
+        close $logfile;
27b8ba
+    }
27b8ba
+
27b8ba
+    # appending to stderr
27b8ba
+    printf STDERR "%s: %s %s\n", $ENV{'HA_LOGTAG'}, hadate(), join ' ', @ARG
27b8ba
+        if (not defined $ENV{'HA_LOGFACILITY'} or $ENV{'HA_LOGFACILITY'} eq '')
27b8ba
+            and (not defined $ENV{'HA_DEBUGLOG'} or $ENV{'HA_DEBUGLOG'} eq '' );
27b8ba
+}
27b8ba
+
27b8ba
+#
27b8ba
+# ocf_log: log messages from the resource agent
27b8ba
+# This function is slightly different from its equivalent in ocf-shellfuncs.in
27b8ba
+# as it behaves like printf.
27b8ba
+# Arguments:
27b8ba
+#   * __OCF_PRIO: log level
27b8ba
+#   * __OCF_MSG:  printf-like format string
27b8ba
+#   * all other arguments are values for the printf-like format string
27b8ba
+#
27b8ba
+sub ocf_log {
27b8ba
+    my $__OCF_PRIO;
27b8ba
+    my $__OCF_MSG;
27b8ba
+
27b8ba
+    # TODO: Revisit and implement internally.
27b8ba
+    if ( scalar @ARG < 2 ) {
27b8ba
+        ocf_log ( 'err', "Not enough arguments [%d] to ocf_log", scalar @ARG );
27b8ba
+    }
27b8ba
+
27b8ba
+    $__OCF_PRIO = shift;
27b8ba
+    $__OCF_MSG  = shift;
27b8ba
+    $__OCF_MSG  = sprintf $__OCF_MSG, @ARG;
27b8ba
+
27b8ba
+    for ( $__OCF_PRIO ) {
27b8ba
+        if    ( /crit/  ) { $__OCF_PRIO = 'CRIT'    }
27b8ba
+        elsif ( /err/   ) { $__OCF_PRIO = 'ERROR'   }
27b8ba
+        elsif ( /warn/  ) { $__OCF_PRIO = 'WARNING' }
27b8ba
+        elsif ( /info/  ) { $__OCF_PRIO = 'INFO'    }
27b8ba
+        elsif ( /debug/ ) { $__OCF_PRIO = 'DEBUG'   }
27b8ba
+        else  { $__OCF_PRIO =~ tr/[a-z]/[A-Z]/ }
27b8ba
+    }
27b8ba
+
27b8ba
+    if ( $__OCF_PRIO eq 'DEBUG' ) {
27b8ba
+        ha_debug( "$__OCF_PRIO: $__OCF_MSG");
27b8ba
+    }
27b8ba
+    else {
27b8ba
+        ha_log( "$__OCF_PRIO: $__OCF_MSG");
27b8ba
+    }
27b8ba
+}
27b8ba
+
27b8ba
+
27b8ba
+#
27b8ba
+# ocf_exit_reason: print exit error string to stderr and log
27b8ba
+# Usage:           Allows the OCF script to provide a string
27b8ba
+#                  describing why the exit code was returned.
27b8ba
+# Arguments:       reason - required, The string that represents
27b8ba
+#                  why the error occured.
27b8ba
+#
27b8ba
+sub ocf_exit_reason {
27b8ba
+    my $cookie = $ENV{'OCF_EXIT_REASON_PREFIX'} || 'ocf-exit-reason:';
27b8ba
+    my $fmt;
27b8ba
+    my $msg;
27b8ba
+
27b8ba
+    # No argument is likely not intentional.
27b8ba
+    # Just one argument implies a printf format string of just "%s".
27b8ba
+    # "Least surprise" in case some interpolated string from variable
27b8ba
+    # expansion or other contains a percent sign.
27b8ba
+    # More than one argument: first argument is going to be the format string.
27b8ba
+    ocf_log ( 'err', 'Not enough arguments [%d] to ocf_exit_reason',
27b8ba
+        scalar @ARG ) if scalar @ARG < 1;
27b8ba
+
27b8ba
+    $fmt = shift;
27b8ba
+    $msg = sprintf $fmt, @ARG;
27b8ba
+
27b8ba
+    print STDERR "$cookie$msg\n";
27b8ba
+    __ha_log( '--ignore-stderr', "ERROR: $msg" );
27b8ba
+}
27b8ba
+
27b8ba
+# returns true if the CRM is currently running a probe. A probe is
27b8ba
+# defined as a monitor operation with a monitoring interval of zero.
27b8ba
+sub ocf_is_probe {
27b8ba
+    return ( $__OCF_ACTION eq 'monitor'
27b8ba
+        and $ENV{'OCF_RESKEY_CRM_meta_interval'} == 0 );
27b8ba
+}
27b8ba
+
27b8ba
+# returns true if the resource is configured as a clone. This is
27b8ba
+# defined as a resource where the clone-max meta attribute is present,
27b8ba
+# and set to greater than zero.
27b8ba
+sub ocf_is_clone {
27b8ba
+    return ( defined $ENV{'OCF_RESKEY_CRM_meta_clone_max'}
27b8ba
+        and $ENV{'OCF_RESKEY_CRM_meta_clone_max'} > 0 );
27b8ba
+}
27b8ba
+
27b8ba
+# returns true if the resource is configured as a multistate
27b8ba
+# (master/slave) resource. This is defined as a resource where the
27b8ba
+# master-max meta attribute is present, and set to greater than zero.
27b8ba
+sub ocf_is_ms {
27b8ba
+    return ( defined $ENV{'OCF_RESKEY_CRM_meta_master_max'}
27b8ba
+        and  $ENV{'OCF_RESKEY_CRM_meta_master_max'} > 0 );
27b8ba
+}
27b8ba
+
27b8ba
+# version check functions
27b8ba
+# allow . and - to delimit version numbers
27b8ba
+# max version number is 999
27b8ba
+# letters and such are effectively ignored
27b8ba
+#
27b8ba
+sub ocf_is_ver {
27b8ba
+    return $ARG[0] =~ /^[0-9][0-9.-]*[0-9]$/;
27b8ba
+}
27b8ba
+
27b8ba
+sub ocf_ver2num {
27b8ba
+    my $v = 0;
27b8ba
+    
27b8ba
+    $v = $v * 1000 + $1 while $ARG[0] =~ /(\d+)/g;
27b8ba
+
27b8ba
+    return $v;
27b8ba
+}
27b8ba
+
27b8ba
+sub ocf_ver_level {
27b8ba
+    my $v = () = $ARG[0] =~ /(\d+)/g;
27b8ba
+    return $v;
27b8ba
+}
27b8ba
+
27b8ba
+sub ocf_ver_complete_level {
27b8ba
+    my $ver   = shift;
27b8ba
+    my $level = shift;
27b8ba
+    my $i     = 0;
27b8ba
+
27b8ba
+    for ( my $i = 0; $i < $level; $i++ ) {
27b8ba
+        $ver .= "$ver.0";
27b8ba
+    }
27b8ba
+
27b8ba
+    return $ver;
27b8ba
+}
27b8ba
+
27b8ba
+# usage: ocf_version_cmp VER1 VER2
27b8ba
+#     version strings can contain digits, dots, and dashes
27b8ba
+#     must start and end with a digit
27b8ba
+# returns:
27b8ba
+#     0: VER1 smaller (older) than VER2
27b8ba
+#     1: versions equal
27b8ba
+#     2: VER1 greater (newer) than VER2
27b8ba
+#     3: bad format
27b8ba
+sub ocf_version_cmp {
27b8ba
+    my $v1 = shift;
27b8ba
+    my $v2 = shift;
27b8ba
+    my $v1_level;
27b8ba
+    my $v2_level;
27b8ba
+    my $level_diff;
27b8ba
+    
27b8ba
+    return 3 unless ocf_is_ver( $v1 );
27b8ba
+    return 3 unless ocf_is_ver( $v2 );
27b8ba
+
27b8ba
+    $v1_level = ocf_ver_level( $v1 );
27b8ba
+    $v2_level = ocf_ver_level( $v2 );
27b8ba
+
27b8ba
+    if ( $v1_level < $v2_level ) {
27b8ba
+        $level_diff = $v2_level - $v1_level;
27b8ba
+        $v1 = ocf_ver_complete_level( $v1, $level_diff );
27b8ba
+    }
27b8ba
+    elsif ( $v1_level > $v2_level ) {
27b8ba
+        $level_diff = $v1_level - $v2_level;
27b8ba
+        $v2 = ocf_ver_complete_level( $v2, $level_diff );
27b8ba
+    }
27b8ba
+
27b8ba
+    $v1 = ocf_ver2num( $v1 );
27b8ba
+    $v2 = ocf_ver2num( $v2 );
27b8ba
+
27b8ba
+    if    ( $v1 == $v2 ) { return 1; }
27b8ba
+    elsif ( $v1 < $v2  ) { return 0; }
27b8ba
+
27b8ba
+    return 2; # -1 would look funny in shell ;-) ( T.N. not in perl ;) )
27b8ba
+}
27b8ba
+
27b8ba
+sub ocf_local_nodename {
27b8ba
+    # use crm_node -n for pacemaker > 1.1.8
27b8ba
+    my $nodename;
27b8ba
+
27b8ba
+    qx{ which pacemakerd > /dev/null 2>&1 };
27b8ba
+    if ( $? == 0 ) {
27b8ba
+        my $version;
27b8ba
+        my $ret = qx{ pacemakerd -\$ };
27b8ba
+
27b8ba
+        $ret =~ /Pacemaker ([\d.]+)/;
27b8ba
+        $version = $1;
27b8ba
+
27b8ba
+        if ( ocf_version_cmp( $version, '1.1.8' ) == 2 ) {
27b8ba
+            qx{ which crm_node > /dev/null 2>&1 };
27b8ba
+            $nodename = qx{ crm_node -n } if $? == 0;
27b8ba
+        }
27b8ba
+    }
27b8ba
+    else {
27b8ba
+        # otherwise use uname -n
27b8ba
+        $nodename = qx { uname -n };
27b8ba
+    }
27b8ba
+
27b8ba
+    chomp $nodename;
27b8ba
+    return $nodename;
27b8ba
+}
27b8ba
+
27b8ba
+# Parse and returns the notify environment variables in a convenient structure
27b8ba
+# Returns undef if the action is not a notify
27b8ba
+# Returns undef if the resource is neither a clone or a multistate one
27b8ba
+sub ocf_notify_env {
27b8ba
+    my $i;
27b8ba
+    my %notify_env;
27b8ba
+
27b8ba
+    return undef unless $__OCF_ACTION eq 'notify';
27b8ba
+
27b8ba
+    return undef unless ocf_is_clone() or ocf_is_ms();
27b8ba
+
27b8ba
+    %notify_env = (
27b8ba
+        'type'       => $ENV{'OCF_RESKEY_CRM_meta_notify_type'}      || '',
27b8ba
+        'operation'  => $ENV{'OCF_RESKEY_CRM_meta_notify_operation'} || '',
27b8ba
+        'active'     => [ ],
27b8ba
+        'inactive'   => [ ],
27b8ba
+        'start'      => [ ],
27b8ba
+        'stop'       => [ ],
27b8ba
+    );
27b8ba
+
27b8ba
+    for my $action ( qw{ active start stop } ) {
27b8ba
+        next unless
27b8ba
+                defined $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_resource"}
27b8ba
+            and defined $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_uname"};
27b8ba
+
27b8ba
+        $i = 0;
27b8ba
+        $notify_env{ $action }[$i++]{'rsc'} = $_ foreach split /\s+/ =>
27b8ba
+            $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_resource"};
27b8ba
+
27b8ba
+        $i = 0;
27b8ba
+        $notify_env{ $action }[$i++]{'uname'} = $_ foreach split /\s+/ =>
27b8ba
+            $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_uname"};
27b8ba
+    }
27b8ba
+
27b8ba
+    # notify_nactive_uname doesn't exists. See:
27b8ba
+    # http://lists.clusterlabs.org/pipermail/developers/2017-January/000406.html
27b8ba
+    if ( defined $ENV{"OCF_RESKEY_CRM_meta_notify_inactive_resource"} ) {
27b8ba
+        $i = 0;
27b8ba
+        $notify_env{'inactive'}[$i++]{'rsc'} = $_ foreach split /\s+/ =>
27b8ba
+            $ENV{"OCF_RESKEY_CRM_meta_notify_inactive_resource"};
27b8ba
+    }
27b8ba
+
27b8ba
+    # exit if the resource is not a mutistate one
27b8ba
+    return %notify_env unless ocf_is_ms();
27b8ba
+
27b8ba
+    for my $action ( qw{ master slave promote demote } ) {
27b8ba
+        $notify_env{ $action } = [ ];
27b8ba
+
27b8ba
+        next unless
27b8ba
+                defined $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_resource"}
27b8ba
+            and defined $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_uname"};
27b8ba
+
27b8ba
+        $i = 0;
27b8ba
+        $notify_env{ $action }[$i++]{'rsc'} = $_ foreach split /\s+/ =>
27b8ba
+            $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_resource"};
27b8ba
+
27b8ba
+        $i = 0;
27b8ba
+        $notify_env{ $action }[$i++]{'uname'} = $_ foreach split /\s+/ =>
27b8ba
+            $ENV{"OCF_RESKEY_CRM_meta_notify_${action}_uname"};
27b8ba
+    }
27b8ba
+
27b8ba
+    # Fix active and inactive fields for Pacemaker version < 1.1.16
27b8ba
+    # ie. crm_feature_set < 3.0.11
27b8ba
+    # See http://lists.clusterlabs.org/pipermail/developers/2016-August/000265.html
27b8ba
+    # and git commit a6713c5d40327eff8549e7f596501ab1785b8765
27b8ba
+    if (
27b8ba
+        ocf_version_cmp( $ENV{"OCF_RESKEY_crm_feature_set"}, '3.0.11' ) == 0
27b8ba
+    ) {
27b8ba
+        $notify_env{ 'active' } = [
27b8ba
+            @{ $notify_env{ 'master' } },
27b8ba
+            @{ $notify_env{ 'slave' } }
27b8ba
+        ];
27b8ba
+    }
27b8ba
+
27b8ba
+    return %notify_env;
27b8ba
+}
27b8ba
+
27b8ba
+$__OCF_ACTION = $ARGV[0];
27b8ba
+
27b8ba
+# Return to sanity for the agents...
27b8ba
+
27b8ba
+undef $ENV{'LC_ALL'};
27b8ba
+$ENV{'LC_ALL'} = 'C';
27b8ba
+setlocale( LC_ALL, 'C' );
27b8ba
+undef $ENV{'LANG'};
27b8ba
+undef $ENV{'LANGUAGE'};
27b8ba
+
27b8ba
+$ENV{'OCF_ROOT'} = '/usr/lib/ocf'
27b8ba
+    unless defined $ENV{'OCF_ROOT'} and $ENV{'OCF_ROOT'} ne '';
27b8ba
+
27b8ba
+# old
27b8ba
+undef $ENV{'OCF_FUNCTIONS_DIR'}
27b8ba
+    if defined $ENV{'OCF_FUNCTIONS_DIR'}
27b8ba
+    and $ENV{'OCF_FUNCTIONS_DIR'} eq "$ENV{'OCF_ROOT'}/resource.d/heartbeat";
27b8ba
+
27b8ba
+# Define OCF_RESKEY_CRM_meta_interval in case it isn't already set,
27b8ba
+# to make sure that ocf_is_probe() always works
27b8ba
+$ENV{'OCF_RESKEY_CRM_meta_interval'} = 0
27b8ba
+    unless defined $ENV{'OCF_RESKEY_CRM_meta_interval'};
27b8ba
+
27b8ba
+# Strip the OCF_RESKEY_ prefix from this particular parameter
27b8ba
+unless ( defined $ENV{'$OCF_RESKEY_OCF_CHECK_LEVEL'}
27b8ba
+    and $ENV{'$OCF_RESKEY_OCF_CHECK_LEVEL'} ne ''
27b8ba
+) {
27b8ba
+    $ENV{'OCF_CHECK_LEVEL'} = $ENV{'$OCF_RESKEY_OCF_CHECK_LEVEL'};
27b8ba
+}
27b8ba
+else {
27b8ba
+    ENV{'OCF_CHECK_LEVEL'} = 0;
27b8ba
+}
27b8ba
+
27b8ba
+unless ( -d $ENV{'OCF_ROOT'} ) {
27b8ba
+    ha_log( "ERROR: OCF_ROOT points to non-directory $ENV{'OCF_ROOT'}." );
27b8ba
+    $! = $OCF_ERR_GENERIC;
27b8ba
+    die;
27b8ba
+}
27b8ba
+
27b8ba
+$ENV{'OCF_RESOURCE_TYPE'} = $__SCRIPT_NAME
27b8ba
+    unless defined $ENV{'OCF_RESOURCE_TYPE'}
27b8ba
+    and $ENV{'OCF_RESOURCE_TYPE'} ne '';
27b8ba
+
27b8ba
+unless ( defined $ENV{'OCF_RA_VERSION_MAJOR'}
27b8ba
+    and $ENV{'OCF_RA_VERSION_MAJOR'} ne ''
27b8ba
+) {
27b8ba
+    # We are being invoked as an init script.
27b8ba
+    # Fill in some things with reasonable values.
27b8ba
+    $ENV{'OCF_RESOURCE_INSTANCE'} = 'default';
27b8ba
+    return 1;
27b8ba
+}
27b8ba
+
27b8ba
+$ENV{'OCF_RESOURCE_INSTANCE'} = "undef" if $__OCF_ACTION eq 'meta-data';
27b8ba
+
27b8ba
+unless ( defined $ENV{'OCF_RESOURCE_INSTANCE'}
27b8ba
+    and $ENV{'OCF_RESOURCE_INSTANCE'} ne ''
27b8ba
+) {
27b8ba
+    ha_log( "ERROR: Need to tell us our resource instance name." );
27b8ba
+    $! = $OCF_ERR_ARGS;
27b8ba
+    die;
27b8ba
+}
27b8ba
+
27b8ba
+1;
27b8ba
+
27b8ba
+
27b8ba
+=head1 COPYRIGHT AND LICENSE
27b8ba
+
27b8ba
+Copyright (C) 2016: Jehan-Guillaume de Rorthais and Mael Rimbault.
27b8ba
+
27b8ba
+Licensed under the PostgreSQL License.
27b8ba
diff --color -uNr a/heartbeat/OCF_ReturnCodes.pm b/heartbeat/OCF_ReturnCodes.pm
27b8ba
--- a/heartbeat/OCF_ReturnCodes.pm	1970-01-01 01:00:00.000000000 +0100
27b8ba
+++ b/heartbeat/OCF_ReturnCodes.pm	2021-04-13 13:37:35.621267404 +0200
27b8ba
@@ -0,0 +1,97 @@
27b8ba
+#!/usr/bin/perl
27b8ba
+# This program is open source, licensed under the PostgreSQL License.
27b8ba
+# For license terms, see the LICENSE file.
27b8ba
+#
27b8ba
+# Copyright (C) 2016-2020: Jehan-Guillaume de Rorthais and Mael Rimbault
27b8ba
+
27b8ba
+=head1 NAME
27b8ba
+
27b8ba
+OCF_ReturnCodes - Common varibales for the OCF Resource Agents supplied by
27b8ba
+heartbeat.
27b8ba
+
27b8ba
+=head1 SYNOPSIS
27b8ba
+
27b8ba
+  use FindBin;
27b8ba
+  use lib "$FindBin::RealBin/../../lib/heartbeat/";
27b8ba
+  
27b8ba
+  use OCF_ReturnCodes;
27b8ba
+
27b8ba
+=head1 DESCRIPTION
27b8ba
+
27b8ba
+This module has been ported from the ocf-retrurncodes shell script of the
27b8ba
+resource-agents project. See L<https://github.com/ClusterLabs/resource-agents/>.
27b8ba
+
27b8ba
+=head1 VARIABLES
27b8ba
+
27b8ba
+Here are the variables exported by this module:
27b8ba
+
27b8ba
+=over
27b8ba
+
27b8ba
+=item $OCF_SUCCESS
27b8ba
+
27b8ba
+=item $OCF_ERR_GENERIC
27b8ba
+
27b8ba
+=item $OCF_ERR_ARGS
27b8ba
+
27b8ba
+=item $OCF_ERR_UNIMPLEMENTED
27b8ba
+
27b8ba
+=item $OCF_ERR_PERM
27b8ba
+
27b8ba
+=item $OCF_ERR_INSTALLED
27b8ba
+
27b8ba
+=item $OCF_ERR_CONFIGURED
27b8ba
+
27b8ba
+=item $OCF_NOT_RUNNING
27b8ba
+
27b8ba
+=item $OCF_RUNNING_MASTER
27b8ba
+
27b8ba
+=item $OCF_FAILED_MASTER
27b8ba
+
27b8ba
+=back
27b8ba
+
27b8ba
+=cut
27b8ba
+
27b8ba
+package OCF_ReturnCodes;
27b8ba
+
27b8ba
+use strict;
27b8ba
+use warnings;
27b8ba
+use 5.008;
27b8ba
+
27b8ba
+BEGIN {
27b8ba
+    use Exporter;
27b8ba
+
27b8ba
+    our $VERSION   = 'v2.3.0';
27b8ba
+    our @ISA       = ('Exporter');
27b8ba
+    our @EXPORT    = qw(
27b8ba
+        $OCF_SUCCESS
27b8ba
+        $OCF_ERR_GENERIC
27b8ba
+        $OCF_ERR_ARGS
27b8ba
+        $OCF_ERR_UNIMPLEMENTED
27b8ba
+        $OCF_ERR_PERM
27b8ba
+        $OCF_ERR_INSTALLED
27b8ba
+        $OCF_ERR_CONFIGURED
27b8ba
+        $OCF_NOT_RUNNING
27b8ba
+        $OCF_RUNNING_MASTER
27b8ba
+        $OCF_FAILED_MASTER
27b8ba
+    );
27b8ba
+    our @EXPORT_OK = ( @EXPORT );
27b8ba
+}
27b8ba
+
27b8ba
+our $OCF_SUCCESS           = 0;
27b8ba
+our $OCF_ERR_GENERIC       = 1;
27b8ba
+our $OCF_ERR_ARGS          = 2;
27b8ba
+our $OCF_ERR_UNIMPLEMENTED = 3;
27b8ba
+our $OCF_ERR_PERM          = 4;
27b8ba
+our $OCF_ERR_INSTALLED     = 5;
27b8ba
+our $OCF_ERR_CONFIGURED    = 6;
27b8ba
+our $OCF_NOT_RUNNING       = 7;
27b8ba
+our $OCF_RUNNING_MASTER    = 8;
27b8ba
+our $OCF_FAILED_MASTER     = 9;
27b8ba
+
27b8ba
+1;
27b8ba
+
27b8ba
+=head1 COPYRIGHT AND LICENSE
27b8ba
+
27b8ba
+Copyright (C) 2016: Jehan-Guillaume de Rorthais and Mael Rimbault.
27b8ba
+
27b8ba
+Licensed under the PostgreSQL License.
27b8ba
diff --color -uNr a/heartbeat/pgsqlms b/heartbeat/pgsqlms
27b8ba
--- a/heartbeat/pgsqlms	1970-01-01 01:00:00.000000000 +0100
27b8ba
+++ b/heartbeat/pgsqlms	2021-04-13 13:37:40.934280411 +0200
27b8ba
@@ -0,0 +1,2308 @@
27b8ba
+#!/usr/bin/perl
27b8ba
+# This program is open source, licensed under the PostgreSQL License.
27b8ba
+# For license terms, see the LICENSE file.
27b8ba
+#
27b8ba
+# Copyright (C) 2016-2020: Jehan-Guillaume de Rorthais and Mael Rimbault
27b8ba
+
27b8ba
+=head1 NAME
27b8ba
+
27b8ba
+ocf_heartbeat_pgsqlms - A PostgreSQL multi-state resource agent for Pacemaker
27b8ba
+
27b8ba
+=head1 SYNOPSIS
27b8ba
+
27b8ba
+B<pgsqlms> [start | stop | monitor | promote | demote | notify | reload | methods | meta-data | validate-all]
27b8ba
+
27b8ba
+=head1 DESCRIPTION
27b8ba
+
27b8ba
+Resource script for PostgreSQL in replication. It manages PostgreSQL servers using streaming replication as an HA resource.
27b8ba
+
27b8ba
+=cut
27b8ba
+
27b8ba
+use strict;
27b8ba
+use warnings;
27b8ba
+use 5.008;
27b8ba
+
27b8ba
+use POSIX qw(locale_h);
27b8ba
+use Scalar::Util qw(looks_like_number);
27b8ba
+use File::Spec;
27b8ba
+use File::Temp;
27b8ba
+use Data::Dumper;
27b8ba
+
27b8ba
+my $OCF_FUNCTIONS_DIR;
27b8ba
+BEGIN {
27b8ba
+	$OCF_FUNCTIONS_DIR = defined $ENV{'OCF_FUNCTIONS_DIR'} ? "$ENV{'OCF_FUNCTIONS_DIR'}" : "$ENV{'OCF_ROOT'}/lib/heartbeat";
27b8ba
+}
27b8ba
+use lib "$OCF_FUNCTIONS_DIR";
27b8ba
+
27b8ba
+use OCF_ReturnCodes;
27b8ba
+use OCF_Directories;
27b8ba
+use OCF_Functions;
27b8ba
+
27b8ba
+our $VERSION = 'v2.3.0';
27b8ba
+our $PROGRAM = 'pgsqlms';
27b8ba
+
27b8ba
+# OCF environment
27b8ba
+my $OCF_RESOURCE_INSTANCE = $ENV{'OCF_RESOURCE_INSTANCE'};
27b8ba
+my $OCF_RUNNING_SLAVE     = $OCF_SUCCESS;
27b8ba
+my %OCF_NOTIFY_ENV        = ocf_notify_env() if $__OCF_ACTION eq 'notify';
27b8ba
+
27b8ba
+# Default parameters values
27b8ba
+my $system_user_default = "postgres";
27b8ba
+my $bindir_default      = "/usr/bin";
27b8ba
+my $pgdata_default      = "/var/lib/pgsql/data";
27b8ba
+my $pghost_default      = "/tmp";
27b8ba
+my $pgport_default      = 5432;
27b8ba
+my $start_opts_default  = "";
27b8ba
+my $maxlag_default      = "0";
27b8ba
+
27b8ba
+# Set default values if not found in environment
27b8ba
+my $system_user  = $ENV{'OCF_RESKEY_system_user'} || $system_user_default;
27b8ba
+my $bindir       = $ENV{'OCF_RESKEY_bindir'} || $bindir_default;
27b8ba
+my $pgdata       = $ENV{'OCF_RESKEY_pgdata'} || $pgdata_default;
27b8ba
+my $datadir      = $ENV{'OCF_RESKEY_datadir'} || $pgdata;
27b8ba
+my $pghost       = $ENV{'OCF_RESKEY_pghost'} || $pghost_default;
27b8ba
+my $pgport       = $ENV{'OCF_RESKEY_pgport'} || $pgport_default;
27b8ba
+my $start_opts   = $ENV{'OCF_RESKEY_start_opts'} || $start_opts_default;
27b8ba
+my $maxlag       = $ENV{'OCF_RESKEY_maxlag'} || $maxlag_default;
27b8ba
+my $recovery_tpl = $ENV{'OCF_RESKEY_recovery_template'}
27b8ba
+    || "$pgdata/recovery.conf.pcmk";
27b8ba
+
27b8ba
+
27b8ba
+# PostgreSQL commands path
27b8ba
+my $POSTGRES   = "$bindir/postgres";
27b8ba
+my $PGCTL      = "$bindir/pg_ctl";
27b8ba
+my $PGPSQL     = "$bindir/psql";
27b8ba
+my $PGCTRLDATA = "$bindir/pg_controldata";
27b8ba
+my $PGISREADY  = "$bindir/pg_isready";
27b8ba
+my $PGWALDUMP  = "$bindir/pg_waldump";
27b8ba
+
27b8ba
+# pacemaker commands path
27b8ba
+my $CRM_MASTER    = "$HA_SBIN_DIR/crm_master --lifetime forever";
27b8ba
+my $CRM_NODE      = "$HA_SBIN_DIR/crm_node";
27b8ba
+my $CRM_RESOURCE  = "$HA_SBIN_DIR/crm_resource";
27b8ba
+my $ATTRD_PRIV    = "$HA_SBIN_DIR/attrd_updater --private --lifetime reboot";
27b8ba
+
27b8ba
+# Global vars
27b8ba
+my $nodename;
27b8ba
+my $exit_code = 0;
27b8ba
+# numeric pgsql versions
27b8ba
+my $PGVERNUM;
27b8ba
+my $PGVER_93 = 90300;
27b8ba
+my $PGVER_10 = 100000;
27b8ba
+my $PGVER_12 = 120000;
27b8ba
+
27b8ba
+# Run a query using psql.
27b8ba
+#
27b8ba
+# This function returns an array with psql return code as first element and
27b8ba
+# the result as second one.
27b8ba
+#
27b8ba
+sub _query {
27b8ba
+    my $query        = shift;
27b8ba
+    my $res          = shift;
27b8ba
+    my $connstr      = "dbname=postgres";
27b8ba
+    my $RS           = chr(30); # ASCII RS  (record separator)
27b8ba
+    my $FS           = chr(3);  # ASCII ETX (end of text)
27b8ba
+    my $postgres_uid = getpwnam( $system_user );
27b8ba
+    my $oldeuid      = $>;
27b8ba
+    my $tmpfile;
27b8ba
+    my @res;
27b8ba
+    my $ans;
27b8ba
+    my $pid;
27b8ba
+    my $rc;
27b8ba
+
27b8ba
+    unless ( defined $res and defined $query and $query ne '' ) {
27b8ba
+        ocf_log( 'debug', '_query: wrong parameters!' );
27b8ba
+        return -1;
27b8ba
+    }
27b8ba
+
27b8ba
+    unless ( $tmpfile = File::Temp->new(
27b8ba
+            TEMPLATE => 'pgsqlms-XXXXXXXX',
27b8ba
+            DIR      => $HA_RSCTMP
27b8ba
+        ) )
27b8ba
+    {
27b8ba
+        ocf_exit_reason( 'Could not create or write in a temp file' );
27b8ba
+        exit $OCF_ERR_INSTALLED;
27b8ba
+    }
27b8ba
+
27b8ba
+    print $tmpfile $query;
27b8ba
+    chmod 0644, $tmpfile;
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_query: %s', $query );
27b8ba
+
27b8ba
+    # Change the effective user to the given system_user so after forking
27b8ba
+    # the given uid to the process should allow psql to connect w/o password
27b8ba
+    $> = $postgres_uid;
27b8ba
+
27b8ba
+    # Forking + piping
27b8ba
+    $pid = open(my $KID, "-|");
27b8ba
+
27b8ba
+    if ( $pid == 0 ) { # child
27b8ba
+        exec $PGPSQL, '--set', 'ON_ERROR_STOP=1', '-qXAtf', $tmpfile,
27b8ba
+            '-R', $RS, '-F', $FS, '--port', $pgport, '--host', $pghost,
27b8ba
+            $connstr;
27b8ba
+    }
27b8ba
+
27b8ba
+    # parent
27b8ba
+    $> = $oldeuid;
27b8ba
+
27b8ba
+    {
27b8ba
+        local $/;
27b8ba
+        $ans = <$KID>;
27b8ba
+    }
27b8ba
+
27b8ba
+    close $KID;
27b8ba
+    $rc = $? >> 8;
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_query: psql return code: %d', $rc );
27b8ba
+
27b8ba
+    if ( defined $ans ) {
27b8ba
+        chop $ans;
27b8ba
+
27b8ba
+        push @{ $res }, [ split(chr(3) => $_, -1) ]
27b8ba
+            foreach split (chr(30) => $ans, -1);
27b8ba
+
27b8ba
+        ocf_log( 'debug', '_query: @res: %s',
27b8ba
+            Data::Dumper->new( [ $res ] )->Terse(1)->Dump );
27b8ba
+    }
27b8ba
+
27b8ba
+    # Possible return codes:
27b8ba
+    #  -1: wrong parameters
27b8ba
+    #   0: OK
27b8ba
+    #   1: failed to get resources (memory, missing file, ...)
27b8ba
+    #   2: unable to connect
27b8ba
+    #   3: query failed
27b8ba
+    return $rc;
27b8ba
+}
27b8ba
+
27b8ba
+# Get the last received location on a standby
27b8ba
+# if the first argument is true, returns the value as decimal
27b8ba
+# if the first argument is false, returns the value as LSN
27b8ba
+# Returns undef if query failed
27b8ba
+sub _get_last_received_lsn {
27b8ba
+    my ( $dec ) = @_;
27b8ba
+    my $pg_last_wal_receive_lsn = 'pg_last_wal_receive_lsn()';
27b8ba
+    my $pg_wal_lsn_diff         = 'pg_wal_lsn_diff';
27b8ba
+    my $query;
27b8ba
+    my $rc;
27b8ba
+    my @rs;
27b8ba
+
27b8ba
+    if ( $PGVERNUM < $PGVER_10  ) {
27b8ba
+        $pg_last_wal_receive_lsn = 'pg_last_xlog_receive_location()';
27b8ba
+        $pg_wal_lsn_diff         = 'pg_xlog_location_diff';
27b8ba
+    }
27b8ba
+
27b8ba
+    if ( $dec ) {
27b8ba
+        $query = "SELECT $pg_wal_lsn_diff( $pg_last_wal_receive_lsn, '0/0' )";
27b8ba
+    }
27b8ba
+    else {
27b8ba
+        $query = "SELECT $pg_last_wal_receive_lsn";
27b8ba
+    }
27b8ba
+
27b8ba
+    $rc = _query( $query, \@rs );
27b8ba
+
27b8ba
+    return $rs[0][0] if $rc == 0 and $rs[0][0];
27b8ba
+
27b8ba
+    ocf_log( 'err', 'Could not query last received LSN (%s)', $rc ) if $rc != 0;
27b8ba
+    ocf_log( 'err', 'No values for last received LSN' )
27b8ba
+        if $rc == 0 and not $rs[0][0];
27b8ba
+
27b8ba
+    return undef;
27b8ba
+}
27b8ba
+
27b8ba
+# Get the master score for each connected standby
27b8ba
+# Returns directly the result set of the query or exit with an error.
27b8ba
+# Exits with OCF_ERR_GENERIC if the query failed
27b8ba
+sub _get_lag_scores {
27b8ba
+    my $pg_current_wal_lsn = 'pg_current_wal_lsn()';
27b8ba
+    my $pg_wal_lsn_diff    = 'pg_wal_lsn_diff';
27b8ba
+    my $write_lsn          = 'write_lsn';
27b8ba
+    my $query;
27b8ba
+    my $rc;
27b8ba
+    my @rs;
27b8ba
+
27b8ba
+    if ( $PGVERNUM < $PGVER_10  ) {
27b8ba
+        $pg_current_wal_lsn = 'pg_current_xlog_location()';
27b8ba
+        $pg_wal_lsn_diff    = 'pg_xlog_location_diff';
27b8ba
+        $write_lsn          = 'write_location';
27b8ba
+    }
27b8ba
+
27b8ba
+    # We check locations of connected standbies by querying the
27b8ba
+    # "pg_stat_replication" view.
27b8ba
+    # The row_number applies on the result set ordered on write_location ASC so
27b8ba
+    # the highest row_number should be given to the closest node from the
27b8ba
+    # master, then the lowest node name (alphanumeric sort) in case of equality.
27b8ba
+    # The result set itself is order by priority DESC to process best known
27b8ba
+    # candidate first.
27b8ba
+    $query = qq{
27b8ba
+      SELECT application_name, priority, location, state, current_lag
27b8ba
+      FROM (
27b8ba
+        SELECT application_name,
27b8ba
+          (1000 - (
27b8ba
+            row_number() OVER (
27b8ba
+              PARTITION BY state IN ('startup', 'backup')
27b8ba
+              ORDER BY location ASC, application_name ASC
27b8ba
+            ) - 1
27b8ba
+           ) * 10
27b8ba
+          ) * CASE WHEN ( $maxlag > 0
27b8ba
+                     AND current_lag > $maxlag)
27b8ba
+                        THEN -1
27b8ba
+                   ELSE 1
27b8ba
+              END AS priority,
27b8ba
+          location, state, current_lag
27b8ba
+        FROM (
27b8ba
+          SELECT application_name, $write_lsn AS location, state,
27b8ba
+            $pg_wal_lsn_diff($pg_current_wal_lsn, $write_lsn) AS current_lag
27b8ba
+          FROM pg_stat_replication
27b8ba
+        ) AS s2
27b8ba
+      ) AS s1
27b8ba
+      ORDER BY priority DESC
27b8ba
+    };
27b8ba
+
27b8ba
+    $rc = _query( $query, \@rs );
27b8ba
+
27b8ba
+    if ( $rc != 0 ) {
27b8ba
+        ocf_exit_reason( 'Query to get standby locations failed (%d)', $rc );
27b8ba
+        exit $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    return \@rs;
27b8ba
+}
27b8ba
+
27b8ba
+# get the timeout for the current action given from environment var
27b8ba
+# Returns   timeout as integer
27b8ba
+#           undef if unknown
27b8ba
+sub _get_action_timeout {
27b8ba
+    my $timeout = $ENV{'OCF_RESKEY_CRM_meta_timeout'} / 1000;
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_get_action_timeout: known timeout: %s',
27b8ba
+        defined $timeout ? $timeout : 'undef' );
27b8ba
+
27b8ba
+    return $timeout if defined $timeout and $timeout =~ /^\d+$/;
27b8ba
+
27b8ba
+    return undef;
27b8ba
+}
27b8ba
+
27b8ba
+# Get, parse and return the value of the given private attribute name
27b8ba
+# Returns an empty string if not found.
27b8ba
+sub _get_priv_attr {
27b8ba
+    my ( $name, $node ) = @_;
27b8ba
+    my $val             = '';
27b8ba
+    my $node_arg        = '';
27b8ba
+    my $ans;
27b8ba
+
27b8ba
+    $node = '' unless defined $node;
27b8ba
+    $name = "$name-$OCF_RESOURCE_INSTANCE";
27b8ba
+
27b8ba
+    $node_arg= "--node $node" if $node ne '';
27b8ba
+
27b8ba
+    $ans = qx{ $ATTRD_PRIV --name "$name" --query $node_arg };
27b8ba
+
27b8ba
+    $ans =~ m/^name=".*" host=".*" value="(.*)"$/;
27b8ba
+
27b8ba
+    $val = $1 if defined $1;
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_get_priv_attr: value of "%s"%s is "%s"', $name,
27b8ba
+        ( $node ? " on \"$node\"": ""),
27b8ba
+        $val );
27b8ba
+
27b8ba
+    return $val;
27b8ba
+}
27b8ba
+
27b8ba
+# Set the given private attribute name to the given value
27b8ba
+# As setting an attribute is asynchronous, this will return as soon as the
27b8ba
+# attribute is really set by attrd and available.
27b8ba
+sub _set_priv_attr {
27b8ba
+    my ( $name, $val ) = @_;
27b8ba
+    my $name_instance  = "$name-$OCF_RESOURCE_INSTANCE";
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_set_priv_attr: set "%s=%s"...', $name_instance, $val );
27b8ba
+
27b8ba
+    qx{ $ATTRD_PRIV --name "$name_instance" --update "$val" };
27b8ba
+
27b8ba
+    # give attr name without the resource instance name as _get_priv_attr adds
27b8ba
+    # it as well
27b8ba
+    while ( _get_priv_attr( $name ) ne $val ) {
27b8ba
+        ocf_log( 'debug', '_set_priv_attr: waiting attrd ack for "%s"...', $name_instance );
27b8ba
+        select( undef, undef, undef, 0.1 );
27b8ba
+    }
27b8ba
+
27b8ba
+    return;
27b8ba
+}
27b8ba
+
27b8ba
+# Delete the given private attribute.
27b8ba
+# As setting an attribute is asynchronous, this will return as soon as the
27b8ba
+# attribute is really deleted by attrd.
27b8ba
+sub _delete_priv_attr {
27b8ba
+    my ( $name ) = @_;
27b8ba
+    my $name_instance  = "$name-$OCF_RESOURCE_INSTANCE";
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_delete_priv_attr: delete "%s"...', $name_instance );
27b8ba
+
27b8ba
+    qx{ $ATTRD_PRIV --name "$name_instance" --delete };
27b8ba
+
27b8ba
+    # give attr name without the resource instance name as _get_priv_attr adds
27b8ba
+    # it as well
27b8ba
+    while ( _get_priv_attr( $name ) ne '' ) {
27b8ba
+        ocf_log( 'debug', '_delete_priv_attr: waiting attrd ack for "%s"...',
27b8ba
+            $name_instance );
27b8ba
+        select( undef, undef, undef, 0.1 );
27b8ba
+    }
27b8ba
+
27b8ba
+    return;
27b8ba
+}
27b8ba
+
27b8ba
+# Get, parse and return the resource master score on given node.
27b8ba
+# Returns an empty string if not found.
27b8ba
+# Returns undef on crm_master call on error
27b8ba
+sub _get_master_score {
27b8ba
+    my ( $node ) = @_;
27b8ba
+    my $node_arg = '';
27b8ba
+    my $score;
27b8ba
+
27b8ba
+    $node_arg = sprintf '--node "%s"', $node if defined $node and $node ne '';
27b8ba
+
27b8ba
+    $score = qx{ $CRM_MASTER --quiet --get-value $node_arg 2> /dev/null };
27b8ba
+
27b8ba
+    return '' unless $? == 0 and defined $score;
27b8ba
+
27b8ba
+    chomp $score;
27b8ba
+
27b8ba
+    return $score;
27b8ba
+}
27b8ba
+
27b8ba
+# Set the master score of the local node or the optionally given node.
27b8ba
+# As setting an attribute is asynchronous, this will return as soon as the
27b8ba
+# attribute is really set by attrd and available everywhere.
27b8ba
+sub _set_master_score {
27b8ba
+    my ( $score, $node ) = @_;
27b8ba
+    my $node_arg = '';
27b8ba
+    my $tmp;
27b8ba
+
27b8ba
+    $node_arg = sprintf '--node "%s"', $node if defined $node and $node ne '';
27b8ba
+
27b8ba
+    qx{ $CRM_MASTER $node_arg --quiet --update "$score" };
27b8ba
+
27b8ba
+    while ( ( $tmp = _get_master_score( $node ) ) ne $score ) {
27b8ba
+        ocf_log( 'debug',
27b8ba
+            '_set_master_score: waiting to set score to "%s" (currently "%s")...',
27b8ba
+            $score, $tmp );
27b8ba
+        select(undef, undef, undef, 0.1);
27b8ba
+    }
27b8ba
+
27b8ba
+    return;
27b8ba
+}
27b8ba
+
27b8ba
+# _master_score_exists
27b8ba
+# This subroutine checks if a master score is set for one of the relative clones
27b8ba
+# in the cluster and the score is greater or equal of 0.
27b8ba
+# Returns 1 if at least one master score >= 0 is found.
27b8ba
+# Returns 0 otherwise
27b8ba
+sub _master_score_exists {
27b8ba
+    my @partition_nodes = split /\s+/ => qx{ $CRM_NODE --partition };
27b8ba
+
27b8ba
+    foreach my $node ( @partition_nodes ) {
27b8ba
+        my $score = _get_master_score( $node );
27b8ba
+
27b8ba
+        return 1 if defined $score and $score ne '' and $score > -1;
27b8ba
+    }
27b8ba
+
27b8ba
+    return 0;
27b8ba
+}
27b8ba
+
27b8ba
+# Check if the current transiation is a recover of a master clone on given node.
27b8ba
+sub _is_master_recover {
27b8ba
+    my ( $n ) = @_;
27b8ba
+
27b8ba
+    return (
27b8ba
+            scalar grep { $_->{'uname'} eq $n } @{ $OCF_NOTIFY_ENV{'master'} }
27b8ba
+        and scalar grep { $_->{'uname'} eq $n } @{ $OCF_NOTIFY_ENV{'promote'} }
27b8ba
+    );
27b8ba
+}
27b8ba
+
27b8ba
+# Check if the current transition is a recover of a slave clone on given node.
27b8ba
+sub _is_slave_recover {
27b8ba
+    my ( $n ) = @_;
27b8ba
+
27b8ba
+    return (
27b8ba
+            scalar grep { $_->{'uname'} eq $n } @{ $OCF_NOTIFY_ENV{'slave'} }
27b8ba
+        and scalar grep { $_->{'uname'} eq $n } @{ $OCF_NOTIFY_ENV{'start'} }
27b8ba
+    );
27b8ba
+}
27b8ba
+
27b8ba
+# check if th current transition is a switchover to the given node.
27b8ba
+sub _is_switchover {
27b8ba
+    my ( $n ) = @_;
27b8ba
+    my $old = $OCF_NOTIFY_ENV{'master'}[0]{'uname'};
27b8ba
+
27b8ba
+    return 0 if scalar @{ $OCF_NOTIFY_ENV{'master'} }  != 1
27b8ba
+             or scalar @{ $OCF_NOTIFY_ENV{'demote'} }  != 1
27b8ba
+             or scalar @{ $OCF_NOTIFY_ENV{'promote'} } != 1;
27b8ba
+
27b8ba
+    return (
27b8ba
+           scalar grep { $_->{'uname'} eq $old } @{ $OCF_NOTIFY_ENV{'demote'} }
27b8ba
+       and scalar grep { $_->{'uname'} eq $n } @{ $OCF_NOTIFY_ENV{'slave'} }
27b8ba
+       and scalar grep { $_->{'uname'} eq $n } @{ $OCF_NOTIFY_ENV{'promote'} }
27b8ba
+       and not scalar grep { $_->{'uname'} eq $old } @{ $OCF_NOTIFY_ENV{'stop'} }
27b8ba
+    );
27b8ba
+}
27b8ba
+
27b8ba
+# Run the given command as the "system_user" given as parameter.
27b8ba
+# It basically forks and seteuid/setuid away from root.
27b8ba
+#
27b8ba
+sub _runas {
27b8ba
+    my $rc;
27b8ba
+    my $pid;
27b8ba
+    my @cmd = @_;
27b8ba
+    my (undef, undef, $postgres_uid, $postgres_gid ) = getpwnam( $system_user );
27b8ba
+
27b8ba
+    $pid = fork;
27b8ba
+
27b8ba
+    if ( $pid == 0 ) { # in child
27b8ba
+        $) = "$postgres_gid $postgres_gid";
27b8ba
+        while ( my ( undef, undef, $gid, $members ) = getgrent ) {
27b8ba
+            $) .= " $gid" if grep { $system_user eq $_ } split /\s+/, $members
27b8ba
+        }
27b8ba
+        $( = $postgres_gid;
27b8ba
+
27b8ba
+        $< = $> = $postgres_uid;
27b8ba
+
27b8ba
+        exec @cmd;
27b8ba
+    }
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_runas: launching as "%s" command "%s"', $system_user,
27b8ba
+        join(' ', @cmd) );
27b8ba
+
27b8ba
+    waitpid $pid, 0;
27b8ba
+    $rc = $? >> 8;
27b8ba
+
27b8ba
+    return $rc;
27b8ba
+}
27b8ba
+
27b8ba
+# Check if instance is listening on the given host/port.
27b8ba
+#
27b8ba
+sub _pg_isready {
27b8ba
+    # Add 60s to the timeout or use a 24h timeout fallback to make sure
27b8ba
+    # Pacemaker will give up before us and take decisions
27b8ba
+    my $timeout = ( _get_action_timeout() || 60*60*24 )  + 60;
27b8ba
+    my $rc = _runas( $PGISREADY, '-h', $pghost, '-p', $pgport, '-d', 'postgres', '-t', $timeout );
27b8ba
+
27b8ba
+    # Possible error codes:
27b8ba
+    #   1: ping rejected (usually when instance is in startup, in crash
27b8ba
+    #      recovery, in warm standby, or when a shutdown is in progress)
27b8ba
+    #   2: no response, usually means the instance is down
27b8ba
+    #   3: no attempt, probably a syntax error, should not happen
27b8ba
+    return $rc;
27b8ba
+}
27b8ba
+
27b8ba
+# Check the postmaster.pid file and the postmaster process.
27b8ba
+# WARNING: we do not distinguish the scenario where postmaster.pid does not
27b8ba
+# exist from the scenario where the process is still alive. It should be ok
27b8ba
+# though, as this is considered a hard error from monitor.
27b8ba
+#
27b8ba
+sub _pg_ctl_status {
27b8ba
+    my $rc = _runas( $PGCTL, '--pgdata', $pgdata, 'status' );
27b8ba
+
27b8ba
+    # Possible error codes:
27b8ba
+    #   3: postmaster.pid file does not exist OR it does but the process
27b8ba
+    #      with the PID found in the file is not alive
27b8ba
+    return $rc;
27b8ba
+}
27b8ba
+
27b8ba
+# Start the local instance using pg_ctl
27b8ba
+#
27b8ba
+sub _pg_ctl_start {
27b8ba
+    # Add 60s to the timeout or use a 24h timeout fallback to make sure
27b8ba
+    # Pacemaker will give up before us and take decisions
27b8ba
+    my $timeout = ( _get_action_timeout() || 60*60*24 ) + 60;
27b8ba
+
27b8ba
+    my @cmd = ( $PGCTL, '--pgdata', $pgdata, '-w', '--timeout', $timeout, 'start' );
27b8ba
+
27b8ba
+    push @cmd => ( '-o', $start_opts ) if $start_opts ne '';
27b8ba
+
27b8ba
+    return _runas( @cmd );
27b8ba
+}
27b8ba
+
27b8ba
+# Enable the Standby mode.
27b8ba
+#
27b8ba
+# Up to v11, creates the recovery.conf file based on the given template.
27b8ba
+# Since v12, creates standby.signal.
27b8ba
+sub _enable_recovery {
27b8ba
+    my $fh;
27b8ba
+    my $content      = '';
27b8ba
+    my $standby_file = "$datadir/standby.signal";
27b8ba
+    my (undef, undef, $uid, $gid) = getpwnam($system_user);
27b8ba
+
27b8ba
+    if ( $PGVERNUM < $PGVER_12 ) {
27b8ba
+        $standby_file = "$datadir/recovery.conf";
27b8ba
+
27b8ba
+        ocf_log( 'debug',
27b8ba
+            '_enable_recovery: get replication configuration from the template file "%s"',
27b8ba
+            $recovery_tpl );
27b8ba
+
27b8ba
+        # Create the recovery.conf file to start the instance as a secondary.
27b8ba
+        # NOTE: the recovery.conf is supposed to be set up so the secondary can
27b8ba
+        # connect to the primary instance, eg. using a virtual IP address.
27b8ba
+        # As there is no primary instance available at startup, secondaries will
27b8ba
+        # complain about failing to connect.
27b8ba
+        # As we can not reload a recovery.conf file on a standby without restarting
27b8ba
+        # it, we will leave with this.
27b8ba
+        # FIXME how would the reload help us in this case ?
27b8ba
+        unless ( defined open( $fh, '<', $recovery_tpl ) ) {
27b8ba
+            ocf_exit_reason( 'Could not open file "%s": %s', $recovery_tpl, $! );
27b8ba
+            exit $OCF_ERR_CONFIGURED;
27b8ba
+        }
27b8ba
+
27b8ba
+        # Copy all parameters from the template file
27b8ba
+        while (my $line = <$fh>) {
27b8ba
+            chomp $line;
27b8ba
+            $content .= "$line\n";
27b8ba
+        }
27b8ba
+        close $fh;
27b8ba
+    }
27b8ba
+
27b8ba
+    ocf_log( 'debug', '_enable_recovery: write the standby file "%s"', $standby_file );
27b8ba
+
27b8ba
+    unless ( open( $fh, '>', $standby_file ) ) {
27b8ba
+        ocf_exit_reason( 'Could not open file "%s": %s', $standby_file, $! );
27b8ba
+        exit $OCF_ERR_CONFIGURED;
27b8ba
+    }
27b8ba
+
27b8ba
+    # Write the recovery.conf file using configuration from the template file
27b8ba
+    print $fh $content;
27b8ba
+
27b8ba
+    close $fh;
27b8ba
+
27b8ba
+    unless ( chown $uid, $gid, $standby_file ) {
27b8ba
+        ocf_exit_reason( 'Could not set owner of "%s"', $standby_file );
27b8ba
+        exit $OCF_ERR_CONFIGURED;
27b8ba
+    };
27b8ba
+}
27b8ba
+
27b8ba
+# Parse and return various informations about the local PostgreSQL instance as
27b8ba
+# reported by its controldata file.
27b8ba
+#
27b8ba
+# WARNING: the status is NOT updated in case of crash.
27b8ba
+#
27b8ba
+# This sub exit the script with an error on failure
27b8ba
+sub _get_controldata {
27b8ba
+    my %controldata;
27b8ba
+    my $ans;
27b8ba
+
27b8ba
+    $ans = qx{ $PGCTRLDATA "$datadir" 2>/dev/null };
27b8ba
+
27b8ba
+    # Parse the output of pg_controldata.
27b8ba
+    # This output is quite stable between pg versions, but we might need to sort
27b8ba
+    # it at some point if things are moving in there...
27b8ba
+    $ans =~ m{
27b8ba
+        # get the current state
27b8ba
+        ^\QDatabase cluster state\E:\s+(.*?)\s*$
27b8ba
+        .*
27b8ba
+        # Get the latest known REDO location
27b8ba
+        ^\QLatest checkpoint's REDO location\E:\s+([/0-9A-F]+)\s*$
27b8ba
+        .*
27b8ba
+        # Get the latest known TL
27b8ba
+        ^\QLatest checkpoint's TimeLineID\E:\s+(\d+)\s*$
27b8ba
+        .*
27b8ba
+        # Get the wal level
27b8ba
+        # NOTE: pg_controldata output changed with PostgreSQL 9.5, so we need to
27b8ba
+        # account for both syntaxes
27b8ba
+        ^(?:\QCurrent \E)?\Qwal_level setting\E:\s+(.*?)\s*$
27b8ba
+    }smx;
27b8ba
+
27b8ba
+    $controldata{'state'}     = $1 if defined $1;
27b8ba
+    $controldata{'redo'}      = $2 if defined $2;
27b8ba
+    $controldata{'tl'}        = $3 if defined $3;
27b8ba
+    $controldata{'wal_level'} = $4 if defined $4;
27b8ba
+
27b8ba
+    ocf_log( 'debug',
27b8ba
+        "_get_controldata: found: %s",
27b8ba
+        Data::Dumper->new( [ \%controldata ] )->Terse(1)->Dump );
27b8ba
+
27b8ba
+    return %controldata if defined $controldata{'state'}
27b8ba
+                        and defined $controldata{'tl'}
27b8ba
+                        and defined $controldata{'redo'}
27b8ba
+                        and defined $controldata{'wal_level'};
27b8ba
+
27b8ba
+    ocf_exit_reason( 'Could not read all datas from controldata file for "%s"',
27b8ba
+        $datadir );
27b8ba
+
27b8ba
+    ocf_log( 'debug',
27b8ba
+        "_get_controldata: controldata file: %s",
27b8ba
+        Data::Dumper->new( [ \%controldata ] )->Terse(1)->Dump, $ans );
27b8ba
+
27b8ba
+    exit $OCF_ERR_ARGS;
27b8ba
+}
27b8ba
+
27b8ba
+# Pead major version from datadir/PG_VERSION and return it as numeric version
27b8ba
+sub _get_pg_version {
27b8ba
+    my $fh;
27b8ba
+    my $PGVERSION;
27b8ba
+    my $PGVERNUM;
27b8ba
+
27b8ba
+    # check PG_VERSION
27b8ba
+    if ( ! -s "$datadir/PG_VERSION" ) {
27b8ba
+        ocf_exit_reason( 'PG_VERSION does not exist in "%s"', $datadir );
27b8ba
+        exit $OCF_ERR_ARGS;
27b8ba
+    }
27b8ba
+
27b8ba
+    unless ( open( $fh, '<', "$datadir/PG_VERSION" ) ) {
27b8ba
+        ocf_exit_reason( "Could not open file \"$datadir/PG_VERSION\": $!" );
27b8ba
+        exit $OCF_ERR_ARGS;
27b8ba
+    }
27b8ba
+
27b8ba
+    read( $fh, $PGVERSION, 32 );
27b8ba
+    close $fh;
27b8ba
+
27b8ba
+    chomp $PGVERSION;
27b8ba
+
27b8ba
+    $PGVERSION =~ /^(\d+)(?:\.(\d+))?$/;
27b8ba
+    $PGVERNUM  = $1 * 10000;
27b8ba
+    $PGVERNUM += $2 * 100 if $1 < 10; # no 2nd num in the major version from v10
27b8ba
+
27b8ba
+    return $PGVERNUM;
27b8ba
+}
27b8ba
+
27b8ba
+# Use pg_controldata to check the state of the PostgreSQL server. This
27b8ba
+# function returns codes depending on this state, so we can find whether the
27b8ba
+# instance is a primary or a secondary, or use it to detect any inconsistency
27b8ba
+# that could indicate the instance has crashed.
27b8ba
+#
27b8ba
+sub _controldata_to_ocf {
27b8ba
+    my %cdata = _get_controldata();
27b8ba
+
27b8ba
+    while ( 1 ) {
27b8ba
+        ocf_log( 'debug', '_controldata: instance "%s" state is "%s"',
27b8ba
+            $OCF_RESOURCE_INSTANCE, $cdata{'state'} );
27b8ba
+
27b8ba
+        # Instance should be running as a primary.
27b8ba
+        return $OCF_RUNNING_MASTER if $cdata{'state'} eq "in production";
27b8ba
+
27b8ba
+        # Instance should be running as a secondary.
27b8ba
+        # This state includes warm standby (rejects connections attempts,
27b8ba
+        # including pg_isready)
27b8ba
+        return $OCF_SUCCESS if $cdata{'state'} eq "in archive recovery";
27b8ba
+
27b8ba
+
27b8ba
+        # The instance should be stopped.
27b8ba
+        # We don't care if it was a primary or secondary before, because we
27b8ba
+        # always start instances as secondaries, and then promote if necessary.
27b8ba
+        return $OCF_NOT_RUNNING if $cdata{'state'} eq "shut down"
27b8ba
+            or $cdata{'state'} eq "shut down in recovery";
27b8ba
+
27b8ba
+        # The state is "in crash recovery", "starting up" or "shutting down".
27b8ba
+        # This state should be transitional, so we wait and loop to check if
27b8ba
+        # it changes.
27b8ba
+        # If it does not, pacemaker will eventually abort with a timeout.
27b8ba
+        ocf_log( 'debug',
27b8ba
+            '_controldata: waiting for transitionnal state "%s" to finish',
27b8ba
+            $cdata{'state'} );
27b8ba
+        sleep 1;
27b8ba
+        %cdata = _get_controldata();
27b8ba
+    }
27b8ba
+
27b8ba
+    # If we reach this point, something went really wrong with this code or
27b8ba
+    # pg_controldata.
27b8ba
+    ocf_exit_reason( 'Unable get instance "%s" state using pg_controldata',
27b8ba
+        $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+    return $OCF_ERR_INSTALLED ;
27b8ba
+}
27b8ba
+
27b8ba
+# Check the write_location of all secondaries, and adapt their master score so
27b8ba
+# that the instance closest to the master will be the selected candidate should
27b8ba
+# a promotion be triggered.
27b8ba
+# NOTE: This is only a hint to pacemaker! The selected candidate to promotion
27b8ba
+# actually re-check it is the best candidate and force a re-election by failing
27b8ba
+# if a better one exists. This avoid a race condition between the call of the
27b8ba
+# monitor action and the promotion where another slave might have catchup faster
27b8ba
+# with the master.
27b8ba
+# NOTE: we cannot directly use the write_location, neither a lsn_diff value as
27b8ba
+# promotion score as Pacemaker considers any value greater than 1,000,000 as
27b8ba
+# INFINITY.
27b8ba
+#
27b8ba
+# This sub must be executed from a master monitor action.
27b8ba
+#
27b8ba
+sub _check_locations {
27b8ba
+    my $partition_nodes;
27b8ba
+    my $node_score;
27b8ba
+    my $row_num;
27b8ba
+    my $row;
27b8ba
+    my @rs;
27b8ba
+
27b8ba
+    # Set the master score if not already done
27b8ba
+    $node_score = _get_master_score();
27b8ba
+    _set_master_score( '1001' ) unless $node_score eq '1001';
27b8ba
+
27b8ba
+    # Ask crm_node what nodes are present in our current cluster partition
27b8ba
+    $partition_nodes = qx{ $CRM_NODE --partition };
27b8ba
+
27b8ba
+    @rs = @{ _get_lag_scores() };
27b8ba
+
27b8ba
+    $row_num = scalar @rs;
27b8ba
+
27b8ba
+    # If no lag are reported at this point, it means that there is no
27b8ba
+    # secondary instance connected.
27b8ba
+    ocf_log( 'warning', 'No secondary connected to the master' )
27b8ba
+        if $row_num == 0;
27b8ba
+
27b8ba
+    # For each standby connected, set their master score based on the following
27b8ba
+    # rule: the first known node/application, with the highest priority and
27b8ba
+    # an acceptable state.
27b8ba
+    while ( $row = shift @rs ) {
27b8ba
+
27b8ba
+        if ( $partition_nodes !~ /$row->[0]/ ) {
27b8ba
+            ocf_log( 'info', 'Ignoring unknown application_name/node "%s"',
27b8ba
+                $row->[0] );
27b8ba
+            next;
27b8ba
+        }
27b8ba
+
27b8ba
+        if ( $row->[0] eq $nodename ) {
27b8ba
+            ocf_log( 'warning', 'Streaming replication with myself!' );
27b8ba
+            next;
27b8ba
+        }
27b8ba
+
27b8ba
+        $node_score = _get_master_score( $row->[0] );
27b8ba
+
27b8ba
+        if ( $row->[3] =~ /^\s*(?:startup|backup)\s*$/ ) {
27b8ba
+            # We exclude any standby being in state backup (pg_basebackup) or
27b8ba
+            # startup (new standby or failing standby)
27b8ba
+            ocf_log( 'info', 'Forbidding promotion on "%s" in state "%s"',
27b8ba
+                $row->[0], $row->[3] );
27b8ba
+
27b8ba
+            _set_master_score( '-1', $row->[0] ) unless $node_score eq '-1';
27b8ba
+        }
27b8ba
+        else {
27b8ba
+            ocf_log( 'debug',
27b8ba
+                '_check_locations: checking "%s" promotion ability (current_score: %s, priority: %s, location: %s, lag: %s)',
27b8ba
+                $row->[0], $node_score, $row->[1], $row->[2], $row->[4] );
27b8ba
+
27b8ba
+            if ( $node_score ne $row->[1] ) {
27b8ba
+                if ( $row->[1] < -1 ) {
27b8ba
+                    ocf_log( 'info', 'Update score of "%s" from %s to %s because replication lag (%s) is higher than given maxlag (%s).',
27b8ba
+                        $row->[0], $node_score, $row->[1], $row->[4], $maxlag );
27b8ba
+                }
27b8ba
+                else {
27b8ba
+                    ocf_log( 'info', 'Update score of "%s" from %s to %s because of a change in the replication lag (%s).',
27b8ba
+                        $row->[0], $node_score, $row->[1], $row->[4] );
27b8ba
+                }
27b8ba
+                _set_master_score( $row->[1], $row->[0] );
27b8ba
+            }
27b8ba
+            else {
27b8ba
+                ocf_log( 'debug',
27b8ba
+                    '_check_locations: "%s" keeps its current score of %s',
27b8ba
+                    $row->[0], $row->[1] );
27b8ba
+            }
27b8ba
+        }
27b8ba
+
27b8ba
+        # Remove this node from the known nodes list.
27b8ba
+        $partition_nodes =~ s/(?:^|\s)$row->[0](?:\s|$)/ /g;
27b8ba
+    }
27b8ba
+
27b8ba
+    $partition_nodes =~ s/(?:^\s+)|(?:\s+$)//g;
27b8ba
+
27b8ba
+    # If there are still nodes in "partition_nodes", it means there is no
27b8ba
+    # corresponding line in "pg_stat_replication".
27b8ba
+    # Exclude these nodes that are not part of the cluster at this
27b8ba
+    # point.
27b8ba
+    foreach my $node (split /\s+/ => $partition_nodes) {
27b8ba
+        # Exclude the current node.
27b8ba
+        next if $node eq $nodename;
27b8ba
+
27b8ba
+        # do not warn if the master score is already set to -1000.
27b8ba
+        # this avoid log flooding (gh #138)
27b8ba
+        $node_score = _get_master_score( $node );
27b8ba
+        next if $node_score eq '-1000';
27b8ba
+
27b8ba
+        ocf_log( 'warning', '"%s" is not connected to the primary', $node );
27b8ba
+        _set_master_score( '-1000', $node );
27b8ba
+    }
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+# _check_switchover
27b8ba
+# check if the pgsql switchover to the localnode is safe.
27b8ba
+# This is supposed to be called **after** the master has been stopped or demoted.
27b8ba
+# This sub checks if the local standby received the shutdown checkpoint from the
27b8ba
+# old master to make sure it can take over the master role and the old master
27b8ba
+# will be able to catchup as a standby after.
27b8ba
+#
27b8ba
+# Returns 0 if switchover is safe
27b8ba
+# Returns 1 if swithcover is not safe
27b8ba
+# Returns 2 for internal error
27b8ba
+sub _check_switchover {
27b8ba
+    my $has_sht_chk = 0;
27b8ba
+    my $last_redo;
27b8ba
+    my $last_lsn;
27b8ba
+    my $ans;
27b8ba
+    my $rc;
27b8ba
+    my $tl;
27b8ba
+    my %cdata;
27b8ba
+
27b8ba
+    $PGWALDUMP = "$bindir/pg_xlogdump" if $PGVERNUM < $PGVER_10;
27b8ba
+
27b8ba
+    ocf_log( 'info', 'Switchover in progress from "%s" to "%s".'
27b8ba
+        .' Need to check the last record in WAL',
27b8ba
+        $OCF_NOTIFY_ENV{'demote'}[0]{'uname'}, $nodename );
27b8ba
+
27b8ba
+    # check if we received the shutdown checkpoint of the master during its
27b8ba
+    # demote process.
27b8ba
+    # We need the last local checkpoint LSN and the last received LSN from
27b8ba
+    # master to check in the WAL between these adresses if we have a
27b8ba
+    # "checkpoint shutdown" using pg_xlogdump/pg_waldump.
27b8ba
+    #
27b8ba
+    # Force a checkpoint to make sure the controldata shows the very last TL
27b8ba
+    # and the master's shutdown checkpoint
27b8ba
+    _query( q{ CHECKPOINT }, {} );
27b8ba
+    %cdata     = _get_controldata();
27b8ba
+    $tl        = $cdata{'tl'};
27b8ba
+    $last_redo = $cdata{'redo'};
27b8ba
+
27b8ba
+    # Get the last received LSN from master
27b8ba
+    $last_lsn = _get_last_received_lsn();
27b8ba
+
27b8ba
+    unless ( defined $last_lsn ) {
27b8ba
+        ocf_exit_reason( 'Could not fetch last received LSN!' );
27b8ba
+
27b8ba
+        return 2;
27b8ba
+    }
27b8ba
+
27b8ba
+    $ans = qx{ $PGWALDUMP --path "$datadir" --timeline "$tl" \\
27b8ba
+               --start "$last_redo" --end "$last_lsn" 2>&1 };
27b8ba
+    $rc = $?;
27b8ba
+
27b8ba
+    ocf_log( 'debug',
27b8ba
+        '_check_switchover: %s rc: "%s", tl: "%s", last_chk: %s, last_lsn: %s, output: "%s"',
27b8ba
+        $PGWALDUMP, $rc, $tl, $last_redo, $last_lsn, $ans
27b8ba
+    );
27b8ba
+
27b8ba
+    if ( $rc == 0 and
27b8ba
+         $ans =~ m{^rmgr: XLOG.*desc: (?i:checkpoint)(?::|_SHUTDOWN) redo [0-9A-F/]+; tli $tl;.*; shutdown$}m
27b8ba
+    ) {
27b8ba
+        ocf_log( 'info', 'Slave received the shutdown checkpoint' );
27b8ba
+        return 0;
27b8ba
+    }
27b8ba
+
27b8ba
+    ocf_exit_reason(
27b8ba
+        'Did not receive the shutdown checkpoint from the old master!' );
27b8ba
+
27b8ba
+    return 1;
27b8ba
+}
27b8ba
+
27b8ba
+# Check to confirm if the instance is really started as _pg_isready stated and
27b8ba
+# check if the instance is primary or secondary.
27b8ba
+#
27b8ba
+sub _confirm_role {
27b8ba
+    my $is_in_recovery;
27b8ba
+    my $rc;
27b8ba
+    my @rs;
27b8ba
+
27b8ba
+    $rc = _query( "SELECT pg_is_in_recovery()", \@rs );
27b8ba
+
27b8ba
+    $is_in_recovery = $rs[0][0];
27b8ba
+
27b8ba
+    if ( $rc == 0 ) {
27b8ba
+        # The query was executed, check the result.
27b8ba
+        if ( $is_in_recovery eq 't' ) {
27b8ba
+            # The instance is a secondary.
27b8ba
+            ocf_log( 'debug', "_confirm_role: instance $OCF_RESOURCE_INSTANCE is a secondary");
27b8ba
+            return $OCF_SUCCESS;
27b8ba
+        }
27b8ba
+        elsif ( $is_in_recovery eq 'f' ) {
27b8ba
+            # The instance is a primary.
27b8ba
+            ocf_log( 'debug', "_confirm_role: instance $OCF_RESOURCE_INSTANCE is a primary");
27b8ba
+            # Check lsn diff with current slaves if any
27b8ba
+            _check_locations() if $__OCF_ACTION eq 'monitor';
27b8ba
+            return $OCF_RUNNING_MASTER;
27b8ba
+        }
27b8ba
+
27b8ba
+        # This should not happen, raise a hard configuration error.
27b8ba
+        ocf_exit_reason(
27b8ba
+            'Unexpected result from query to check if "%s" is a primary or a secondary: "%s"',
27b8ba
+            $OCF_RESOURCE_INSTANCE, $is_in_recovery );
27b8ba
+
27b8ba
+        return $OCF_ERR_CONFIGURED;
27b8ba
+    }
27b8ba
+    elsif ( $rc == 1 or $rc == 2 ) {
27b8ba
+        # psql cound not connect to the instance.
27b8ba
+        # As pg_isready reported the instance was listening, this error
27b8ba
+        # could be a max_connection saturation. Just report a soft error.
27b8ba
+        ocf_exit_reason( 'psql could not connect to instance "%s"',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    # The query failed (rc: 3) or bad parameters (rc: -1).
27b8ba
+    # This should not happen, raise a hard configuration error.
27b8ba
+    ocf_exit_reason(
27b8ba
+        'The query to check if instance "%s" is a primary or a secondary failed (rc: %d)',
27b8ba
+        $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+
27b8ba
+    return $OCF_ERR_CONFIGURED;
27b8ba
+}
27b8ba
+
27b8ba
+
27b8ba
+# Check to confirm if the instance is really stopped as _pg_isready stated
27b8ba
+# and if it was propertly shut down.
27b8ba
+#
27b8ba
+sub _confirm_stopped {
27b8ba
+    my $pgctlstatus_rc;
27b8ba
+    my $controldata_rc;
27b8ba
+
27b8ba
+    # Check the postmaster process status.
27b8ba
+    $pgctlstatus_rc = _pg_ctl_status();
27b8ba
+
27b8ba
+    if ( $pgctlstatus_rc == 0 ) {
27b8ba
+        # The PID file exists and the process is available.
27b8ba
+        # That should not be the case, return an error.
27b8ba
+        ocf_exit_reason(
27b8ba
+            'Instance "%s" is not listening, but the process referenced in postmaster.pid exists',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    # The PID file does not exist or the process is not available.
27b8ba
+    ocf_log( 'debug',
27b8ba
+        '_confirm_stopped: no postmaster process found for instance "%s"',
27b8ba
+        $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+    if ( -f "$datadir/backup_label" ) {
27b8ba
+        # We are probably on a freshly built secondary that was not started yet.
27b8ba
+        ocf_log( 'debug',
27b8ba
+            '_confirm_stopped: backup_label file exists: probably on a never started secondary',
27b8ba
+        );
27b8ba
+        return $OCF_NOT_RUNNING;
27b8ba
+    }
27b8ba
+
27b8ba
+    # Continue the check with pg_controldata.
27b8ba
+    $controldata_rc = _controldata_to_ocf();
27b8ba
+    if ( $controldata_rc == $OCF_RUNNING_MASTER ) {
27b8ba
+        # The controldata has not been updated to "shutdown".
27b8ba
+        # It should mean we had a crash on a primary instance.
27b8ba
+        ocf_exit_reason(
27b8ba
+            'Instance "%s" controldata indicates a running primary instance, the instance has probably crashed',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_FAILED_MASTER;
27b8ba
+    }
27b8ba
+    elsif ( $controldata_rc == $OCF_SUCCESS ) {
27b8ba
+        # The controldata has not been updated to "shutdown in recovery".
27b8ba
+        # It should mean we had a crash on a secondary instance.
27b8ba
+        # There is no "FAILED_SLAVE" return code, so we return a generic error.
27b8ba
+        ocf_exit_reason(
27b8ba
+            'Instance "%s" controldata indicates a running secondary instance, the instance has probably crashed',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+    elsif ( $controldata_rc == $OCF_NOT_RUNNING ) {
27b8ba
+        # The controldata state is consistent, the instance was probably
27b8ba
+        # propertly shut down.
27b8ba
+        ocf_log( 'debug',
27b8ba
+            '_confirm_stopped: instance "%s" controldata indicates that the instance was propertly shut down',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_NOT_RUNNING;
27b8ba
+    }
27b8ba
+
27b8ba
+    # Something went wrong with the controldata check.
27b8ba
+    ocf_exit_reason(
27b8ba
+        'Could not get instance "%s" status from controldata (returned: %d)',
27b8ba
+        $OCF_RESOURCE_INSTANCE, $controldata_rc );
27b8ba
+
27b8ba
+    return $OCF_ERR_GENERIC;
27b8ba
+}
27b8ba
+
27b8ba
+############################################################
27b8ba
+#### OCF FUNCS
27b8ba
+
27b8ba
+
27b8ba
+
27b8ba
+=head1 SUPPORTED PARAMETERS
27b8ba
+
27b8ba
+=over
27b8ba
+
27b8ba
+=item B<pgdata>
27b8ba
+
27b8ba
+Location of the PGDATA of your instance
27b8ba
+
27b8ba
+(optional, string, default "/var/lib/pgsql/data")
27b8ba
+
27b8ba
+=item B<pghost>
27b8ba
+
27b8ba
+The socket directory or IP address to use to connect to the local instance
27b8ba
+
27b8ba
+(optional, string, default "/tmp")
27b8ba
+
27b8ba
+=item B<pgport>
27b8ba
+
27b8ba
+The port to connect to the local instance
27b8ba
+
27b8ba
+(optional, integer, default "5432")
27b8ba
+
27b8ba
+=item B<bindir>
27b8ba
+
27b8ba
+Location of the PostgreSQL binaries.
27b8ba
+
27b8ba
+(optional, string, default "/usr/bin")
27b8ba
+
27b8ba
+=item B<system_user>
27b8ba
+
27b8ba
+The system owner of your instance's process
27b8ba
+
27b8ba
+(optional, string, default "postgres")
27b8ba
+
27b8ba
+=item B<recovery_template>
27b8ba
+
27b8ba
+B<ONLY> for PostgreSQL 11 and bellow.
27b8ba
+
27b8ba
+The local template that will be copied as the C<PGDATA/recovery.conf> file.
27b8ba
+This template file must exists on all node.
27b8ba
+
27b8ba
+With PostgreSQL 12 and higher, the cluster will refuse to start if this
27b8ba
+parameter is set or a template file is found.
27b8ba
+
27b8ba
+(optional, string, default "$PGDATA/recovery.conf.pcmk")
27b8ba
+
27b8ba
+=item B<maxlag>
27b8ba
+
27b8ba
+Maximum lag allowed on a standby before we set a negative master score on it.
27b8ba
+The calculation is based on the difference between the current xlog location on
27b8ba
+the master and the write location on the standby.
27b8ba
+
27b8ba
+(optional, integer, default "0" disables this feature)
27b8ba
+
27b8ba
+=item B<datadir>
27b8ba
+
27b8ba
+Path to the directory set in C<data_directory> from your postgresql.conf file.
27b8ba
+This parameter has same default than PostgreSQL itself: the C<pgdata> parameter
27b8ba
+value.
27b8ba
+
27b8ba
+Unless you have a special PostgreSQL setup and you understand this parameter,
27b8ba
+B<ignore it>
27b8ba
+
27b8ba
+(optional, string, default to the value of C<pgdata>)
27b8ba
+
27b8ba
+=item B<start_opts>
27b8ba
+
27b8ba
+Additional arguments given to the postgres process on startup. See
27b8ba
+"postgres --help" for available options. Useful when the postgresql.conf file
27b8ba
+is not in the data directory (PGDATA), eg.:
27b8ba
+
27b8ba
+  -c config_file=/etc/postgresql/9.3/main/postgresql.conf
27b8ba
+
27b8ba
+(optinal, string, default "")
27b8ba
+
27b8ba
+=back
27b8ba
+
27b8ba
+=cut
27b8ba
+
27b8ba
+sub ocf_meta_data {
27b8ba
+    print qq{
27b8ba
+        
27b8ba
+        <resource-agent name="pgsqlms">
27b8ba
+          <version>1.0</version>
27b8ba
+
27b8ba
+          <longdesc lang="en">
27b8ba
+            Resource script for PostgreSQL in replication. It manages PostgreSQL servers using streaming replication as an HA resource.
27b8ba
+          </longdesc>
27b8ba
+          <shortdesc lang="en">Manages PostgreSQL servers in replication</shortdesc>
27b8ba
+          <parameters>
27b8ba
+            <parameter name="system_user" unique="0" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                System user account used to run the PostgreSQL server
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">PostgreSQL system User</shortdesc>
27b8ba
+              <content type="string" default="$system_user_default" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+            <parameter name="bindir" unique="0" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Path to the directory storing the PostgreSQL binaries. The agent uses psql, pg_isready, pg_controldata and pg_ctl.
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Path to the PostgreSQL binaries</shortdesc>
27b8ba
+              <content type="string" default="$bindir_default" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+            <parameter name="pgdata" unique="1" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Path to the data directory, e.g. PGDATA
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Path to the data directory</shortdesc>
27b8ba
+              <content type="string" default="$pgdata_default" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+            <parameter name="datadir" unique="1" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Path to the directory set in data_directory from your postgresql.conf file. This parameter
27b8ba
+                has the same default than PostgreSQL itself: the pgdata parameter value. Unless you have a
27b8ba
+                special PostgreSQL setup and you understand this parameter, ignore it.
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Path to the directory set in data_directory from your postgresql.conf file</shortdesc>
27b8ba
+              <content type="string" default="PGDATA" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+            <parameter name="pghost" unique="0" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Host IP address or unix socket folder the instance is listening on.
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Instance IP or unix socket folder</shortdesc>
27b8ba
+              <content type="string" default="$pghost_default" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+            <parameter name="pgport" unique="0" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Port the instance is listening on.
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Instance port</shortdesc>
27b8ba
+              <content type="integer" default="$pgport_default" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+           <parameter name="maxlag" unique="0" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Maximum lag allowed on a standby before we set a negative master score on it. The calculation
27b8ba
+                is based on the difference between the current LSN on the master and the LSN
27b8ba
+                written on the standby.
27b8ba
+                This parameter must be a valid positive number as described in PostgreSQL documentation.
27b8ba
+                See: https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS-NUMERIC
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Maximum write lag before we mark a standby as inappropriate to promote</shortdesc>
27b8ba
+              <content type="integer" default="$maxlag_default" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+            <parameter name="recovery_template" unique="1" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Path to the recovery.conf template. This file is simply copied to \$PGDATA
27b8ba
+                before starting the instance as slave.
27b8ba
+                ONLY for PostgreSQL 11 and bellow. This parameter is IGNORED for
27b8ba
+                PostgreSQL 12 and higher. The cluster will refuse to start if a template
27b8ba
+                file is found.
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Path to the recovery.conf template for PostgreSQL 11 and older.</shortdesc>
27b8ba
+              <content type="string" default="PGDATA/recovery.conf.pcmk" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+            <parameter name="start_opts" unique="0" required="0">
27b8ba
+              <longdesc lang="en">
27b8ba
+                Additionnal arguments given to the postgres process on startup.
27b8ba
+                See "postgres --help" for available options. Usefull when the
27b8ba
+                postgresql.conf file is not in the data directory (PGDATA), eg.:
27b8ba
+                "-c config_file=/etc/postgresql/9.3/main/postgresql.conf".
27b8ba
+              </longdesc>
27b8ba
+              <shortdesc lang="en">Additionnal arguments given to the postgres process on startup.</shortdesc>
27b8ba
+              <content type="string" default="$start_opts_default" />
27b8ba
+            </parameter>
27b8ba
+
27b8ba
+          </parameters>
27b8ba
+          <actions>
27b8ba
+            <action name="start" timeout="60" />
27b8ba
+            <action name="stop" timeout="60" />
27b8ba
+            <action name="reload" timeout="20" />
27b8ba
+            <action name="promote" timeout="30" />
27b8ba
+            <action name="demote" timeout="120" />
27b8ba
+            <action name="monitor" depth="0" timeout="10" interval="15"/>
27b8ba
+            <action name="monitor" depth="0" timeout="10" interval="15" role="Master"/>
27b8ba
+            <action name="monitor" depth="0" timeout="10" interval="16" role="Slave"/>
27b8ba
+            <action name="notify" timeout="60" />
27b8ba
+            <action name="meta-data" timeout="5" />
27b8ba
+            <action name="validate-all" timeout="5" />
27b8ba
+            <action name="methods" timeout="5" />
27b8ba
+          </actions>
27b8ba
+        </resource-agent>
27b8ba
+    };
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+
27b8ba
+=head1 SUPPORTED ACTIONS
27b8ba
+
27b8ba
+This resource agent supports the following actions (operations):
27b8ba
+
27b8ba
+=over
27b8ba
+
27b8ba
+=item B<start>
27b8ba
+
27b8ba
+Starts the resource. Suggested minimum timeout: 60.
27b8ba
+
27b8ba
+=item B<stop>
27b8ba
+
27b8ba
+Stops the resource. Suggested minimum timeout: 60.
27b8ba
+
27b8ba
+=item B<reload>
27b8ba
+
27b8ba
+Suggested minimum timeout: 20.
27b8ba
+
27b8ba
+=item B<promote>
27b8ba
+
27b8ba
+Promotes the resource to the Master role. Suggested minimum timeout: 30.
27b8ba
+
27b8ba
+=item B<demote>
27b8ba
+
27b8ba
+Demotes the resource to the Slave role. Suggested minimum timeout: 120.
27b8ba
+
27b8ba
+=item B<monitor (Master role)>
27b8ba
+
27b8ba
+Performs a detailed status check. Suggested minimum timeout: 10.
27b8ba
+Suggested interval: 15.
27b8ba
+
27b8ba
+=item B<monitor (Slave role)>
27b8ba
+
27b8ba
+Performs a detailed status check. Suggested minimum timeout: 10.
27b8ba
+Suggested interval: 16.
27b8ba
+
27b8ba
+=item B<notify>
27b8ba
+
27b8ba
+Suggested minimum timeout: 60
27b8ba
+
27b8ba
+=item B<meta-data>
27b8ba
+
27b8ba
+Retrieves resource agent metadata (internal use only).
27b8ba
+Suggested minimum timeout: 5.
27b8ba
+
27b8ba
+=item B<methods>
27b8ba
+
27b8ba
+Suggested minimum timeout: 5.
27b8ba
+
27b8ba
+=item B<validate-all>
27b8ba
+
27b8ba
+Performs a validation of the resource configuration.
27b8ba
+Suggested minimum timeout: 5.
27b8ba
+
27b8ba
+=back
27b8ba
+
27b8ba
+=cut
27b8ba
+
27b8ba
+sub ocf_methods {
27b8ba
+    print q{
27b8ba
+        start
27b8ba
+        stop
27b8ba
+        reload
27b8ba
+        promote
27b8ba
+        demote
27b8ba
+        monitor
27b8ba
+        notify
27b8ba
+        methods
27b8ba
+        meta-data
27b8ba
+        validate-all
27b8ba
+    };
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+############################################################
27b8ba
+#### RA FUNCS
27b8ba
+
27b8ba
+sub pgsql_validate_all {
27b8ba
+    my $fh;
27b8ba
+    my $ans = '';
27b8ba
+    my %cdata;
27b8ba
+
27b8ba
+    unless (
27b8ba
+        ocf_version_cmp( $ENV{"OCF_RESKEY_crm_feature_set"}, '3.0.9' ) == 2
27b8ba
+    ) {
27b8ba
+        ocf_exit_reason(
27b8ba
+            'PAF %s is compatible with Pacemaker 1.1.13 and greater',
27b8ba
+            $VERSION
27b8ba
+        );
27b8ba
+        return $OCF_ERR_INSTALLED;
27b8ba
+    }
27b8ba
+
27b8ba
+    # check notify=true
27b8ba
+    $ans = qx{ $CRM_RESOURCE --resource "$OCF_RESOURCE_INSTANCE" \\
27b8ba
+                 --meta --get-parameter notify 2>/dev/null };
27b8ba
+    chomp $ans;
27b8ba
+    unless ( lc($ans) =~ /^true$|^on$|^yes$|^y$|^1$/ ) {
27b8ba
+        ocf_exit_reason(
27b8ba
+            'You must set meta parameter notify=true for your master resource'
27b8ba
+        );
27b8ba
+        return $OCF_ERR_INSTALLED;
27b8ba
+    }
27b8ba
+
27b8ba
+    # check master-max=1
27b8ba
+    unless (
27b8ba
+        defined $ENV{'OCF_RESKEY_CRM_meta_master_max'}
27b8ba
+            and $ENV{'OCF_RESKEY_CRM_meta_master_max'} eq '1'
27b8ba
+    ) {
27b8ba
+        ocf_exit_reason(
27b8ba
+            'You must set meta parameter master-max=1 for your master resource'
27b8ba
+        );
27b8ba
+        return $OCF_ERR_INSTALLED;
27b8ba
+    }
27b8ba
+
27b8ba
+    if ( $PGVERNUM >= $PGVER_12 ) {
27b8ba
+        # check PostgreSQL setup: checks related to v12 and after
27b8ba
+        my $guc;
27b8ba
+
27b8ba
+        # recovery.conf template must not exists
27b8ba
+        if ( -f $recovery_tpl ) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                'Recovery template file "%s" is forbidden for PostgreSQL 12 and above',
27b8ba
+                $recovery_tpl );
27b8ba
+            exit $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+
27b8ba
+        # WARNING: you MUST put -C as first argument to bypass the root check
27b8ba
+        $guc = qx{ $POSTGRES -C recovery_target_timeline -D "$pgdata" $start_opts};
27b8ba
+        chomp $guc;
27b8ba
+        unless ( $guc eq 'latest' ) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                q{Parameter "recovery_target_timeline" MUST be set to 'latest'. } .
27b8ba
+                q{It is currently set to '%s'}, $guc );
27b8ba
+            return $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+
27b8ba
+        $guc = qx{ $POSTGRES -C primary_conninfo -D "$pgdata" $start_opts};
27b8ba
+        unless ($guc =~ /\bapplication_name='?$nodename'?\b/) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                q{Parameter "primary_conninfo" MUST contain 'application_name=%s'. }.
27b8ba
+                q{It is currently set to '%s'}, $nodename, $guc );
27b8ba
+            return $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+    }
27b8ba
+    else {
27b8ba
+        my @content;
27b8ba
+
27b8ba
+        # check recovery template
27b8ba
+        if ( ! -f $recovery_tpl ) {
27b8ba
+            ocf_exit_reason( 'Recovery template file "%s" does not exist',
27b8ba
+                $recovery_tpl );
27b8ba
+            return $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+
27b8ba
+        # check content of the recovery template file
27b8ba
+        unless ( open( $fh, '<', $recovery_tpl ) ) {
27b8ba
+            ocf_exit_reason( 'Could not open file "%s": %s', $recovery_tpl, $! );
27b8ba
+            return $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+        @content = <$fh>;
27b8ba
+        close $fh;
27b8ba
+
27b8ba
+
27b8ba
+        unless ( grep /^\s*standby_mode\s*=\s*'?on'?\s*$/, @content ) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                'Recovery template file must contain "standby_mode = on"' );
27b8ba
+            return $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+
27b8ba
+        unless ( grep /^\s*recovery_target_timeline\s*=\s*'?latest'?\s*$/, @content ) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                "Recovery template file must contain \"recovery_target_timeline = 'latest'\""
27b8ba
+            );
27b8ba
+            return $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+
27b8ba
+        unless (
27b8ba
+            grep /^\s*primary_conninfo\s*=.*['\s]application_name=$nodename['\s]/,
27b8ba
+            @content
27b8ba
+        ) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                'Recovery template file must contain in primary_conninfo parameter "application_name=%s"',
27b8ba
+                $nodename );
27b8ba
+            return $OCF_ERR_ARGS;
27b8ba
+        }
27b8ba
+    }
27b8ba
+
27b8ba
+    unless ( looks_like_number($maxlag) ) {
27b8ba
+        ocf_exit_reason( 'maxlag is not a number: "%s"', $maxlag );
27b8ba
+        return $OCF_ERR_INSTALLED;
27b8ba
+    }
27b8ba
+
27b8ba
+    # check system user
27b8ba
+    unless ( defined getpwnam $system_user ) {
27b8ba
+        ocf_exit_reason( 'System user "%s" does not exist', $system_user );
27b8ba
+        return $OCF_ERR_ARGS;
27b8ba
+    }
27b8ba
+
27b8ba
+    # require 9.3 minimum
27b8ba
+    if ( $PGVERNUM < $PGVER_93 ) {
27b8ba
+        ocf_exit_reason( "Require 9.3 and more" );
27b8ba
+        return $OCF_ERR_INSTALLED;
27b8ba
+    }
27b8ba
+
27b8ba
+    # check binaries
27b8ba
+    unless ( -x $PGCTL and -x $PGPSQL and -x $PGCTRLDATA and -x $PGISREADY
27b8ba
+         and ( -x $PGWALDUMP or -x "$bindir/pg_xlogdump")
27b8ba
+     ) {
27b8ba
+        ocf_exit_reason(
27b8ba
+            "Missing one or more binary. Check following path: %s, %s, %s, %s, %s or %s",
27b8ba
+            $PGCTL, $PGPSQL, $PGCTRLDATA, $PGISREADY, $PGWALDUMP, "$bindir/pg_xlogdump" );
27b8ba
+        return $OCF_ERR_ARGS;
27b8ba
+    }
27b8ba
+
27b8ba
+    # require wal_level >= hot_standby
27b8ba
+    %cdata = _get_controldata();
27b8ba
+    unless ( $cdata{'wal_level'} =~ m{hot_standby|logical|replica} ) {
27b8ba
+        ocf_exit_reason(
27b8ba
+            'wal_level must be one of "hot_standby", "logical" or "replica"' );
27b8ba
+        return $OCF_ERR_ARGS;
27b8ba
+    }
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+
27b8ba
+# Start the PostgreSQL instance as a *secondary*
27b8ba
+#
27b8ba
+sub pgsql_start {
27b8ba
+    my $rc         = pgsql_monitor();
27b8ba
+    my %cdata      = _get_controldata();
27b8ba
+    my $prev_state = $cdata{'state'};
27b8ba
+
27b8ba
+    # Instance must be running as secondary or being stopped.
27b8ba
+    # Anything else is an error.
27b8ba
+    if ( $rc == $OCF_SUCCESS ) {
27b8ba
+        ocf_log( 'info', 'Instance "%s" already started',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+    elsif ( $rc != $OCF_NOT_RUNNING ) {
27b8ba
+        ocf_exit_reason( 'Unexpected state for instance "%s" (returned %d)',
27b8ba
+            $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    #
27b8ba
+    # From here, the instance is NOT running for sure.
27b8ba
+    #
27b8ba
+
27b8ba
+    ocf_log( 'debug',
27b8ba
+        'pgsql_start: instance "%s" is not running, starting it as a secondary',
27b8ba
+        $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+    # Must start as a standby, so enable recovery.
27b8ba
+    _enable_recovery();
27b8ba
+
27b8ba
+    # Start the instance as a secondary.
27b8ba
+    $rc = _pg_ctl_start();
27b8ba
+
27b8ba
+    if ( $rc == 0 ) {
27b8ba
+
27b8ba
+        # Wait for the start to finish.
27b8ba
+        sleep 1 while ( $rc = pgsql_monitor() ) == $OCF_NOT_RUNNING;
27b8ba
+
27b8ba
+        if ( $rc == $OCF_SUCCESS ) {
27b8ba
+            ocf_log( 'info', 'Instance "%s" started', $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+            # Check if a master score exists in the cluster.
27b8ba
+            # During the very first start of the cluster, no master score will
27b8ba
+            # exists on any of the existing slaves, unless an admin designated
27b8ba
+            # one of them using crm_master. If no master exists the cluster will
27b8ba
+            # not promote a master among the slaves.
27b8ba
+            # To solve this situation, we check if there is at least one master
27b8ba
+            # score existing on one node in the cluster. Do nothing if at least
27b8ba
+            # one master score is found among the clones of the resource. If no
27b8ba
+            # master score exists, set a score of 1 only if the resource was a
27b8ba
+            # shut downed master before the start.
27b8ba
+            if ( $prev_state eq "shut down" and not _master_score_exists() ) {
27b8ba
+                ocf_log( 'info', 'No master score around. Set mine to 1' );
27b8ba
+
27b8ba
+                _set_master_score( '1' );
27b8ba
+            }
27b8ba
+
27b8ba
+            return $OCF_SUCCESS;
27b8ba
+        }
27b8ba
+
27b8ba
+        ocf_exit_reason(
27b8ba
+            'Instance "%s" is not running as a slave (returned %d)',
27b8ba
+             $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    ocf_exit_reason( 'Instance "%s" failed to start (rc: %d)',
27b8ba
+        $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+
27b8ba
+    return $OCF_ERR_GENERIC;
27b8ba
+}
27b8ba
+
27b8ba
+# Stop the PostgreSQL instance
27b8ba
+#
27b8ba
+sub pgsql_stop {
27b8ba
+    my $rc;
27b8ba
+    my $state;
27b8ba
+    my $pidfile = "$datadir/postmaster.pid";
27b8ba
+    # Add 60s to the timeout or use a 24h timeout fallback to make sure
27b8ba
+    # Pacemaker will give up before us and take decisions
27b8ba
+    my $timeout = ( _get_action_timeout() || 60*60*24 ) + 60;
27b8ba
+
27b8ba
+    # Instance must be running as secondary or primary or being stopped.
27b8ba
+    # Anything else is an error.
27b8ba
+    $rc = pgsql_monitor();
27b8ba
+    if ( $rc == $OCF_NOT_RUNNING ) {
27b8ba
+        ocf_log( 'info', 'Instance "%s" already stopped',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+    elsif ( $rc != $OCF_SUCCESS and $rc != $OCF_RUNNING_MASTER ) {
27b8ba
+        ocf_exit_reason( 'Unexpected state for instance "%s" (returned %d)',
27b8ba
+            $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    #
27b8ba
+    # From here, the instance is running for sure.
27b8ba
+    #
27b8ba
+
27b8ba
+    ocf_log( 'debug', 'pgsql_stop: instance "%s" is running, stopping it',
27b8ba
+        $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+    # Try to quit with proper shutdown.
27b8ba
+
27b8ba
+
27b8ba
+    $rc = _runas( $PGCTL, '--pgdata', $pgdata, '-w', '--timeout', $timeout,
27b8ba
+        '-m', 'fast', 'stop' );
27b8ba
+
27b8ba
+    if ( $rc == 0 ) {
27b8ba
+        # Wait for the stop to finish.
27b8ba
+        sleep 1 while ( $rc = pgsql_monitor() ) != $OCF_NOT_RUNNING ;
27b8ba
+
27b8ba
+        ocf_log( 'info', 'Instance "%s" stopped', $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+        return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+
27b8ba
+    ocf_exit_reason( 'Instance "%s" failed to stop', $OCF_RESOURCE_INSTANCE );
27b8ba
+    return $OCF_ERR_GENERIC;
27b8ba
+}
27b8ba
+
27b8ba
+# Monitor the PostgreSQL instance
27b8ba
+#
27b8ba
+sub pgsql_monitor {
27b8ba
+    my $pgisready_rc;
27b8ba
+    my $controldata_rc;
27b8ba
+
27b8ba
+    ocf_log( 'debug', 'pgsql_monitor: monitor is a probe' ) if ocf_is_probe();
27b8ba
+
27b8ba
+    # First check, verify if the instance is listening.
27b8ba
+    $pgisready_rc = _pg_isready();
27b8ba
+
27b8ba
+    if ( $pgisready_rc == 0 ) {
27b8ba
+        # The instance is listening.
27b8ba
+        # We confirm that the instance is up and return if it is a primary or a
27b8ba
+        # secondary
27b8ba
+        ocf_log( 'debug', 'pgsql_monitor: instance "%s" is listening',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return _confirm_role();
27b8ba
+    }
27b8ba
+
27b8ba
+    if ( $pgisready_rc == 1 ) {
27b8ba
+        # The attempt was rejected.
27b8ba
+        # This could happen in several cases:
27b8ba
+        #   - at startup
27b8ba
+        #   - during shutdown
27b8ba
+        #   - during crash recovery
27b8ba
+        #   - if instance is a warm standby
27b8ba
+        # Except for the warm standby case, this should be a transitional state.
27b8ba
+        # We try to confirm using pg_controldata.
27b8ba
+        ocf_log( 'debug',
27b8ba
+            'pgsql_monitor: instance "%s" rejects connections - checking again...',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        $controldata_rc = _controldata_to_ocf();
27b8ba
+
27b8ba
+        if ( $controldata_rc == $OCF_RUNNING_MASTER
27b8ba
+            or $controldata_rc == $OCF_SUCCESS
27b8ba
+        ) {
27b8ba
+            # This state indicates that pg_isready check should succeed.
27b8ba
+            # We check again.
27b8ba
+            ocf_log( 'debug',
27b8ba
+                'pgsql_monitor: instance "%s" controldata shows a running status',
27b8ba
+                $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+            $pgisready_rc = _pg_isready();
27b8ba
+            if ( $pgisready_rc == 0 ) {
27b8ba
+                # Consistent with pg_controdata output.
27b8ba
+                # We can check if the instance is primary or secondary
27b8ba
+                ocf_log( 'debug', 'pgsql_monitor: instance "%s" is listening',
27b8ba
+                    $OCF_RESOURCE_INSTANCE );
27b8ba
+                return _confirm_role();
27b8ba
+            }
27b8ba
+
27b8ba
+            # Still not consistent, raise an error.
27b8ba
+            # NOTE: if the instance is a warm standby, we end here.
27b8ba
+            # TODO raise an hard error here ?
27b8ba
+            ocf_exit_reason(
27b8ba
+                'Instance "%s" controldata is not consistent with pg_isready (returned: %d)',
27b8ba
+                $OCF_RESOURCE_INSTANCE, $pgisready_rc );
27b8ba
+            ocf_log( 'info',
27b8ba
+                'If this instance is in warm standby, this resource agent only supports hot standby',
27b8ba
+                $OCF_RESOURCE_INSTANCE, $pgisready_rc );
27b8ba
+
27b8ba
+            return $OCF_ERR_GENERIC;
27b8ba
+        }
27b8ba
+
27b8ba
+        if ( $controldata_rc == $OCF_NOT_RUNNING ) {
27b8ba
+            # This state indicates that pg_isready check should fail with rc 2.
27b8ba
+            # We check again.
27b8ba
+            $pgisready_rc = _pg_isready();
27b8ba
+            if ( $pgisready_rc == 2 ) {
27b8ba
+                # Consistent with pg_controdata output.
27b8ba
+                # We check the process status using pg_ctl status and check
27b8ba
+                # if it was propertly shut down using pg_controldata.
27b8ba
+                ocf_log( 'debug',
27b8ba
+                    'pgsql_monitor: instance "%s" is not listening',
27b8ba
+                    $OCF_RESOURCE_INSTANCE );
27b8ba
+                return _confirm_stopped();
27b8ba
+            }
27b8ba
+            # Still not consistent, raise an error.
27b8ba
+            # TODO raise an hard error here ?
27b8ba
+            ocf_exit_reason(
27b8ba
+                'Instance "%s" controldata is not consistent with pg_isready (returned: %d)',
27b8ba
+                $OCF_RESOURCE_INSTANCE, $pgisready_rc );
27b8ba
+
27b8ba
+            return $OCF_ERR_GENERIC;
27b8ba
+        }
27b8ba
+
27b8ba
+        # Something went wrong with the controldata check, hard fail.
27b8ba
+        ocf_exit_reason(
27b8ba
+            'Could not get instance "%s" status from controldata (returned: %d)',
27b8ba
+            $OCF_RESOURCE_INSTANCE, $controldata_rc );
27b8ba
+
27b8ba
+        return $OCF_ERR_INSTALLED;
27b8ba
+    }
27b8ba
+
27b8ba
+    elsif ( $pgisready_rc == 2 ) {
27b8ba
+        # The instance is not listening.
27b8ba
+        # We check the process status using pg_ctl status and check
27b8ba
+        # if it was propertly shut down using pg_controldata.
27b8ba
+        ocf_log( 'debug', 'pgsql_monitor: instance "%s" is not listening',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return _confirm_stopped();
27b8ba
+    }
27b8ba
+
27b8ba
+    elsif ( $pgisready_rc == 3 ) {
27b8ba
+        # No attempt was done, probably a syntax error.
27b8ba
+        # Hard configuration error, we don't want to retry or failover here.
27b8ba
+        ocf_exit_reason(
27b8ba
+            'Unknown error while checking if instance "%s" is listening (returned %d)',
27b8ba
+            $OCF_RESOURCE_INSTANCE, $pgisready_rc );
27b8ba
+
27b8ba
+        return $OCF_ERR_CONFIGURED;
27b8ba
+    }
27b8ba
+
27b8ba
+    ocf_exit_reason( 'Unexpected result when checking instance "%s" status',
27b8ba
+        $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+    return $OCF_ERR_GENERIC;
27b8ba
+}
27b8ba
+
27b8ba
+
27b8ba
+# Demote the PostgreSQL instance from primary to secondary
27b8ba
+# To demote a PostgreSQL instance, we must:
27b8ba
+#   * stop it gracefully
27b8ba
+#   * create recovery.conf with standby_mode = on
27b8ba
+#   * start it
27b8ba
+#
27b8ba
+sub pgsql_demote {
27b8ba
+    my $rc;
27b8ba
+
27b8ba
+    $rc = pgsql_monitor();
27b8ba
+
27b8ba
+    # Running as primary. Normal, expected behavior.
27b8ba
+    if ( $rc == $OCF_RUNNING_MASTER ) {
27b8ba
+        ocf_log( 'debug', 'pgsql_demote: "%s" currently running as a primary',
27b8ba
+            $OCF_RESOURCE_INSTANCE )  ;
27b8ba
+    }
27b8ba
+    elsif ( $rc == $OCF_SUCCESS ) {
27b8ba
+        # Already running as secondary. Nothing to do.
27b8ba
+        ocf_log( 'debug',
27b8ba
+            'pgsql_demote: "%s" currently running as a secondary',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+            return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+    elsif ( $rc == $OCF_NOT_RUNNING ) {
27b8ba
+        # Instance is stopped. Nothing to do.
27b8ba
+        ocf_log( 'debug', 'pgsql_demote: "%s" currently shut down',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+    }
27b8ba
+    elsif ( $rc == $OCF_ERR_CONFIGURED ) {
27b8ba
+        # We actually prefer raising a hard or fatal error instead of leaving
27b8ba
+        # the CRM abording its transition for a new one because of a soft error.
27b8ba
+        # The hard error will force the CRM to move the resource immediately.
27b8ba
+        return $OCF_ERR_CONFIGURED;
27b8ba
+    }
27b8ba
+    else {
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    # TODO we need to make sure at least one slave is connected!!
27b8ba
+
27b8ba
+    # WARNING if the resource state is stopped instead of master, the ocf ra dev
27b8ba
+    # rsc advises to return OCF_ERR_GENERIC, misleading the CRM in a loop where
27b8ba
+    # it computes transitions of demote(failing)->stop->start->promote actions
27b8ba
+    # until failcount == migration-threshold.
27b8ba
+    # This is a really ugly trick to keep going with the demode action if the
27b8ba
+    # rsc is already stopped gracefully.
27b8ba
+    # See discussion "CRM trying to demote a stopped resource" on
27b8ba
+    # developers@clusterlabs.org
27b8ba
+    unless ( $rc == $OCF_NOT_RUNNING ) {
27b8ba
+        # Add 60s to the timeout or use a 24h timeout fallback to make sure
27b8ba
+        # Pacemaker will give up before us and take decisions
27b8ba
+        my $timeout = ( _get_action_timeout() || 60*60*24 )  + 60;
27b8ba
+
27b8ba
+        # WARNING the instance **MUST** be stopped gracefully.
27b8ba
+        # Do **not** use pg_stop() or service or systemctl here as these
27b8ba
+        # commands might force-stop the PostgreSQL instance using immediate
27b8ba
+        # after some timeout and return success, which is misleading.
27b8ba
+
27b8ba
+        $rc = _runas( $PGCTL, '--pgdata', $pgdata, '--mode', 'fast', '-w',
27b8ba
+            '--timeout', $timeout , 'stop' );
27b8ba
+
27b8ba
+        # No need to wait for stop to complete, this is handled in pg_ctl
27b8ba
+        # using -w option.
27b8ba
+        unless ( $rc == 0 ) {
27b8ba
+            ocf_exit_reason( 'Failed to stop "%s" using pg_ctl (returned %d)',
27b8ba
+                $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+            return $OCF_ERR_GENERIC;
27b8ba
+        }
27b8ba
+
27b8ba
+        # Double check that the instance is stopped correctly.
27b8ba
+        $rc = pgsql_monitor();
27b8ba
+        unless ( $rc == $OCF_NOT_RUNNING ) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                'Unexpected "%s" state: monitor status (%d) disagree with pg_ctl return code',
27b8ba
+                $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+            return $OCF_ERR_GENERIC;
27b8ba
+        }
27b8ba
+    }
27b8ba
+
27b8ba
+    #
27b8ba
+    # At this point, the instance **MUST** be stopped gracefully.
27b8ba
+    #
27b8ba
+
27b8ba
+    # Note: We do not need to handle the recovery.conf file here as pgsql_start
27b8ba
+    # deal with that itself. Equally, no need to wait for the start to complete
27b8ba
+    # here, handled in pgsql_start.
27b8ba
+    $rc = pgsql_start();
27b8ba
+    if ( $rc == $OCF_SUCCESS ) {
27b8ba
+        ocf_log( 'info', 'pgsql_demote: "%s" started as a secondary',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+
27b8ba
+    # NOTE: No need to double check the instance state as pgsql_start already use
27b8ba
+    # pgsql_monitor to check the state before returning.
27b8ba
+
27b8ba
+    ocf_exit_reason( 'Starting "%s" as a standby failed (returned %d)',
27b8ba
+        $OCF_RESOURCE_INSTANCE, $rc );
27b8ba
+    return $OCF_ERR_GENERIC;
27b8ba
+}
27b8ba
+
27b8ba
+
27b8ba
+# Promote the secondary instance to primary
27b8ba
+#
27b8ba
+sub pgsql_promote {
27b8ba
+    my $rc;
27b8ba
+    my $cancel_switchover;
27b8ba
+
27b8ba
+    $rc = pgsql_monitor();
27b8ba
+
27b8ba
+    if ( $rc == $OCF_SUCCESS ) {
27b8ba
+        # Running as slave. Normal, expected behavior.
27b8ba
+        ocf_log( 'debug', 'pgsql_promote: "%s" currently running as a standby',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+    }
27b8ba
+    elsif ( $rc == $OCF_RUNNING_MASTER ) {
27b8ba
+        # Already a master. Unexpected, but not a problem.
27b8ba
+        ocf_log( 'info', '"%s" already running as a primary',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+    elsif ( $rc == $OCF_NOT_RUNNING ) { # INFO this is not supposed to happen.
27b8ba
+        # Currently not running. Need to start before promoting.
27b8ba
+        ocf_log( 'info', '"%s" currently not running, starting it',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+        $rc = pgsql_start();
27b8ba
+        if ( $rc != $OCF_SUCCESS ) {
27b8ba
+            ocf_exit_reason( 'Failed to start the instance "%s"',
27b8ba
+                $OCF_RESOURCE_INSTANCE );
27b8ba
+            return $OCF_ERR_GENERIC;
27b8ba
+        }
27b8ba
+    }
27b8ba
+    else {
27b8ba
+        ocf_exit_reason( 'Unexpected error, cannot promote "%s"',
27b8ba
+            $OCF_RESOURCE_INSTANCE );
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    #
27b8ba
+    # At this point, the instance **MUST** be started as a secondary.
27b8ba
+    #
27b8ba
+
27b8ba
+    # Cancel the switchover if it has been considered not safe during the
27b8ba
+    # pre-promote action
27b8ba
+    $cancel_switchover = _get_priv_attr('cancel_switchover');
27b8ba
+    if ( $cancel_switchover ) { # if not empty or not 0
27b8ba
+        ocf_exit_reason( 'Switchover has been canceled from pre-promote action' );
27b8ba
+
27b8ba
+        _delete_priv_attr( 'cancel_switchover' );
27b8ba
+
27b8ba
+        return $OCF_ERR_GENERIC if $cancel_switchover eq '1';
27b8ba
+        return $OCF_ERR_ARGS; # ban the resource from the node if we have an
27b8ba
+                              # internal error during _check_switchover
27b8ba
+    }
27b8ba
+
27b8ba
+    # Do not check for a better candidate if we try to recover the master
27b8ba
+    # Recover of a master is detected during the pre-promote action. It sets the
27b8ba
+    # private attribute 'recover_master' to '1' if this is a master recover.
27b8ba
+    if ( _get_priv_attr( 'recover_master' ) eq '1' ) {
27b8ba
+        ocf_log( 'info', 'Recovering old master, no election needed');
27b8ba
+    }
27b8ba
+    else {
27b8ba
+
27b8ba
+        # The promotion is occurring on the best known candidate (highest
27b8ba
+        # master score), as chosen by pacemaker during the last working monitor
27b8ba
+        # on previous master (see pgsql_monitor/_check_locations subs).
27b8ba
+        # To avoid any race condition between the last monitor action on the
27b8ba
+        # previous master and the **real** most up-to-date standby, we
27b8ba
+        # set each standby location during the "pre-promote" action, and stored
27b8ba
+        # them using the "lsn_location" resource attribute.
27b8ba
+        #
27b8ba
+        # The best standby to promote would have the highest known LSN. If the
27b8ba
+        # current resource is not the best one, we need to modify the master
27b8ba
+        # scores accordingly, and abort the current promotion.
27b8ba
+        ocf_log( 'debug',
27b8ba
+            'pgsql_promote: checking if current node is the best candidate for promotion' );
27b8ba
+
27b8ba
+        # Exclude nodes that are known to be unavailable (not in the current
27b8ba
+        # partition) using the "crm_node" command
27b8ba
+        my @active_nodes    = split /\s+/ => _get_priv_attr( 'nodes' );
27b8ba
+        my $node_to_promote = '';
27b8ba
+        my $ans;
27b8ba
+        my $max_tl;
27b8ba
+        my $max_lsn;
27b8ba
+        my $node_tl;
27b8ba
+        my $node_lsn;
27b8ba
+        my $wal_num;
27b8ba
+        my $wal_off;
27b8ba
+
27b8ba
+        # Get the "lsn_location" attribute value for the current node, as set
27b8ba
+        # during the "pre-promote" action.
27b8ba
+        # It should be the greatest among the secondary instances.
27b8ba
+        $ans = _get_priv_attr( 'lsn_location' );
27b8ba
+
27b8ba
+        if ( $ans eq '' ) {
27b8ba
+            # This should not happen as the "lsn_location" attribute should have
27b8ba
+            # been updated during the "pre-promote" action.
27b8ba
+            ocf_exit_reason( 'Can not get current node LSN location' );
27b8ba
+            return $OCF_ERR_GENERIC;
27b8ba
+        }
27b8ba
+
27b8ba
+        chomp $ans;
27b8ba
+        ( $max_tl, $max_lsn ) = split /#/, $ans;
27b8ba
+
27b8ba
+        ocf_log( 'debug', 'pgsql_promote: current node TL#LSN location: %s#%s',
27b8ba
+            $max_tl, $max_lsn );
27b8ba
+
27b8ba
+        # Now we compare with the other available nodes.
27b8ba
+        foreach my $node ( @active_nodes ) {
27b8ba
+            # We exclude the current node from the check.
27b8ba
+            next if $node eq $nodename;
27b8ba
+
27b8ba
+            # Get the "lsn_location" attribute value for the node, as set during
27b8ba
+            # the "pre-promote" action.
27b8ba
+            # This is implemented as a loop as private attributes are asynchronously
27b8ba
+            # available from other nodes.
27b8ba
+            # see: https://github.com/ClusterLabs/PAF/issues/131
27b8ba
+            # NOTE: if a node did not set its lsn_location for some reason, this will end
27b8ba
+            # with a timeout and the whole promotion will start again.
27b8ba
+            WAIT_FOR_LSN: {
27b8ba
+                $ans = _get_priv_attr( 'lsn_location', $node );
27b8ba
+                if ( $ans eq '' ) {
27b8ba
+                    ocf_log( 'info', 'pgsql_promote: waiting for LSN from %s', $node );
27b8ba
+                    select( undef, undef, undef, 0.1 );
27b8ba
+                    redo WAIT_FOR_LSN;
27b8ba
+                }
27b8ba
+            }
27b8ba
+
27b8ba
+            chomp $ans;
27b8ba
+            ( $node_tl, $node_lsn ) = split /#/, $ans;
27b8ba
+
27b8ba
+            ocf_log( 'debug',
27b8ba
+                'pgsql_promote: comparing with "%s": TL#LSN is %s#%s',
27b8ba
+                $node, $node_tl, $node_lsn );
27b8ba
+
27b8ba
+            # If the node has a higher LSN, select it as a best candidate to
27b8ba
+            # promotion and keep looping to check the TL/LSN of other nodes.
27b8ba
+            if ( $node_tl > $max_tl
27b8ba
+                or ( $node_tl == $max_tl and $node_lsn > $max_lsn )
27b8ba
+            ) {
27b8ba
+                ocf_log( 'debug',
27b8ba
+                    'pgsql_promote: "%s" is a better candidate to promote (%s#%s > %s#%s)',
27b8ba
+                    $node, $node_tl, $node_lsn, $max_tl, $max_lsn );
27b8ba
+                $node_to_promote = $node;
27b8ba
+                $max_tl          = $node_tl;
27b8ba
+                $max_lsn         = $node_lsn;
27b8ba
+            }
27b8ba
+        }
27b8ba
+
27b8ba
+        # If any node has been selected, we adapt the master scores accordingly
27b8ba
+        # and break the current promotion.
27b8ba
+        if ( $node_to_promote ne '' ) {
27b8ba
+            ocf_exit_reason(
27b8ba
+                '%s is the best candidate to promote, aborting current promotion',
27b8ba
+                $node_to_promote );
27b8ba
+
27b8ba
+            # Reset current node master score.
27b8ba
+            _set_master_score( '1' );
27b8ba
+
27b8ba
+            # Set promotion candidate master score.
27b8ba
+            _set_master_score( '1000', $node_to_promote );
27b8ba
+
27b8ba
+            # We fail the promotion to trigger another promotion transition
27b8ba
+            # with the new scores.
27b8ba
+            return $OCF_ERR_GENERIC;
27b8ba
+        }
27b8ba
+
27b8ba
+        # Else, we will keep on promoting the current node.
27b8ba
+    }
27b8ba
+
27b8ba
+    unless (
27b8ba
+        # Promote the instance on the current node.
27b8ba
+        _runas( $PGCTL, '--pgdata', $pgdata, '-w', 'promote' ) == 0 )
27b8ba
+    {
27b8ba
+        ocf_exit_reason( 'Error during promotion command' );
27b8ba
+        return $OCF_ERR_GENERIC;
27b8ba
+    }
27b8ba
+
27b8ba
+    # The instance promotion is asynchronous, so we need to wait for this
27b8ba
+    # process to complete.
27b8ba
+    while ( pgsql_monitor() != $OCF_RUNNING_MASTER ) {
27b8ba
+        ocf_log( 'info', 'Waiting for the promote to complete' );
27b8ba
+        sleep 1;
27b8ba
+    }
27b8ba
+
27b8ba
+    ocf_log( 'info', 'Promote complete' );
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+# This action is called **before** the actual promotion when a failing master is
27b8ba
+# considered unreclaimable, recoverable or a new master must be promoted
27b8ba
+# (switchover or first start).
27b8ba
+# As every "notify" action, it is executed almost simultaneously on all
27b8ba
+# available nodes.
27b8ba
+sub pgsql_notify_pre_promote {
27b8ba
+    my $rc;
27b8ba
+    my $node_tl;
27b8ba
+    my $node_lsn;
27b8ba
+    my %cdata;
27b8ba
+    my %active_nodes;
27b8ba
+    my $attr_nodes;
27b8ba
+
27b8ba
+    ocf_log( 'info', 'Promoting instance on node "%s"',
27b8ba
+        $OCF_NOTIFY_ENV{'promote'}[0]{'uname'} );
27b8ba
+
27b8ba
+    # No need to do an election between slaves if this is recovery of the master
27b8ba
+    if ( _is_master_recover( $OCF_NOTIFY_ENV{'promote'}[0]{'uname'} ) ) {
27b8ba
+        ocf_log( 'warning', 'This is a master recovery!' );
27b8ba
+
27b8ba
+        _set_priv_attr( 'recover_master', '1' )
27b8ba
+            if $OCF_NOTIFY_ENV{'promote'}[0]{'uname'} eq $nodename;
27b8ba
+
27b8ba
+        return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+
27b8ba
+    # Environment cleanup!
27b8ba
+    _delete_priv_attr( 'lsn_location'      );
27b8ba
+    _delete_priv_attr( 'recover_master'    );
27b8ba
+    _delete_priv_attr( 'nodes'             );
27b8ba
+    _delete_priv_attr( 'cancel_switchover' );
27b8ba
+
27b8ba
+    # check for the last received entry of WAL from the master if we are
27b8ba
+    # the designated slave to promote
27b8ba
+    if ( _is_switchover( $nodename ) and scalar
27b8ba
+         grep { $_->{'uname'} eq $nodename } @{ $OCF_NOTIFY_ENV{'promote'} }
27b8ba
+    ) {
27b8ba
+        $rc = _check_switchover();
27b8ba
+
27b8ba
+        unless ( $rc == 0 ) {
27b8ba
+            # Shortcut the election process as the switchover will be
27b8ba
+            # canceled
27b8ba
+            _set_priv_attr( 'cancel_switchover', $rc );
27b8ba
+            return $OCF_SUCCESS; # return code is ignored during notify
27b8ba
+        }
27b8ba
+
27b8ba
+        # If the sub keeps going, that means the switchover is safe.
27b8ba
+        # Keep going with the election process in case the switchover was
27b8ba
+        # instruct to the wrong node.
27b8ba
+        # FIXME: should we allow a switchover to a lagging slave?
27b8ba
+    }
27b8ba
+
27b8ba
+    # We need to trigger an election between existing slaves to promote the best
27b8ba
+    # one based on its current LSN location. Each node set a private attribute
27b8ba
+    # "lsn_location" with its TL and LSN location.
27b8ba
+    #
27b8ba
+    # During the following promote action, The designated standby for
27b8ba
+    # promotion use these attributes to check if the instance to be promoted
27b8ba
+    # is the best one, so we can avoid a race condition between the last
27b8ba
+    # successful monitor on the previous master and the current promotion.
27b8ba
+
27b8ba
+    # As we can not break the transition from a notification action, we check
27b8ba
+    # during the promotion if each node TL and LSN are valid.
27b8ba
+
27b8ba
+    # Force a checpoint to make sure the controldata shows the very last TL
27b8ba
+    _query( q{ CHECKPOINT }, {} );
27b8ba
+    %cdata    = _get_controldata();
27b8ba
+    $node_lsn = _get_last_received_lsn( 'in decimal' );
27b8ba
+
27b8ba
+    unless ( defined $node_lsn ) {
27b8ba
+        ocf_log( 'warning', 'Unknown current node LSN' );
27b8ba
+        # Return code are ignored during notifications...
27b8ba
+        return $OCF_SUCCESS;
27b8ba
+    }
27b8ba
+
27b8ba
+    $node_lsn = "$cdata{'tl'}#$node_lsn";
27b8ba
+
27b8ba
+    ocf_log( 'info', 'Current node TL#LSN: %s', $node_lsn );
27b8ba
+
27b8ba
+    # Set the "lsn_location" attribute value for this node so we can use it
27b8ba
+    # during the following "promote" action.
27b8ba
+    _set_priv_attr( 'lsn_location', $node_lsn );
27b8ba
+
27b8ba
+    ocf_log( 'warning', 'Could not set the current node LSN' )
27b8ba
+        if $? != 0 ;
27b8ba
+
27b8ba
+    # If this node is the future master, keep track of the slaves that
27b8ba
+    # received the same notification to compare our LSN with them during
27b8ba
+    # promotion
27b8ba
+    if ( $OCF_NOTIFY_ENV{'promote'}[0]{'uname'} eq $nodename ) {
27b8ba
+        # Build the list of active nodes:
27b8ba
+        #   master + slave + start - stop
27b8ba
+        # FIXME: Deal with rsc started during the same transaction but **after**
27b8ba
+        #        the promotion ?
27b8ba
+        $active_nodes{ $_->{'uname'} }++ foreach @{ $OCF_NOTIFY_ENV{'active'} },
27b8ba
+                                                 @{ $OCF_NOTIFY_ENV{'start'} };
27b8ba
+        $active_nodes{ $_->{'uname'} }-- foreach @{ $OCF_NOTIFY_ENV{'stop'} };
27b8ba
+
27b8ba
+        $attr_nodes = join " "
27b8ba
+            => grep { $active_nodes{$_} > 0 } keys %active_nodes;
27b8ba
+
27b8ba
+        _set_priv_attr( 'nodes', $attr_nodes );
27b8ba
+    }
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+# This action is called after a promote action.
27b8ba
+sub pgsql_notify_post_promote {
27b8ba
+
27b8ba
+    # We have a new master (or the previous one recovered).
27b8ba
+    # Environment cleanup!
27b8ba
+    _delete_priv_attr( 'lsn_location'      );
27b8ba
+    _delete_priv_attr( 'recover_master'    );
27b8ba
+    _delete_priv_attr( 'nodes'             );
27b8ba
+    _delete_priv_attr( 'cancel_switchover' );
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+# This is called before a demote occurs.
27b8ba
+sub pgsql_notify_pre_demote {
27b8ba
+    my $rc;
27b8ba
+    my %cdata;
27b8ba
+
27b8ba
+    # do nothing if the local node will not be demoted
27b8ba
+    return $OCF_SUCCESS unless scalar
27b8ba
+        grep { $_->{'uname'} eq $nodename } @{ $OCF_NOTIFY_ENV{'demote'} };
27b8ba
+
27b8ba
+    $rc = pgsql_monitor();
27b8ba
+
27b8ba
+    # do nothing if this is not a master recovery
27b8ba
+    return $OCF_SUCCESS unless _is_master_recover( $nodename )
27b8ba
+                           and $rc == $OCF_FAILED_MASTER;
27b8ba
+
27b8ba
+    # in case of master crash, we need to detect if the CRM tries to recover
27b8ba
+    # the master clone. The usual transition is to do:
27b8ba
+    #   demote->stop->start->promote
27b8ba
+    #
27b8ba
+    # There are multiple flaws with this transition:
27b8ba
+    #  * the 1st and 2nd actions will fail because the instance is in
27b8ba
+    #    OCF_FAILED_MASTER step
27b8ba
+    #  * the usual start action is dangerous as the instance will start with
27b8ba
+    #    a recovery.conf instead of entering a normal recovery process
27b8ba
+    #
27b8ba
+    # To avoid this, we try to start the instance in recovery from here.
27b8ba
+    # If it success, at least it will be demoted correctly with a normal
27b8ba
+    # status. If it fails, it will be catched up in next steps.
27b8ba
+
27b8ba
+    ocf_log( 'info', 'Trying to start failing master "%s"...',
27b8ba
+        $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+    # Either the instance managed to start or it couldn't.
27b8ba
+    # We rely on the pg_ctk '-w' switch to take care of this. If it couldn't
27b8ba
+    # start, this error will be catched up later during the various checks
27b8ba
+    _pg_ctl_start();
27b8ba
+
27b8ba
+    %cdata = _get_controldata();
27b8ba
+
27b8ba
+    ocf_log( 'info', 'State is "%s" after recovery attempt', $cdata{'state'} );
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+# This is called before a stop occurs.
27b8ba
+sub pgsql_notify_pre_stop {
27b8ba
+    my $rc;
27b8ba
+    my %cdata;
27b8ba
+
27b8ba
+    # do nothing if the local node will not be stopped
27b8ba
+    return $OCF_SUCCESS unless scalar
27b8ba
+        grep { $_->{'uname'} eq $nodename } @{ $OCF_NOTIFY_ENV{'stop'} };
27b8ba
+
27b8ba
+    $rc = _controldata_to_ocf();
27b8ba
+
27b8ba
+    # do nothing if this is not a slave recovery
27b8ba
+    return $OCF_SUCCESS unless _is_slave_recover( $nodename )
27b8ba
+                           and $rc == $OCF_RUNNING_SLAVE;
27b8ba
+
27b8ba
+    # in case of slave crash, we need to detect if the CRM tries to recover
27b8ba
+    # the slaveclone. The usual transition is to do: stop->start
27b8ba
+    #
27b8ba
+    # This transition can no twork because the instance is in
27b8ba
+    # OCF_ERR_GENERIC step. So the stop action will fail, leading most
27b8ba
+    # probably to fencing action.
27b8ba
+    #
27b8ba
+    # To avoid this, we try to start the instance in recovery from here.
27b8ba
+    # If it success, at least it will be stopped correctly with a normal
27b8ba
+    # status. If it fails, it will be catched up in next steps.
27b8ba
+
27b8ba
+    ocf_log( 'info', 'Trying to start failing slave "%s"...',
27b8ba
+        $OCF_RESOURCE_INSTANCE );
27b8ba
+
27b8ba
+    # Either the instance managed to start or it couldn't.
27b8ba
+    # We rely on the pg_ctk '-w' switch to take care of this. If it couldn't
27b8ba
+    # start, this error will be catched up later during the various checks
27b8ba
+    _pg_ctl_start();
27b8ba
+
27b8ba
+    %cdata = _get_controldata();
27b8ba
+
27b8ba
+    ocf_log( 'info', 'State is "%s" after recovery attempt', $cdata{'state'} );
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+# Notify type actions, called on all available nodes before (pre) and after
27b8ba
+# (post) other actions, like promote, start, ...
27b8ba
+#
27b8ba
+sub pgsql_notify {
27b8ba
+    my $type_op;
27b8ba
+
27b8ba
+    ocf_log( 'debug', "pgsql_notify: environment variables: %s",
27b8ba
+        Data::Dumper->new( [ \%OCF_NOTIFY_ENV ] )->Sortkeys(1)->Terse(1)->Dump );
27b8ba
+
27b8ba
+    return unless %OCF_NOTIFY_ENV;
27b8ba
+
27b8ba
+    $type_op = "$OCF_NOTIFY_ENV{'type'}-$OCF_NOTIFY_ENV{'operation'}";
27b8ba
+
27b8ba
+    for ( $type_op ) {
27b8ba
+        if    ( /^pre-promote$/  ) { return pgsql_notify_pre_promote()  }
27b8ba
+        elsif ( /^post-promote$/ ) { return pgsql_notify_post_promote() }
27b8ba
+        elsif ( /^pre-demote$/   ) { return pgsql_notify_pre_demote()   }
27b8ba
+        elsif ( /^pre-stop$/     ) { return pgsql_notify_pre_stop()     }
27b8ba
+    }
27b8ba
+
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+}
27b8ba
+
27b8ba
+# Action used to allow for online modification of resource parameters value.
27b8ba
+#
27b8ba
+sub pgsql_reload {
27b8ba
+
27b8ba
+    # No action necessary, the action declaration is enough to inform pacemaker
27b8ba
+    # that the modification of any non-unique parameter can be applied without
27b8ba
+    # having to restart the resource.
27b8ba
+    ocf_log( 'info', 'Instance "%s" reloaded', $OCF_RESOURCE_INSTANCE );
27b8ba
+    return $OCF_SUCCESS;
27b8ba
+
27b8ba
+}
27b8ba
+
27b8ba
+############################################################
27b8ba
+#### MAIN
27b8ba
+
27b8ba
+exit ocf_meta_data() if $__OCF_ACTION eq 'meta-data';
27b8ba
+exit ocf_methods()   if $__OCF_ACTION eq 'methods';
27b8ba
+
27b8ba
+# Avoid "could not change directory" when executing commands as "system-user".
27b8ba
+chdir File::Spec->tmpdir();
27b8ba
+
27b8ba
+# mandatory sanity checks
27b8ba
+# check pgdata
27b8ba
+if ( ! -d $pgdata ) {
27b8ba
+    ocf_exit_reason( 'PGDATA "%s" does not exist', $pgdata );
27b8ba
+    exit $OCF_ERR_ARGS;
27b8ba
+}
27b8ba
+
27b8ba
+# check datadir
27b8ba
+if ( ! -d $datadir ) {
27b8ba
+    ocf_exit_reason( 'data_directory "%s" does not exist', $datadir );
27b8ba
+    exit $OCF_ERR_ARGS;
27b8ba
+}
27b8ba
+
27b8ba
+# Set PostgreSQL version
27b8ba
+$PGVERNUM = _get_pg_version();
27b8ba
+
27b8ba
+# Set current node name.
27b8ba
+$nodename = ocf_local_nodename();
27b8ba
+
27b8ba
+$exit_code = pgsql_validate_all();
27b8ba
+
27b8ba
+exit $exit_code if $exit_code != $OCF_SUCCESS or $__OCF_ACTION eq 'validate-all';
27b8ba
+
27b8ba
+# Run action
27b8ba
+for ( $__OCF_ACTION ) {
27b8ba
+    if    ( /^start$/     ) { $exit_code = pgsql_start()   }
27b8ba
+    elsif ( /^stop$/      ) { $exit_code = pgsql_stop()    }
27b8ba
+    elsif ( /^monitor$/   ) { $exit_code = pgsql_monitor() }
27b8ba
+    elsif ( /^promote$/   ) { $exit_code = pgsql_promote() }
27b8ba
+    elsif ( /^demote$/    ) { $exit_code = pgsql_demote()  }
27b8ba
+    elsif ( /^notify$/    ) { $exit_code = pgsql_notify()  }
27b8ba
+    elsif ( /^reload$/    ) { $exit_code = pgsql_reload()  }
27b8ba
+    else  { $exit_code = $OCF_ERR_UNIMPLEMENTED }
27b8ba
+}
27b8ba
+
27b8ba
+exit $exit_code;
27b8ba
+
27b8ba
+
27b8ba
+=head1 EXAMPLE CRM SHELL
27b8ba
+
27b8ba
+The following is an example configuration for a pgsqlms resource using the
27b8ba
+crm(8) shell:
27b8ba
+
27b8ba
+  primitive pgsqld pgsqlms                                                 \
27b8ba
+    params pgdata="/var/lib/postgresql/9.6/main"                           \
27b8ba
+      bindir="/usr/lib/postgresql/9.6/bin"                                 \
27b8ba
+      pghost="/var/run/postgresql"                                         \
27b8ba
+      recovery_template="/etc/postgresql/9.6/main/recovery.conf.pcmk"      \
27b8ba
+      start_opts="-c config_file=/etc/postgresql/9.6/main/postgresql.conf" \
27b8ba
+    op start timeout=60s                                                   \
27b8ba
+    op stop timeout=60s                                                    \
27b8ba
+    op promote timeout=30s                                                 \
27b8ba
+    op demote timeout=120s                                                 \
27b8ba
+    op monitor interval=15s timeout=10s role="Master"                      \
27b8ba
+    op monitor interval=16s timeout=10s role="Slave"                       \
27b8ba
+    op notify timeout=60s
27b8ba
+
27b8ba
+  ms pgsql-ha pgsqld meta notify=true
27b8ba
+
27b8ba
+
27b8ba
+=head1 EXAMPLE PCS
27b8ba
+
27b8ba
+The following is an example configuration for a pgsqlms resource using pcs(8):
27b8ba
+
27b8ba
+  pcs resource create pgsqld ocf:heartbeat:pgsqlms            \
27b8ba
+    bindir=/usr/pgsql-9.6/bin pgdata=/var/lib/pgsql/9.6/data  \
27b8ba
+    op start timeout=60s                                      \
27b8ba
+    op stop timeout=60s                                       \
27b8ba
+    op promote timeout=30s                                    \
27b8ba
+    op demote timeout=120s                                    \
27b8ba
+    op monitor interval=15s timeout=10s role="Master"         \
27b8ba
+    op monitor interval=16s timeout=10s role="Slave"          \
27b8ba
+    op notify timeout=60s --master notify=true
27b8ba
+
27b8ba
+=head1 SEE ALSO
27b8ba
+
27b8ba
+http://clusterlabs.org/
27b8ba
+
27b8ba
+=head1 AUTHOR
27b8ba
+
27b8ba
+Jehan-Guillaume de Rorthais and Mael Rimbault.
27b8ba
+
27b8ba
+=cut
27b8ba
diff --color -uNr a/paf_LICENSE b/paf_LICENSE
27b8ba
--- a/paf_LICENSE	1970-01-01 01:00:00.000000000 +0100
27b8ba
+++ b/paf_LICENSE	2021-04-14 09:16:39.083555835 +0200
27b8ba
@@ -0,0 +1,19 @@
27b8ba
+Copyright (c) 2016-2020, Jehan-Guillaume de Rorthais, Mael Rimbault.
27b8ba
+
27b8ba
+Permission to use, copy, modify, and distribute this software and its
27b8ba
+documentation for any purpose, without fee, and without a written agreement
27b8ba
+is hereby granted, provided that the above copyright notice and this
27b8ba
+paragraph and the following two paragraphs appear in all copies.
27b8ba
+
27b8ba
+IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
27b8ba
+DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
27b8ba
+LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
27b8ba
+DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
27b8ba
+POSSIBILITY OF SUCH DAMAGE.
27b8ba
+
27b8ba
+THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
27b8ba
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
27b8ba
+AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
27b8ba
+ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
27b8ba
+PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
27b8ba
+
27b8ba
diff --color -uNr a/paf_README.md b/paf_README.md
27b8ba
--- a/paf_README.md	1970-01-01 01:00:00.000000000 +0100
27b8ba
+++ b/paf_README.md	2021-04-14 09:18:57.450968048 +0200
27b8ba
@@ -0,0 +1,86 @@
27b8ba
+# PostgreSQL Automatic Failover
27b8ba
+
27b8ba
+High-Availibility for Postgres, based on industry references Pacemaker and
27b8ba
+Corosync.
27b8ba
+
27b8ba
+## Description
27b8ba
+
27b8ba
+Pacemaker is nowadays the industry reference for High Availability. In the same
27b8ba
+fashion than for Systemd, all Linux distributions moved (or are moving) to this
27b8ba
+unique Pacemaker+Corosync stack, removing all other existing high availability
27b8ba
+stacks (CMAN, RGManager, OpenAIS, ...). It is able to detect failure on various
27b8ba
+services and automatically decide to failover the failing resource to another
27b8ba
+node when possible.
27b8ba
+
27b8ba
+To be able to manage a specific service resource, Pacemaker interact with it
27b8ba
+through a so-called "Resource Agent". Resource agents must comply to the OCF
27b8ba
+specification which define what they must implement (start, stop, promote,
27b8ba
+etc), how they should behave and inform Pacemaker of their results.
27b8ba
+
27b8ba
+PostgreSQL Automatic Failover is a new OCF resource Agent dedicated to
27b8ba
+PostgreSQL. Its original wish is to keep a clear limit between the Pacemaker
27b8ba
+administration and the PostgreSQL one, to keep things simple, documented and
27b8ba
+yet powerful.
27b8ba
+
27b8ba
+Once your PostgreSQL cluster built using internal streaming replication, PAF is
27b8ba
+able to expose to Pacemaker what is the current status of the PostgreSQL
27b8ba
+instance on each node: master, slave, stopped, catching up, etc. Should a
27b8ba
+failure occurs on the master, Pacemaker will try to recover it by default.
27b8ba
+Should the failure be non-recoverable, PAF allows the slaves to be able to
27b8ba
+elect the best of them (the closest one to the old master) and promote it as
27b8ba
+the new master. All of this thanks to the robust, feature-full and most
27b8ba
+importantly experienced project: Pacemaker.
27b8ba
+
27b8ba
+For information about how to install this agent, see `INSTALL.md`.
27b8ba
+
27b8ba
+## Setup and requirements
27b8ba
+
27b8ba
+PAF supports PostgreSQL 9.3 and higher. It has been extensively tested under
27b8ba
+CentOS 6 and 7 in various scenario.
27b8ba
+
27b8ba
+PAF has been written to give to the administrator the maximum control
27b8ba
+over their PostgreSQL configuration and architecture. Thus, you are 100%
27b8ba
+responsible for the master/slave creations and their setup. The agent
27b8ba
+will NOT edit your setup. It only requires you to follow these pre-requisites:
27b8ba
+
27b8ba
+  * slave __must__ be in hot_standby (accept read-only connections) ;
27b8ba
+  * the following parameters __must__ be configured in the appropriate place :
27b8ba
+    * `standby_mode = on` (for PostgreSQL 11 and before)
27b8ba
+    * `recovery_target_timeline = 'latest'`
27b8ba
+    * `primary_conninfo` wih `application_name` set to the node name as seen
27b8ba
+      in Pacemaker.
27b8ba
+  * these last parameters has been merged inside the instance configuration
27b8ba
+    file with PostgreSQL 12. For PostgreSQL 11 and before, you __must__
27b8ba
+    provide a `recovery.conf` template file.
27b8ba
+
27b8ba
+When setting up the resource in Pacemaker, here are the available parameters you
27b8ba
+can set:
27b8ba
+
27b8ba
+  * `bindir`: location of the PostgreSQL binaries (default: `/usr/bin`)
27b8ba
+  * `pgdata`: location of the PGDATA of your instance (default:
27b8ba
+    `/var/lib/pgsql/data`)
27b8ba
+  * `datadir`: path to the directory set in `data_directory` from your
27b8ba
+    postgresql.conf file. This parameter has same default than PostgreSQL
27b8ba
+    itself: the `pgdata` parameter value. Unless you have a special PostgreSQL
27b8ba
+    setup and you understand this parameter, __ignore it__
27b8ba
+  * `pghost`: the socket directory or IP address to use to connect to the
27b8ba
+    local instance (default: `/tmp` or `/var/run/postgresql` for DEBIAN)
27b8ba
+  * `pgport`:  the port to connect to the local instance (default: `5432`)
27b8ba
+  * `recovery_template`: __only__ for PostgreSQL 11 and before. The local 
27b8ba
+    template that will be copied as the `PGDATA/recovery.conf` file. This
27b8ba
+    file must not exist on any node for PostgreSQL 12 and after.
27b8ba
+    (default: `$PGDATA/recovery.conf.pcmk`)
27b8ba
+  * `start_opts`: Additional arguments given to the postgres process on startup.
27b8ba
+    See "postgres --help" for available options. Useful when the postgresql.conf
27b8ba
+    file is not in the data directory (PGDATA), eg.:
27b8ba
+    `-c config_file=/etc/postgresql/9.3/main/postgresql.conf`
27b8ba
+  * `system_user`: the system owner of your instance's process (default:
27b8ba
+    `postgres`)
27b8ba
+  * `maxlag`: maximum lag allowed on a standby before we set a negative master
27b8ba
+    score on it. The calculation is based on the difference between the current
27b8ba
+    xlog location on the master and the write location on the standby.
27b8ba
+    (default: 0, which disables this feature)
27b8ba
+
27b8ba
+For a demonstration about how to setup a cluster, see
27b8ba
+[http://clusterlabs.github.io/PAF/documentation.html](http://clusterlabs.github.io/PAF/documentation.html).
27b8ba
+