]> git.8kb.co.uk Git - slony-i/slony_failover/blob - slony_failover.pl
694ef9f738943e87c4c0bc18730810b5025993a2
[slony-i/slony_failover] / slony_failover.pl
1 #!/usr/bin/perl
2
3 # Script:       failover.pl
4 # Copyright:    08/04/2012: v1.0.2 Glyn Astill <glyn@8kb.co.uk>
5 # Requires:     Perl 5.10.1+, Data::UUID, File::Slurp
6 #               PostgreSQL 9.0+ Slony-I 1.2+ / 2.0+
7 #
8 # This script is a command-line utility to manage switchover and failover
9 # of replication sets in Slony-I clusters.
10 #
11 # This script is free software: you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation, either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This script is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this script.  If not, see <http://www.gnu.org/licenses/>.
23
24 use strict;
25 use warnings;
26 use DBI;
27 use Getopt::Long qw/GetOptions/;
28 use Data::UUID;
29 use File::Slurp;
30 use v5.10.1;
31 use sigtrap 'handler' => \&sigExit, 'HUP', 'INT','ABRT','QUIT','TERM';
32 use Time::HiRes qw/usleep gettimeofday/;
33 use POSIX qw/strftime/;
34 use Config qw/%Config/;
35
36 use constant false => 0;
37 use constant true  => 1;
38
39 my $g_script_version = '1.0.3';
40 my $g_debug = true;
41 my $g_pidfile = '/var/run/slony_failover.pid';
42 my $g_pid_written = false;
43 my $g_lang = 'en';
44 my $g_prefix = '/tmp/slony_failovers';
45 my $g_separate_working = true;
46 my $g_log_prefix = '%t';
47 my $g_log_to_db = false;
48 my $g_logdb_name;
49 my $g_logdb_host;
50 my $g_logdb_port;
51 my $g_logdb_user;
52 my $g_logdb_pass;
53 my $g_slonikpath;
54 my $g_use_try_blocks = false;
55 my $g_lockset_method = 'multiple';
56 my $g_logfile = 'failover.log';
57 my $g_input;
58 my $g_silence_notice = false;
59 my $g_reason;
60 my $g_script;
61 my $g_node_from;
62 my $g_node_to;
63 my $g_clname;
64 my $g_dbname;
65 my $g_dbhost;
66 my $g_dbport = 5432;
67 my $g_dbconninfo;
68 my $g_dbpass = '';
69 my $g_dbuser = 'slony';
70 my $g_node_count;
71 my $g_available_node_count;
72 my $g_critical_node_count;
73 my $g_subs_follow_origin = false;
74 my $g_use_comment_aliases = false;
75 my @g_cluster;                      # Array refs of node info.  In hindsight this should have been a hash, should be fairly simple to switch.
76 my @g_failed;
77 my @g_sets;
78 my @g_lags;
79 my $g_result;
80 my $g_version;
81 my $g_failover_method = 'old';
82 my $g_resubscribe_method = 'subscribe';
83 my $g_failover = false;
84 my $g_fail_subonly = false;
85 my $g_drop_failed = false;
86 my $g_autofailover = false;
87 my $g_autofailover_poll_interval = 500;
88 my $g_autofailover_retry = 2;
89 my $g_autofailover_retry_sleep = 1000;
90 my $g_autofailover_provs = false;
91 my $g_autofailover_config_any = true;
92 my $g_autofailover_perspective_sleep = 20000;
93 my $g_autofailover_majority_only = false;
94 my $g_autofailover_is_quorum = false;
95 my @g_unresponsive;
96 my %g_unresponsive_subonly;
97 my %g_backups;
98 my $g_pid = $$;
99
100 # Hash containing messages used by lookupMsg()
101 my %message = (
102 'en' => {
103     'usage'                            => q{-h <host> -p <port> -db <database> -cl <cluster name> -u <username> -P <password> -f <config file> (Password option not recommended; use pgpass instead)},
104     'title'                            => q{Slony-I failover script version $1},
105     'cluster_fixed'                    => q{Aborting failover action: all origin/provider nodes now responsive},
106     'cluster_failed'                   => q{Found $1 failed nodes, sleeping for $2ms before retry $3 of $4},
107     'load_cluster'                     => q{Getting a list of database nodes...}, 
108     'load_cluster_fail'                => q{Unable to read cluster configuration $1}, 
109     'load_cluster_success'             => q{I Loaded Slony-I v$1 cluster "$2" with $3 nodes read from node at $4:$5/$6}, 
110     'lag_detail'                       => q{Current node lag information from configuration node:},
111     'script_settings'                  => q{Using $1 batches of lock set, $2 FAILOVER and $3},
112     'generated_script'                 => q{Generated script "$1"},
113     'autofailover_init'                => q{Entering autofailover mode},
114     'autofailover_init_cnf'            => q{Slony configuration will be read from $1 node},
115     'autofailover_init_pol'            => q{Polling every $1ms},
116     'autofailover_init_ret'            => q{Failed nodes will be retried $1 times with $2ms sleep},
117     'autofailover_init_set'            => q{Failed forwarding providers $1 be failed over},
118     'autofailover_load_cluster'        => q{$1 Slony-I v$2 cluster "$3" with $4 nodes read from node $5},
119     'autofailover_proceed'             => q{Proceeding with failover:},
120     'autofailover_detail'              => q{Failed node: $1, Backup node: $2},
121     'autofailover_halt'                => q{Unable to perform any failover for $1 failed nodes},
122     'autofailover_check_sub'           => q{Checking subscriber node $1},
123     'autofailover_check_sub_fail'      => q{Unable to check subscriber node $1},
124     'autofailover_promote_find'        => q{Finding most up to date subscriber to all sets ($1) on unresponsive node $2},
125     'autofailover_promote_found'       => q{Using previously found most up to date subscriber to all sets ($1) on unresponsive node $2},
126     'autofailover_promote_skip'        => q{No failover required for unresponsive node $1 as it is neither the origin or an active forwarder of any sets},
127     'autofailover_promote_fail'        => q{Could not find suitable backup node for promotion},
128     'autofailover_node_detail'         => q{Node $1 is $2 subscribed to ($3) node $4 and provides sets $5 at $6 seconds lag (on event $7)},
129     'autofailover_promote_best'        => q{Best node for promotion is node $1 lag = $2 seconds (event $3)},
130     'autofailover_promote_unsuitable'  => q{Node $1 is unsuitable for promotion},
131     'autofailover_unresponsive'        => q{Detected unresponsive origin node: $1},
132     'autofailover_unresponsive_prov'   => q{Detected unresponsive provider node: $1},
133     'autofailover_unresponsive_subonly'=> q{Detected unresponsive subscriber only node: $1},
134     'autofailover_recovery_subonly'    => q{Detected recovery of previously unresponsive subscriber only node: $1},
135     'autofailover_pspec_check_fail'    => q{Failed to connect to node $1: $2},
136     'autofailover_pspec_check'         => q{Getting objective judgement from other nodes, apparent unresponsive nodes are : $1 (Failed nodes = $2 of $3)},
137     'autofailover_pspec_check_sleep'   => q{Sleeping for $1 ms},
138     'autofailover_pspec_check_data'    => q{$1: Node $2 says lag from node $3 -> $4 is $5 seconds},
139     'autofailover_pspec_check_true'    => q{All detected failed nodes confirmed as lagging by other nodes},
140     'autofailover_pspec_check_false'   => q{Not all nodes confirmed as lagging},
141     'autofailover_pspec_check_unknown' => q{Unable to confirm lag status of all nodes},
142     'autofailover_split_check'         => q{Surviving nodes ($1 of $2) are the majority},
143     'autofailover_split_check_fail'    => q{Surviving nodes ($1) are not the majority},
144     'interactive_head_id'              => q{ID},
145     'interactive_head_name'            => q{Name},
146     'interactive_head_status'          => q{Status},
147     'interactive_head_providers'       => q{Provider IDs},
148     'interactive_head_config'          => q{Configuration},
149     'interactive_detail_1'             => q{Origin for sets: },
150     'interactive_detail_2'             => q{Providing sets: },
151     'interactive_detail_3'             => q{Subscriptions: },
152     'interactive_choose_node'          => q{Please choose the node to move all sets $1:},
153     'interactive_confirm'              => q{You chose to move sets $1 node $2 ($3). Is this correct [y/n]? },
154     'interactive_action'               => q{Best course of action is most likely to do a "$1". Do you wish to continue [y/n]?},
155     'interactive_surrender'            => q{Uable to determine best course of action},
156     'interactive_write_script'         => q{Writing a script to $1 node $2 to $3},
157     'interactive_check_nodes'          => q{Checking availability of database nodes...},
158     'interactive_continue'             => q{Do you wish to continue [y/n]?},
159     'interactive_drop_nodes'           => q{Do you want to also drop the failed nodes from the slony configuration [y/n]?},
160     'interactive_preserve'             => q{Preserve subscription paths to follow the origin node (choose no if unsure) [y/n]?},
161     'interactive_aliases'              => q{Generate aliases based on sl_node/set comments in parentheses (choose no if unsure) [y/n]?},
162     'interactive_summary'              => q{Summary of nodes to be passed to failover:},
163     'interactive_node_info'            => q{Node : $1 ($2) $3 (conninfo $4)},
164     'interactive_run_script'           => q{Would you like to run this script now [y/n]?},
165     'interactive_running'              => q{Running the script now. This may take some time; please be patient!},
166     'interactive_reason'               => q{Please enter a brief reson for taking this action: },
167     'interactive_failover_detail_1'    => q{Before you go any further please consider the impact of a full failover:},
168     'interactive_failover_detail_2'    => q{The node you are failing over from will cease to participate in the cluster permanently until it is rebuild & subscribed},
169     'interactive_failover_detail_3'    => q{If the outage is temporary (i.e. network/power/easily replaceable hardware related) consider waiting it out},
170     'interactive_failover_detail_4'    => q{This type of failover is likely to be more a business decision than a technical one},
171     'info_all_nodes_available'         => q{INFO: All nodes are available},
172     'info_req_nodes_available'         => q{INFO: $1 of $2 nodes are available. No unavailable nodes are subscribed to the old origin},
173     'wrn_node_unavailable'             => q{WARNING: Node $1 unavailable},
174     'wrn_req_unavailable'              => q{WARNING: Old origin node ($1) is available, however $2 subscribers are unavailable},
175     'wrn_not_tested'                   => q{WARNING: Script not tested with Slony-I v$1},
176     'wrn_failover_issues'              => q{WARNING: Slony-I v$1 may struggle to failover correctly with multiple failed nodes (affects v2.0-2.1)},
177     'note_autofail_fwd_only'           => q{NOTICE: Slony versions prior to 2.2 cannot initiate failover from only failed forwarding providers},
178     'note_fail_sub_only'               => q{NOTICE: Slony versions prior to 2.2 cannot failover subscriber only nodes, reverting to failover_offline_subscriber_only = false},
179     'note_multiple_try'                => q{NOTICE: Cannot lock multiple sets within try blocks in version $1 dropping back to single sets},
180     'note_reshape_cluster'             => q{NOTICE: Either drop the failed subscribers or bring them back up, then retry to MOVE SET},
181     'dbg_generic'                      => q{DEBUG: $1},
182     'dbg_cluster'                      => q{DEBUG: NodeID $1/ProvIDs $2/Conninfo $3/OrigSets $4/NodeName $5/ProvTree $6/Active $7/FwdSets $8/ActSubSets $9},
183     'dbg_resubscribe'                  => q{DEBUG: Checking possibility to resubscribe set $1 ($2) to node $3 ($4) which pulls $5 ($6) from $7 ($8)},
184     'dbg_failover_method'              => q{DEBUG: Failover method is $1},
185     'dbg_cluster_load'                 => q{DEBUG: Loading cluster configuration from $1},
186     'dbg_cluster_good'                 => q{DEBUG: Cluster state good},
187     'dbg_autofailover_check'           => q{DEBUG: Checking node $1 ($2) role is $3 (conninfo: $4)},
188     'dbg_autofailover_active_check'    => q{DEBUG: Initiate active check of $1 node $2},
189     'dbg_slonik_script'                => q{DEBUG: Running slonik script $1},
190     'err_generic'                      => q{ERROR: $1},
191     'err_no_database'                  => q{ERROR: Please specify a database name},
192     'err_no_cluster'                   => q{ERROR: Please specify a slony cluster name},
193     'err_no_host'                      => q{ERROR: Please specify a host},
194     'err_no_config'                    => q{ERROR: No valid config found},
195     'err_fail_config'                  => q{ERROR: Failed to load configuration},
196     'err_write_fail'                   => q{ERROR: Could not write to $1 "$2"},
197     'err_read_fail'                    => q{ERROR: Could not read from $1 "$2"},
198     'err_unlink_fail'                  => q{ERROR: Could not delete $1 "$2"},
199     'err_mkdir_fail'                   => q{ERROR: Unable to create $1 directory "$2"},
200     'err_execute_fail'                 => q{ERROR: Could not execute $1 "$2"},
201     'err_inactive'                     => q{ERROR: Node $1 is not active (state = $2)},
202     'err_cluster_empty'                => q{ERROR: Loaded cluster contains no nodes}, 
203     'err_cluster_offline'              => q{ERROR: Loaded cluster contains no reachable nodes}, 
204     'err_cluster_lone'                 => q{ERROR: Loaded cluster contains only 1 node}, 
205     'err_not_origin'                   => q{ERROR: Node $1 is not the origin of any sets},
206     'err_not_provider'                 => q{ERROR: Node $1 is not a provider of any sets},
207     'err_not_provider_sets'            => q{ERROR: Node $1 does not provide the sets required: need ($2) but provides ($3)},
208     'err_no_configuration'             => q{ERROR: Could not read configuration for node $1},
209     'err_must_enter_node_id'           => q{ERROR: You must enter a node id},
210     'err_not_a_node_id'                => q{ERROR: I have no knowledge of a node $1},
211     'err_same_node'                    => q{ERROR: Cant move from and to the same node},
212     'err_node_offline'                 => q{ERROR: $1 node ($2) is not available},
213     'err_incomplete_preamble'          => q{ERROR: Incomplete preamble},
214     'err_running_slonik'               => q{ERROR: Could not run slonik: $1},
215     'err_pgsql_connect'                => q{ERROR: Cannot connect to postgres server},
216     'slonik_output'                    => q{SLONIK: $1},
217     'exit_noaction'                    => q{Exiting, no action has been taken},
218     'exit'                             => q{Exited by $1}
219     },
220 'fr' => {
221     'usage'                            => q{-h <host> -p <port> -db <database> -cl <cluster name> -u <username> -P <password> -f <config file> (Option mot de passe pas recommandé; utiliser pgpass place)},
222     'title'                            => q{Slony-I failover (basculement) version de script $1},
223     'cluster_fixed'                    => q{Abandon de l'action de basculement: tous les noeuds d'origine / de fournisseurs maintenant sensible},
224     'cluster_failed'                   => q{Trouvé $1 Ã©choué noeuds, couchage pour $2 ms avant réessayer $3 de $4},
225     'load_cluster'                     => q{Obtenir une liste de noeuds de base de donnees...},
226     'load_cluster_fail'                => q{Impossible de lire la configuration du cluster $1},
227     'load_cluster_success'             => q{Chargé Slony-I v$1 groupe "$2" avec $3 noeuds lire Ã  partir du noeud Ã  $4:$5/$6},
228     'lag_detail'                       => q{Current informations noeud de décalage Ã  partir du noeud de configuration:},
229     'script_settings'                  => q{Utilisation de $1 lots de système de verrouillage, $2 FAILOVER et $3},
230     'generated_script'                 => q{Script généré "$1"},
231     'autofailover_init'                => q{Entrer dans le mode de autofailover},
232     'autofailover_init_cnf'            => q{Configuration Slony sera lu Ã  partir de $1 noeud},
233     'autofailover_init_pol'            => q{Vérifier toutes les $1ms},
234     'autofailover_init_ret'            => q{Noeuds défaillants seront rejugés $1 fois avec $2 ms sommeil},
235     'autofailover_init_set'            => q{Fournisseurs d'expédition Ã©choué $1 Ãªtre Ã©choué sur},
236     'autofailover_load_cluster'        => q{$1 Slony-I v$2 grappe "$3" avec $4 noeuds lire Ã  noeud $5},
237     'autofailover_proceed'             => q{De procéder Ã  failover:},
238     'autofailover_detail'              => q{Noeud défaillant: $1, noeud de sauvegarde: $2},
239     'autofailover_halt'                => q{Noeuds Impossible d'effectuer une failover pour $1 Ã©choué},
240     'autofailover_check_sub'           => q{Vérification noeud abonné $1},
241     'autofailover_check_sub_fail'      => q{Impossible de vérifier noeud abonné $1},
242     'autofailover_promote_find'        => q{Trouver plus Ã  jour abonné Ã  tous les jeux ($1) sur le noeud ne répond pas $2},
243     'autofailover_promote_found'       => q{Utilisation précédemment trouvé plus Ã  jour abonné Ã  tous les jeux ($1) sur le noeud ne répond pas $2},
244     'autofailover_promote_skip'        => q{Pas de failover requis pour le noeud ne répond pas $1 car il n'est ni l'origine ou un transitaire active de tous les jeux},
245     'autofailover_promote_fail'        => q{Impossible de trouver le noeud de sauvegarde approprié pour la promotion},
246     'autofailover_node_detail'         => q{Noeud $1 est souscrit Ã  $2 ($3) noeud $4 et fournit des ensembles de $5 Ã  retard $6 secondes (en cas d'événement $7)},
247     'autofailover_promote_best'        => q{Meilleur noeud pour la promotion est noeud $1 décalage = $2 secondes (événement $3)},
248     'autofailover_promote_unsuitable'  => q{Noeud $1 est inadapté pour la promotion},
249     'autofailover_unresponsive'        => q{Noeud d'origine ne répond pas détecté: $1},
250     'autofailover_unresponsive_prov'   => q{Noeud fournisseur ne répond pas détecté: $1},
251     'autofailover_unresponsive_subonly'=> q{Abonné ne répond pas détecté seulement de noeud: $1},
252     'autofailover_recovery_subonly'    => q{Recouvrement détecté de l'abonné ne répond pas seulement auparavant de noeud: $1},
253     'autofailover_pspec_check_fail'    => q{Impossible de se connecter au noeud $1: $2},
254     'autofailover_pspec_check'         => q{Obtenir un jugement objectif Ã  partir d'autres noeuds, les noeuds qui ne répondent pas apparentes sont : $1 (Noeuds défaillants = $2 de $3)},
255     'autofailover_pspec_check_sleep'   => q{Dormir pour $1 ms},
256     'autofailover_pspec_check_data'    => q{$1: Noeud $2 dit décalage de $3 -> $4 noeud est $5 secondes},
257     'autofailover_pspec_check_true'    => q{Tous les noeuds détectés pas confirmés comme Ã  la traîne par d'autres noeuds},
258     'autofailover_pspec_check_false'   => q{Pas tous les noeuds confirmé retard},
259     'autofailover_pspec_check_unknown' => q{Impossible de confirmer le statut de latence de tous les noeuds},
260     'autofailover_split_check'         => q{Autres noeuds ($1 sur $2) sont la majorité},
261     'autofailover_split_check_fail'    => q{Autres noeuds ($1) ne sont pas la majorité},
262     'interactive_head_name'            => q{Nom},
263     'interactive_head_status'          => q{Statut},
264     'interactive_head_providers'       => q{Fournisseur IDs},
265     'interactive_detail_1'             => q{Origine pour les jeux: },
266     'interactive_detail_2'             => q{Fournir des ensembles: },
267     'interactive_detail_3'             => q{Abonnements: },
268     'interactive_choose_node'          => q{S'il vous plaît choisissez le noeud Ã  déplacer tous les ensembles $1:},
269     'interactive_confirm'              => q{Vous avez choisi de passer ensembles $1 noeud $2 ($3). Est-ce correct [o/n]? },
270     'interactive_drop_nodes'           => q{Voulez-vous laisser tomber aussi les noeuds défaillants de la configuration de slony [o/n]?},
271     'interactive_action'               => q{Meilleur plan d'action est le plus susceptible de faire une $1. Voulez-vous continuer [o/n]?},
272     'interactive_surrender'            => q{Uable pour déterminer le meilleur plan d'action},
273     'interactive_write_script'         => q{Rédaction d'un script Ã  $1 $2 noeud Ã  $3},
274     'interactive_check_nodes'          => q{Vérification de la disponibilité des noeuds de base de donnees...},
275     'interactive_continue'             => q{Voulez-vous continuer [o/n]?},
276     'interactive_preserve'             => q{Préserver les chemins de souscription Ã  suivre le noeud d'origine (ne pas choisir en cas de doute) [o/n]?},
277     'interactive_aliases'              => q{Générer des alias sur la base de sl_node / set commentaires entre parenthèses (ne pas choisir en cas de doute) [o/n]?},
278     'interactive_summary'              => q{Résumé des noeuds Ã  passer Ã  failover:},
279     'interactive_node_info'            => q{Noeud : $1 ($2) $3 (conninfo $4)},
280     'interactive_run_script'           => q{Voulez-vous exécuter ce script maintenant [o/n]?},
281     'interactive_running'              => q{L'exécution du script maintenant. Cela peut prendre un certain temps; s'il vous plaît Ãªtre patient!},
282     'interactive_reason'               => q{S'il vous plaît entrer une brève reson pour cette action: },
283     'interactive_failover_detail_1'    => q{Avant d'aller plus loin s'il vous plaît envisager l'impact d'un failover (basculement) complet:},
284     'interactive_failover_detail_2'    => q{Le noeud vous ne parviennent pas au-dessus de cesse de participer au groupe de façon permanente jusqu'à ce qu'il soit Ã  reconstruire et souscrit},
285     'interactive_failover_detail_3'    => q{Si la panne est temporaire (c.-à-réseau / alimentation / facilement remplaçable matériel connexe) envisager d'attendre dehors},
286     'interactive_failover_detail_4'    => q{Ce type de failover est susceptible d'être plus une décision d'affaires que technique},
287     'info_all_nodes_available'         => q{INFO: Tous les noeuds sont disponibles},
288     'info_req_nodes_available'         => q{INFO: $1 of $2 noeuds sont disponibles. Pas de noeuds indisponibles sont souscrites Ã  l'ancienne origine},
289     'wrn_node_unavailable'             => q{ATTENTION: Noeud $1 disponible},
290     'wrn_req_unavailable'              => q{ATTENTION: Noeud Old origine ($1) est disponible, mais $2 abonnés ne sont pas disponibles},
291     'wrn_not_tested'                   => q{ATTENTION: Script pas testé avec Slony-I v$1},
292     'wrn_failover_issues'              => q{ATTENTION: Slony-I v$1 peut lutter pour basculer correctement avec plusieurs nÅ“uds défaillants (affecte v2.0-2.1)},
293     'note_autofail_fwd_only'           => q{AVIS: Versions antérieures Ã  la 2.2 Slony ne peuvent pas initier le basculement de seulement Ã©choué transmettre fournisseurs},
294     'note_fail_sub_only'               => q{AVIS: Versions antérieures Ã  la 2.2 Slony ne peuvent pas basculer abonnes seuls les noeuds, revenant Ã  failover_offile_subscriber_only = false},
295     'note_multiple_try'                => q{AVIS: Vous ne pouvez pas verrouiller plusieurs ensembles dans des blocs try dans la version $1 de retomber Ã  des jeux simples},
296     'note_reshape_cluster'             => q{AVIS: Vous devez supprimer les abonnés défaillants ou les ramener, puis réessayez Ã  MOVE SET},
297     'err_generic'                      => q{ERREUR: $1},
298     'err_no_database'                  => q{ERREUR: S'il vous plaît spécifier un base de donnees nom},
299     'err_no_cluster'                   => q{ERREUR: S'il vous plaît indiquez un nom de cluster slony},
300     'err_no_host'                      => q{ERREUR: S'il vous plaît spécifier un hôte},
301     'err_no_config'                    => q{ERREUR: Aucune configuration valide n'a Ã©té trouvée},
302     'err_fail_config'                  => q{ERREUR: Impossible de charger la configuration},
303     'err_write_fail'                   => q{ERREUR: Impossible d'écrire dans $1 "$2"},
304     'err_read_fail'                    => q{ERREUR: Impossible de lire $1 "$2"},
305     'err_unlink_fail'                  => q{ERREUR: Impossible de supprimer $1 "$2"},
306     'err_mkdir_fail'                   => q{ERREUR: Impossible de créer $1 répertoire "$2"},
307     'err_execute_fail'                 => q{ERREUR: Impossible d'exécuter $1 "$2"},
308     'err_inactive'                     => q{ERREUR: Noeud $1 n'est pas active (état = $2)},
309     'err_cluster_empty'                => q{ERREUR: Groupe chargé contient pas de noeuds},
310     'err_cluster_offline'              => q{ERREUR: Groupe chargé contient pas de noeuds accessibles},
311     'err_cluster_lone'                 => q{ERRRUE: Groupe chargé ne contient que 1 noeud},
312     'err_not_origin'                   => q{ERREUR: Noeud $1 n'est pas Ã  l'origine de tous les jeux},
313     'err_not_provider'                 => q{ERREUR: Noeud $1 n'est pas un fournisseur de tous les jeux},
314     'err_not_provider_sets'            => q{ERREUR: Noeud $1 ne fournit pas les ensembles nécessaires: le besoin ($2), mais fournit ($3)},
315     'err_no_configuration'             => q{ERREUR: Impossible de lire la configuration pour le noeud $1},
316     'err_must_enter_node_id'           => q{ERREUR: Vous devez entrer un id de noeud},
317     'err_not_a_node_id'                => q{ERREUR: Je n'ai pas connaissance d'un $1 de noeud},
318     'err_same_node'                    => q{ERREUR: Cant déplacer depuis et vers le même noeud},
319     'err_node_offline'                 => q{ERREUR: $1 noeud ($2) n'est pas disponible},
320     'err_incomplete_preamble'          => q{ERREUR: Préambule incomplète},
321     'err_running_slonik'               => q{ERREUR: Ne pouvait pas courir slonik: $1},
322     'err_pgsql_connect'                => q{ERREUR: Impossible de se connecter au serveur postgres},
323     'slonik_output'                    => q{SLONIK: $1},
324     'exit_noaction'                    => q{Quitter, aucune action n'a Ã©té prise},
325     'exit'                             => q{Quitter par $1}
326     }
327 );
328
329
330 # Setup date variables
331 my ($g_year, $g_month, $g_day, $g_hour, $g_min, $g_sec) = (localtime(time))[5,4,3,2,1,0];
332 my $g_date = sprintf ("%02d:%02d:%02d on %02d/%02d/%04d", $g_hour, $g_min, $g_sec, $g_day, $g_month+1, $g_year+1900);
333
334 # Handle command line options
335 Getopt::Long::Configure('no_ignore_case');
336 use vars qw{%opt};
337 die lookupMsg('usage') unless GetOptions(\%opt, 'host|H=s', 'port|p=i', 'dbname|db=s', 'clname|cl=s', 'dbuser|u=s', 'dbpass|P=s', 'cfgfile|f=s', 'infoprint|I', ) and keys %opt and ! @ARGV;
338
339 # Read configuration
340 if (defined($opt{cfgfile})) {
341     unless (getConfig($opt{cfgfile})) {
342         println(lookupMsg('err_no_config'));
343         exit(1);
344     }
345 }
346 else {
347     if (defined($opt{dbname})) {
348         $g_dbname = $opt{dbname};
349     }
350     if (defined($opt{clname})) {
351         $g_clname = $opt{clname};
352     }
353     if (defined($opt{host})) {
354         $g_dbhost = $opt{host};
355     }
356     if (defined($opt{port})) {
357         $g_dbport = $opt{port};
358     }
359     if (defined($opt{dbuser})) {
360         $g_dbuser = $opt{dbuser};
361     }
362     if (defined($opt{dbpass})) {
363         $g_dbpass = $opt{dbpass};
364     }
365 }
366
367 # Display message and die if any of the required configuration variables are missing
368 if (!defined($g_dbname)) {
369     println(lookupMsg('err_no_database'));
370     die lookupMsg('usage');
371 }
372 if (!defined($g_clname)) {
373     println(lookupMsg('err_no_cluster'));
374     die lookupMsg('usage');
375 }
376 if (!defined($g_dbhost)) {
377     println(lookupMsg('err_no_host'));
378     die lookupMsg('usage');
379 }
380
381
382 # Build conninfo from supplied datbase name/host/port
383 $g_dbconninfo = "dbname=$g_dbname;host=$g_dbhost;port=$g_dbport";
384
385 if (!defined($opt{infoprint})) {
386     # Check prefix directory and create if not present
387     unless(-e $g_prefix or mkdir $g_prefix) {
388         println(lookupMsg('err_mkdir_fail', 'prefix', $g_prefix));
389         exit(2);
390     }
391
392     if ($g_separate_working) {
393         if ($g_prefix !~ m/\/$/) {
394             $g_prefix .= "/";
395         }
396
397         # Get a uuid for working directory
398         $g_prefix .= getUUID($g_date);
399
400         # Create a working directory and setup log file
401         unless(-e $g_prefix or mkdir $g_prefix) {
402             println(lookupMsg('err_mkdir_fail', 'work', $g_prefix));
403         }
404     }
405 }
406
407 # Set postgres path if provided
408 if (defined($g_slonikpath) && ($g_slonikpath ne "")) {
409     $ENV{PATH} .= ":$g_slonikpath";
410 }
411
412 # Check if autofailover is enabled, if so check configuration and enter autofailover mode
413 if (($g_autofailover) && !defined($opt{infoprint})) {
414
415     # Write out a PID file
416     if (writePID($g_prefix, $g_logfile, $g_log_prefix, $g_pidfile)) {
417         $g_pid_written = true;
418     }
419     else {
420         cleanExit(1, "system");
421     }
422     
423     # Go into endless loop for autofailover
424     autoFailover($g_dbconninfo, $g_clname, $g_dbuser, $g_dbpass, $g_prefix, $g_logfile, $g_log_prefix);
425 }
426
427 # Read slony configuration and output some basic information
428 eval {
429     #local $| = 1;
430     println(lookupMsg('load_cluster', $g_prefix));
431     ($g_node_count, $g_version) = loadCluster($g_dbconninfo, $g_clname, $g_dbuser, $g_dbpass, $g_prefix, $g_logfile, $g_log_prefix);
432 };
433 if ($@) {
434     println(lookupMsg('load_cluster_fail', 'from supplied configuration'));
435     cleanExit(2, "system");
436 }
437
438 if (defined($opt{infoprint})) {
439     println(lookupMsg('load_cluster_success', $g_version, $g_clname, $g_node_count, $g_dbhost, $g_dbport, $g_dbname) . ":");
440     chooseNode("info", undef, undef, undef, 0);
441     exit(0);
442 }
443 else {
444     printlog($g_prefix,$g_logfile,$g_log_prefix,"*"x68 . "\n* ");
445     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('title', $g_script_version));
446     printlogln($g_prefix,$g_logfile,$g_log_prefix,"*"x68);
447 }
448
449 if ($g_node_count <= 0) {
450     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_cluster_empty'));
451     cleanExit(3, "system");
452 }
453 else {
454     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('load_cluster_success', $g_version, $g_clname, $g_node_count, $g_dbhost, $g_dbport, $g_dbname));
455     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('script_settings', $g_lockset_method, $g_failover_method, uc($g_resubscribe_method)));
456 }
457
458 # Output lag information between each node and node configuration was read from
459 if (loadLag($g_dbconninfo, $g_clname, $g_dbuser, $g_dbpass, $g_prefix, $g_logfile, $g_log_prefix) > 0) {
460     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('lag_detail'));
461     foreach (@g_lags) {
462         printlogln($g_prefix,$g_logfile,$g_log_prefix,"\t$_");
463     }
464     printlog($g_prefix,$g_logfile,$g_log_prefix,"\n");
465 }
466
467 # Prompt user to choose nodes to move sets from / to
468 $g_node_from = chooseNode("from", $g_prefix, $g_logfile, $g_log_prefix, 0);
469 if ($g_node_from == 0) {
470     cleanExit(4, "user");
471 }
472 elsif ($g_node_from == -1) {
473     cleanExit(5, "system");
474 }
475
476 $g_node_to = chooseNode("to", $g_prefix, $g_logfile, $g_log_prefix, $g_node_from);
477 if ($g_node_to == 0) {
478     cleanExit(6, "user");
479 }
480 elsif ($g_node_to == -1) {
481     cleanExit(7, "system");
482 }
483 elsif ($g_node_from == $g_node_to) {
484     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_same_node'));
485     cleanExit(8, "system");
486 }
487
488 # Check nodes are available and decide on action to take
489 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_check_nodes'));
490 ($g_available_node_count, $g_critical_node_count) = checkNodes($g_clname, $g_dbuser, $g_dbpass, $g_node_from, $g_node_to, $g_prefix, $g_logfile, $g_log_prefix);
491
492 if ($g_available_node_count <= 0) {
493     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_cluster_offline'));
494     cleanExit(9, "system");
495 }
496 elsif ($g_critical_node_count == -1) {
497     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_node_offline', 'Target new origin', $g_node_to));
498     cleanExit(10, "system");
499 }
500 elsif ($g_critical_node_count == -2) {
501     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_node_offline', 'Old origin', $g_node_from));
502     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_action', 'FAILOVER'));
503     $g_failover = true;
504 }
505 elsif ($g_critical_node_count == 0) {
506     if ($g_node_count == $g_available_node_count) {
507         printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('info_all_nodes_available'));
508     }
509     else {
510         printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('info_req_nodes_available', $g_available_node_count, $g_node_count));
511     }
512     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_action', 'MOVE SET'));
513 }
514 elsif ($g_critical_node_count > 0) {
515     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('wrn_req_unavailable', $g_node_from, $g_critical_node_count));
516     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('note_reshape_cluster'));
517     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit_noaction'));
518     cleanExit(11, "user");
519 }
520 else {
521     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_surrender'));
522     cleanExit(12, "system");
523 }
524 $g_input = <>;
525 chomp($g_input);
526 if ($g_input !~ /^[Y|O]$/i) {
527     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit_noaction'));
528     cleanExit(13, "user");
529 }
530
531 if (!$g_use_comment_aliases) {
532     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_aliases'));
533     $g_input = <>;
534     chomp($g_input);
535     if ($g_input =~ /^[Y|O]$/i) {
536         $g_use_comment_aliases = true;
537     }
538 }
539
540 if ($g_failover) {
541     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_summary'));
542
543     foreach (@g_failed) {
544         printlogln($g_prefix,$g_logfile,$g_log_prefix,"\t" . lookupMsg('interactive_node_info',$_->[0],($_->[4] // "unnamed"),(defined($_->[9]) ? "providing sets $_->[9]" : "sole subscriber"), $_->[2])); 
545     }
546
547     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_failover_detail_1'));
548     printlogln($g_prefix,$g_logfile,$g_log_prefix,"\t" . lookupMsg('interactive_failover_detail_2'));
549     printlogln($g_prefix,$g_logfile,$g_log_prefix,"\t" . lookupMsg('interactive_failover_detail_3'));
550     printlogln($g_prefix,$g_logfile,$g_log_prefix,"\t" . lookupMsg('interactive_failover_detail_4'));
551
552     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_drop_nodes'));
553     $g_input = <>;
554     if ($g_input ~~ /^[Y|O]$/i) {
555         $g_drop_failed = true;
556     }
557
558     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_reason'));
559     $g_reason = <>;
560     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_continue'));
561     $g_input = <>;
562     chomp($g_input);
563     if ($g_input !~ /^[Y|O]$/i) {
564         printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit_noaction'));
565         cleanExit(14, "user");
566     }
567
568     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_write_script', 'failover from', $g_node_from, $g_node_to));
569     $g_script = writeFailover($g_prefix, $g_dbconninfo, $g_clname, $g_dbuser, $g_dbpass, $g_node_from, $g_node_to, $g_subs_follow_origin, $g_use_comment_aliases, $g_logfile, $g_log_prefix);    
570 }
571 else {
572     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_preserve'));
573     $g_input = <>;
574     chomp($g_input);
575     if ($g_input =~ /^[Y|O]$/i) {
576         $g_subs_follow_origin = true;
577     }
578
579     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_reason'));
580     $g_reason = <>;
581
582     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_write_script', 'move all sets provided by', $g_node_from, $g_node_to));
583     $g_script = writeMoveSet($g_prefix, $g_dbconninfo, $g_clname, $g_dbuser, $g_dbpass, $g_node_from, $g_node_to, $g_subs_follow_origin, $g_use_comment_aliases, $g_logfile, $g_log_prefix);    
584 }
585
586 # Complete and run script if required
587 if (-e $g_script) {
588     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('generated_script', $g_script));
589     printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_run_script', $g_script));
590     $g_input = <>;
591     chomp($g_input);
592     if ($g_input =~ /^[Y|O]$/i) {
593         printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_running'));
594         unless (runSlonik($g_script, $g_prefix, $g_logfile, $g_log_prefix)) {
595             printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_execute_fail', 'slonik script', $g_script));
596         }
597     }
598     else {
599         printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit_noaction'));
600     }
601 }
602 else {
603     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_read_fail', 'slonik script', $g_script));
604     cleanExit(15, "system");
605 }
606
607 cleanExit(0, "script completion");
608
609 ###########################################################################################################################################
610
611 # Display exit message, insert log file into database if requested, delete any pid files and exit with the requested code
612 sub cleanExit {
613     my $exit_code = shift;
614     my $type = shift;
615
616     printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit', $type));
617
618     if ($g_log_to_db) {    
619         eval {
620            logDB("dbname=$g_logdb_name;host=$g_logdb_host;port=$g_logdb_port", $g_logdb_user, $g_logdb_pass, $exit_code, $g_reason, $g_prefix, $g_logfile, $g_log_prefix, $g_clname, $g_script);
621         };
622     }
623
624     if ($g_pid_written) {
625         removePID($g_prefix, $g_logfile, $g_log_prefix, $g_pidfile);
626     }
627
628     exit($exit_code);
629 }
630
631 # Exit on caught signal
632 sub sigExit {
633     cleanExit(100,'signal');    
634 }
635
636 # Check we can reach each node in the cluster and that it contains the Slony schema
637 sub checkNodes {
638     my $clname = shift;
639     my $dbuser = shift;
640     my $dbpass = shift;
641     my $from = shift;
642     my $to = shift;
643     my $prefix = shift;
644     my $logfile = shift;
645     my $log_prefix = shift;
646
647     my $dsn;
648     my $dbh;
649     my $sth;
650     my $query;
651     my $result_count = 0;
652     my $critical_count = 0;
653
654     my @subsets;
655     my @origsets;
656
657     undef @g_failed;
658     undef @g_unresponsive;
659     undef %g_backups;
660
661     foreach (@g_cluster) {
662         if ($_->[0] == $from) {
663             @origsets = split(',', $_->[3]); 
664             last;
665         }
666     }
667
668     foreach (@g_cluster) {
669         if ($g_debug) {
670             printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_cluster', $_->[0],($_->[1] // "<NONE>"),$_->[2],($_->[3] // "<NONE>"),$_->[4],($_->[5] // "<NONE>") . "(" . ($_->[8] // "<NONE>") . ")",$_->[6],($_->[7] // "<NONE>"),($_->[9] // "<NONE>") . " (" . ($_->[10] // "<NONE>") . ")"));
671         }
672             
673         $dsn = "DBI:Pg:$_->[2];";
674         eval {
675             $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
676             $query = "SELECT count(*) FROM pg_namespace WHERE nspname = ?";
677             $sth = $dbh->prepare($query);
678             $sth->bind_param(1, "_" . $clname);
679             $sth->execute();
680         
681             $result_count = $result_count+$sth->rows;        
682
683             $sth->finish;
684             $dbh->disconnect();
685
686         };
687         if ($@) {
688             # Critical count will be -1 if the new origin is down, -2 if the old origin is down or positive if subscribers to sets on old origin are down.
689             printlogln($prefix,$logfile,$log_prefix,lookupMsg('wrn_node_unavailable', $_->[0]));
690             if ($g_debug) {
691                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
692             }
693             if ($_->[0] == $to) {
694                 $critical_count = -1;        
695             }
696             elsif ($_->[0] == $from) {
697                 $critical_count = -2;        
698             }
699             else {
700                 foreach my $subprov (split(';', $_->[5])) {
701                     my ($node, $setlist) = (split('->', $subprov)) ;
702                     $node =~ s/n//g;
703                     $setlist =~ s/(\)|\(|s)//g;
704                     @subsets = (split(',', $setlist));
705
706                     if (($critical_count >= 0) && (checkSubscribesAnySets(\@origsets, \@subsets))) {
707                         $critical_count++;    
708                     }
709                 }
710             }
711             # Only push nodes with active subscribers to sets into failed list unless explicitly told to
712             if (($g_fail_subonly) || (defined($_->[9]))) {
713                 push(@g_failed, \@$_);
714                 $g_backups{$_->[0]} = $to;
715             }
716             push(@g_unresponsive, \@$_);
717         }    
718         
719     }
720     return ($result_count, $critical_count);
721 }
722
723 # Load information on all nodes in the Slony cluster into global @g_cluster:
724 # 0) no_id = Node id of this node 
725 # 1) no_provs =  Comma separated list of all provider node ids
726 # 2) no_conninfo =  Conninfo as recorded in sl_path
727 # 3) origin_sets = Comma separated list of set ids originating on this node
728 # 4) no_name = Node name; this is extracted from text between parentheses in sl_node.no_comment
729 # 5) no_sub_tree = Text representation of subscriptions in the form n<provider node id>->(s<set id>, ..)
730 # 6) no_status = Text representing the state of the node; either ACTIVE,INACTIVE or FAILED
731 # 7) sub_sets = Comma separated list of all set ids this node is subscribed to 
732 # 8) no_sub_tree_name = As per no_sub_tree but holds textual names extracted from sl_node.no_comment
733 # 9) prov_sets_active = Comma separated list of all set ids this node is actively forwarding
734 # 10) prov_sets = Comma separated list of all set ids this node is subscribed to and able to forward
735 sub loadCluster {
736     my $dbconninfo = shift;
737     my $clname = shift;
738     my $dbuser = shift;
739     my $dbpass = shift;
740     my $prefix = shift;
741     my $logfile = shift;
742     my $log_prefix = shift;
743
744     my $dsn;
745     my $dbh;
746     my $sth;
747     my $query;
748     my $version;
749     my $qw_clname;
750     undef @g_cluster;
751
752     if ($g_debug) {
753         printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_cluster_load', $dbconninfo));
754     }
755
756     $dsn = "DBI:Pg:$dbconninfo;";
757     eval {
758         $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
759         $qw_clname = $dbh->quote_identifier("_" . $clname);
760
761         $query = "SELECT $qw_clname.getModuleVersion()";
762         $sth = $dbh->prepare($query);
763         $sth->execute();
764         ($version) = $sth->fetchrow; 
765         $sth->finish;
766
767         $query = "WITH z AS (
768                 SELECT a.no_id, b.sub_provider AS no_prov,
769                     COALESCE(c.pa_conninfo,(SELECT pa_conninfo FROM $qw_clname.sl_path WHERE pa_server = $qw_clname.getlocalnodeid(?) LIMIT 1)) AS no_conninfo,
770                     array_to_string(array(SELECT set_id FROM $qw_clname.sl_set WHERE set_origin = a.no_id ORDER BY set_id),',') AS origin_sets,
771                     string_agg(CASE WHEN b.sub_receiver = a.no_id AND b.sub_forward AND b.sub_active THEN b.sub_set::text END, ',' ORDER BY b.sub_set) AS sub_sets,
772                     coalesce(trim(regexp_replace(substring(a.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_','g')), 'node' || a.no_id) AS no_name,
773                     'n' || b.sub_provider || '->(' || string_agg(CASE WHEN b.sub_receiver = a.no_id THEN 's' || b.sub_set END,',' ORDER BY b.sub_set,',') || ')' AS sub_tree,
774                     coalesce(trim(regexp_replace(substring(d.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_','g')), 'node' || b.sub_provider, '')
775                     || '->(' || string_agg(CASE WHEN b.sub_receiver = a.no_id THEN coalesce(trim(regexp_replace(e.set_comment, '[^0-9A-Za-z]', '_', 'g')), 'set' || b.sub_set) END,',' ORDER BY b.sub_set) || ')' AS sub_tree_name,
776                     CASE " . ((substr($version,0,3) >= 2.2) ? "WHEN a.no_failed THEN 'FAILED' " : "") . "WHEN a.no_active THEN 'ACTIVE' ELSE 'INACTIVE' END AS no_status,
777                     array_to_string(array(SELECT DISTINCT sub_set::text FROM $qw_clname.sl_subscribe WHERE sub_provider = a.no_id AND sub_active ORDER BY sub_set),',') AS prov_sets_active,
778                     string_agg(CASE WHEN b.sub_receiver = a.no_id THEN b.sub_set::text END,',' ORDER BY b.sub_set,',') AS prov_sets    
779                 FROM $qw_clname.sl_node a
780                 LEFT OUTER JOIN $qw_clname.sl_subscribe b ON a.no_id = b.sub_receiver
781                 LEFT OUTER JOIN $qw_clname.sl_path c ON c.pa_server = a.no_id AND c.pa_client = $qw_clname.getlocalnodeid(?)
782                 LEFT OUTER JOIN $qw_clname.sl_node d ON b.sub_provider = d.no_id
783                 LEFT OUTER JOIN $qw_clname.sl_set e ON b.sub_set = e.set_id
784                 GROUP BY b.sub_provider, a.no_id, a.no_comment, c.pa_conninfo, d.no_comment, a.no_active
785                 ORDER BY a.no_id
786                 )
787                 SELECT no_id,
788                     nullif(string_agg(no_prov::text, ',' ORDER BY no_prov),'') AS no_provs,
789                     no_conninfo,
790                     nullif(string_agg(origin_sets::text, ',' ORDER BY origin_sets),'') AS origin_sets,
791                     no_name,
792                     nullif(string_agg(sub_tree, ';' ORDER BY sub_tree),'') AS no_sub_tree,
793                     no_status,
794                     nullif(string_agg(sub_sets::text, ',' ORDER BY prov_sets),'') AS sub_sets,
795                     nullif(string_agg(sub_tree_name, ';' ORDER BY sub_tree_name),'') AS no_sub_tree_name,
796                     nullif(string_agg(prov_sets_active::text, ',' ORDER BY prov_sets_active),'') AS prov_sets_active,
797                     nullif(string_agg(prov_sets::text, ',' ORDER BY sub_sets),'') AS prov_sets
798                 FROM z GROUP BY no_id, no_conninfo, no_name, no_status";
799         $sth = $dbh->prepare($query);
800
801         $sth->bind_param(1, "_" . $clname);
802         $sth->bind_param(2, "_" . $clname);
803
804         $sth->execute();
805
806         while (my @node = $sth->fetchrow) { 
807             #printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', join(' - ', @node)));
808             push(@g_cluster,  \@node);
809         }
810
811         $sth->finish;
812
813         $dbh->disconnect();
814     };
815     if ($@) {
816         if ($g_debug) {
817             printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
818         }
819         die lookupMsg('err_pgsql_connect');
820     }
821     else {
822         #if (substr($version,0,1) < 2) {
823         #    printlogln($prefix,$logfile,$log_prefix,lookupMsg('wrn_not_tested', $version));
824         #}
825         if (($g_use_try_blocks) && ($g_lockset_method eq 'multiple') && (substr($version,0,3) <= 9.9)) {
826             # It's currently not possible to lock multiple sets at a time within a try block (v2.2.2), leave the logic in and set a high version number for now.
827             printlogln($prefix,$logfile,$log_prefix, lookupMsg('note_multiple_try', $version));
828             $g_lockset_method = 'single';
829         }
830         if (substr($version,0,3) >= 2.2) {
831             $g_failover_method = 'new';
832             $g_resubscribe_method = 'resubscribe';
833         }
834         else {
835             unless ($g_silence_notice) {
836                 if ((substr($version,0,3) >= 2.0) && (substr($version,0,3) < 2.2)) {
837                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('wrn_failover_issues', $version));
838                 }
839                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('note_autofail_fwd_only'));
840                 $g_silence_notice = true;
841             }
842             if ($g_fail_subonly) {
843                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('note_fail_sub_only'));
844                 $g_fail_subonly = false;
845             }
846         }
847         
848     }
849
850     return (scalar(@g_cluster), $version);
851 }
852
853 # Load all sets originating on a node into global @g_sets
854 sub loadSets {
855     my $dbconninfo = shift;
856     my $clname = shift;
857     my $nodenumber = shift;
858     my $dbuser = shift;
859     my $dbpass = shift;
860     my $prefix = shift;
861     my $logfile = shift;
862     my $log_prefix = shift;
863     
864     my $dsn;
865     my $dbh;
866     my $sth;
867     my $query;
868     my $qw_clname;
869
870     @g_sets = ();
871     
872     $dsn = "DBI:Pg:$dbconninfo;";
873     eval {
874         $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
875         $qw_clname = $dbh->quote_identifier("_" . $clname);
876         $query = "SELECT set_id, trim(regexp_replace(set_comment,'[^0-9,A-Z,a-z]','_','g')) FROM $qw_clname.sl_set WHERE set_origin = ? ORDER BY set_id;";
877
878         $sth = $dbh->prepare($query);
879         $sth->bind_param(1, $nodenumber);
880
881         $sth->execute();
882
883         while (my @set = $sth->fetchrow) { 
884             push(@g_sets,  \@set);
885         }
886
887         $sth->finish;
888         $dbh->disconnect();
889     };
890     if ($@) {
891         if ($g_debug) {
892             printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
893         }
894         die lookupMsg('err_pgsql_connect');
895     }
896
897     return scalar(@g_sets);
898 }
899
900 # Load information regarding replication lag from sl_status into @g_lags 
901 # If loading from a node that is not the intended origin then this information might not be that accurate/useful
902 sub loadLag {
903     my $dbconninfo = shift;
904     my $clname = shift;
905     my $dbuser = shift;
906     my $dbpass = shift;
907     my $prefix = shift;
908     my $logfile = shift;
909     my $log_prefix = shift;
910
911     my $dsn;
912     my $dbh;
913     my $sth;
914     my $query;
915     my $qw_clname;
916
917     @g_lags = ();
918
919     $dsn = "DBI:Pg:$dbconninfo;";
920     eval {
921         $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
922         $qw_clname = $dbh->quote_identifier("_" . $clname);
923         $query = "SELECT a.st_origin || ' (' || coalesce(trim(regexp_replace(substring(b.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_', 'g')), 'node' || b.no_id) || ')<->'
924                 || a.st_received || ' (' || coalesce(trim(regexp_replace(substring(c.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_', 'g')), 'node' || c.no_id) || ') Events: '
925                 || a.st_lag_num_events || ' Time: ' || a.st_lag_time 
926             FROM $qw_clname.sl_status a
927             INNER JOIN $qw_clname.sl_node b on a.st_origin = b.no_id
928             INNER JOIN $qw_clname.sl_node c on a.st_received = c.no_id";
929
930         $sth = $dbh->prepare($query);
931         $sth->execute();
932
933         while (my $lag = $sth->fetchrow) { 
934             push(@g_lags,  $lag);
935         }
936
937         $sth->finish;
938         $dbh->disconnect();
939     };
940     if ($@) {
941         if ($g_debug) {
942             printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
943         }
944         die lookupMsg('err_pgsql_connect');
945     }
946
947     return scalar(@g_lags);
948 }
949
950 # Prompt user for nodes to an from in interactive mode and do some checking
951 sub chooseNode {
952     my $type = shift;
953     my $prefix = shift;
954     my $logfile = shift;
955     my $log_prefix = shift;
956     my $last_choice = shift;
957     my $line;
958     my $choice;
959     my %options;
960     my $ok;
961     my @sets_from;
962     my @sets_to;
963     my $found = false;
964
965     $line = sprintf "%-4s %-14s %-10s %-24s %-s\n", lookupMsg('interactive_head_id'), lookupMsg('interactive_head_name'), lookupMsg('interactive_head_status'), lookupMsg('interactive_head_providers'), lookupMsg('interactive_head_config');
966     printlog($prefix,$logfile,$log_prefix,"$line");
967     $line = sprintf "%-4s %-14s %-10s %-24s %-s\n", "="x(length(lookupMsg('interactive_head_id'))), "="x(length(lookupMsg('interactive_head_name'))), "="x(length(lookupMsg('interactive_head_status'))), "="x(length(lookupMsg('interactive_head_providers'))), "="x(length(lookupMsg('interactive_head_config')));
968     printlog($prefix,$logfile,$log_prefix,"$line");
969
970     foreach (@g_cluster) {
971         $line = sprintf "%-4s %-14s %-10s %-24s %-s\n", $_->[0], $_->[4], $_->[6], ($_->[1] // "<NONE>"), (lookupMsg('interactive_detail_1') . ($_->[3] // "<NONE>"));
972         printlog($prefix,$logfile,$log_prefix,"$line");
973         $line = sprintf "%-55s %-s\n", " ", (lookupMsg('interactive_detail_2') . ($_->[7] // "<NONE>"));
974         printlog($prefix,$logfile,$log_prefix,"$line");
975         $line = sprintf "%-55s %-s\n", " ", (lookupMsg('interactive_detail_3') . ($_->[5] // "<NONE>"));
976         printlogln($prefix,$logfile,$log_prefix,"$line");
977         $options{$_->[0]} = {name => $_->[4], sets => ($_->[3] // ""), status => $_->[6], provider => $_->[7]};
978     }
979     if ($type !~ m/info/i) {
980         printlog($prefix,$logfile,$log_prefix,lookupMsg('interactive_choose_node', $type));
981         $choice = <>;
982         chomp($choice);
983     
984         if(exists($options{$choice})) {
985             if ($options{$choice}->{status} ne "ACTIVE") {
986                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_inactive', $choice, lc($options{$choice}->{status})));
987                 $choice = -1;
988             }
989             elsif (($type =~ m/from/i) && (length(trim($options{$choice}->{sets})) <= 0)) {
990                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_origin', $choice));
991                 $choice = -1;
992             }    
993             elsif ($type =~ m/to/i) {
994                 if (length(trim($options{$choice}->{provider})) <= 0) {
995                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_provider', $choice));
996                     $choice = -1;
997                 }
998                 else {
999                     foreach my $old_origin (@g_cluster) {
1000                         if ($old_origin->[0] == $last_choice) {
1001                             @sets_from = split(',', $old_origin->[3]);
1002                             @sets_to =  split(',', $options{$choice}->{provider});
1003                             if (checkProvidesAllSets(\@sets_from, \@sets_to)) {
1004                                 $found = true;
1005                             }
1006                             else {
1007                                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_provider_sets',$choice,$old_origin->[3],$options{$choice}->{providers}));
1008                                 $choice = -1;
1009                             }
1010                             last;
1011                         }
1012                     }
1013                     unless ($found) {
1014                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_no_configuration', $last_choice));
1015                         $choice = -1;
1016                     } 
1017                 }
1018             }    
1019             else {
1020                 printlog($prefix,$logfile,$log_prefix,lookupMsg('interactive_confirm',$type,$choice,$options{$choice}->{name}));
1021                 $ok = <>;
1022                 chomp($ok);    
1023                 if ($ok !~ /^[Y|O]$/i) {
1024                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('exit_noaction'));
1025                     $choice = 0;
1026                 }
1027             }
1028         }
1029         elsif (!length($choice)) {
1030             printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_must_enter_node_id'));
1031             $choice = -1;
1032         }
1033         else {
1034             printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_a_node_id', $choice));
1035             $choice = -1;
1036         }
1037     }
1038
1039     return $choice;
1040 }
1041
1042 # Write a slonik preamble section using information pulled into @g_cluster and @g_sets by loadCluster() and loadSets() functions
1043 sub writePreamble {
1044     my $filename = shift;
1045     my $dbconninfo = shift;
1046     my $clname = shift;
1047     my $dbuser = shift;
1048     my $dbpass = shift;
1049     my $sets = shift;
1050     my $aliases = shift;
1051     my $prefix = shift;
1052     my $logfile = shift;
1053     my $log_prefix = shift;
1054     my $comment_all_failed = shift;
1055     my $set_count;
1056     my $line_prefix;
1057     my $success = false;
1058
1059     my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1060     my $date = sprintf ("%02d:%02d:%02d on %02d/%02d/%04d", $hour, $min, $sec, $day, $month+1, $year+1900);
1061
1062     if (open(SLONFILE, ">", $filename)) {    
1063         print SLONFILE ("# Script autogenerated on $date\n\n");
1064         print SLONFILE ("######\n# Preamble (cluster structure)\n######\n\n# Cluster name\n");
1065         if ($aliases) {
1066             print SLONFILE ("DEFINE slony_cluster_name $clname;\n");
1067             print SLONFILE ("CLUSTER NAME = \@slony_cluster_name;\n\n");
1068         }
1069         else {
1070             print SLONFILE ("CLUSTER NAME = $clname;\n\n");
1071         }
1072         foreach (@g_cluster) {
1073             $line_prefix = '';
1074             if (($comment_all_failed) && (exists $g_backups{$_->[0]})) {
1075                 $line_prefix = "# (Node $_->[0] unavailable) ";
1076             }
1077             elsif (!$g_fail_subonly) {
1078                 foreach my $unresponsive (@g_unresponsive) {
1079                     if (($_->[0] == $unresponsive->[0]) && !defined($_->[9]) && ($g_failover_method eq 'new')) {
1080                         $line_prefix = "# (Node $_->[0] unavailable subscriber only) ";
1081                     }
1082                 }
1083             }
1084             print SLONFILE ("# Preamble for node $_->[0] named $_->[4]\n");
1085             if ($aliases) {
1086                 print SLONFILE ($line_prefix . "DEFINE $_->[4] $_->[0];\n");
1087                 print SLONFILE ($line_prefix . "DEFINE $_->[4]_conninfo '$_->[2]';\n");
1088                 print SLONFILE ($line_prefix . "NODE \@$_->[4] ADMIN CONNINFO = \@$_->[4]_conninfo;\n\n");
1089             }
1090             else {
1091                 print SLONFILE ($line_prefix . "NODE $_->[0] ADMIN CONNINFO = '$_->[2]';\n\n");
1092             }
1093             if (($aliases) && ($sets)) {
1094                 $set_count = loadSets($dbconninfo, $clname, $_->[0], $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
1095                 if ($set_count > 0) {
1096                     print SLONFILE ("# Sets provided (currently) by node $_->[0]\n");
1097                     foreach my $set (@g_sets) {
1098                         print SLONFILE ($line_prefix . "DEFINE $set->[1] $set->[0];\n");
1099                     }
1100                     print SLONFILE ("\n");
1101                 }
1102             }
1103         }    
1104         $success = true;
1105     }
1106     else {
1107         printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_write_fail', "script", $filename));
1108         $success = false; 
1109     }
1110     return $success;
1111 }
1112
1113 # Write slonik commands to move sets
1114 sub writeMoveSet {
1115     my $prefix = shift;
1116     my $dbconninfo = shift;
1117     my $clname = shift;
1118     my $dbuser = shift;
1119     my $dbpass = shift;
1120     my $from = shift;
1121     my $to = shift;
1122     my $subs = shift;
1123     my $aliases = shift;
1124     my $logfile = shift;
1125     my $log_prefix = shift;
1126     my $from_name;
1127     my $to_name;
1128     my $set_count;
1129     my $line_prefix;
1130     my $try_prefix = "";
1131     my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1132     my $filetime = sprintf ("%02d_%02d_%04d_%02d:%02d:%02d", $day, $month+1, $year+1900, $hour, $min, $sec);
1133     my $filename = $prefix . "/" . $clname . "-move_sets_from_" . $from . "_to_" . $to . "_on_" . $filetime . ".scr";
1134
1135     if ($g_use_try_blocks) {
1136         $try_prefix = "\t";
1137     }
1138  
1139     my @subprov_name;
1140     my $subprov_idx;
1141     my $subprov;
1142     my ($node, $setlist);
1143     my ($node_name, $setlist_name);
1144     my @subsets;
1145
1146     unless (writePreamble($filename, $dbconninfo, $clname, $dbuser, $dbpass, true, $aliases, $prefix, $logfile, $log_prefix, true)) {
1147         printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_incomplete_preamble'));
1148     }
1149
1150     foreach (@g_cluster) {
1151         if ($_->[0] == $from) {
1152             $from_name = $_->[4];
1153         }
1154         elsif ($_->[0] == $to) {
1155             $to_name = $_->[4];
1156         }
1157     }
1158
1159     if (open(SLONFILE, ">>", $filename)) {
1160
1161         print SLONFILE ("######\n# Actions (changes to cluster structure)\n######\n");
1162         
1163         $set_count = loadSets($dbconninfo, $clname, $from, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
1164         if ($set_count > 0) {
1165
1166             if ($g_lockset_method ne "single") {
1167                 if ($g_use_try_blocks) {
1168                     print SLONFILE ("TRY {\n");                
1169                 }
1170                 foreach (@g_sets) {
1171                     if ($aliases) {    
1172                         print SLONFILE ($try_prefix . "ECHO 'Locking set $_->[1] ($_->[0])';\n");
1173                         print SLONFILE ($try_prefix . "LOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n");
1174                     }
1175                     else {
1176                         print SLONFILE ($try_prefix . "ECHO 'Locking set $_->[0]';\n");
1177                         print SLONFILE ($try_prefix . "LOCK SET ( ID = $_->[0], ORIGIN = $from);\n");
1178                     }
1179                 
1180                 }
1181                 print SLONFILE ("\n");
1182                 foreach (@g_sets) {
1183                     if ($aliases) {    
1184                         print SLONFILE ($try_prefix . "ECHO 'Moving set $_->[1] ($_->[0])';\n");
1185                         print SLONFILE ($try_prefix . "MOVE SET ( ID = \@$_->[1], OLD ORIGIN = \@$from_name, NEW ORIGIN = \@$to_name);\n");
1186                     }
1187                     else {
1188                         print SLONFILE ($try_prefix . "ECHO 'Moving set $_->[0]';\n");
1189                         print SLONFILE ($try_prefix . "MOVE SET ( ID = $_->[0], OLD ORIGIN = $from, NEW ORIGIN = $to);\n");
1190                     }
1191                 
1192                 }                
1193                 if ($g_use_try_blocks) {
1194                     print SLONFILE ("}\nON ERROR {\n");
1195                     foreach (@g_sets) {
1196                         if ($aliases) {    
1197                             print SLONFILE ($try_prefix . "ECHO 'Unlocking set $_->[1] ($_->[0])';\n");
1198                             print SLONFILE ($try_prefix . "UNLOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n");
1199                         }
1200                         else {
1201                             print SLONFILE ($try_prefix . "ECHO 'Unlocking set $_->[0]';\n");
1202                             print SLONFILE ($try_prefix . "UNLOCK SET ( ID = $_->[0], ORIGIN = $from);\n");
1203                         }
1204                     }
1205                     print SLONFILE ("\tEXIT 1;\n}\nON SUCCESS {\n");
1206                 }
1207                 if ($aliases) {    
1208                     print SLONFILE ($try_prefix . "WAIT FOR EVENT (ORIGIN = \@$from_name, CONFIRMED = ALL, WAIT ON = \@$from_name, TIMEOUT = 0);\n");
1209                 }
1210                 else {
1211                     print SLONFILE ($try_prefix . "WAIT FOR EVENT (ORIGIN = $from, CONFIRMED = ALL, WAIT ON = $from, TIMEOUT = 0);\n");
1212                 }
1213                 if ($g_use_try_blocks) {
1214                     print SLONFILE ("}\n");
1215                 }
1216             }
1217             foreach (@g_sets) {
1218                 if ($g_lockset_method eq "single") {
1219                     if ($aliases) {    
1220                         print SLONFILE ("\nECHO 'Moving set $_->[1] ($_->[0])';\n");
1221                         if ($g_use_try_blocks) {
1222                             print SLONFILE ("TRY {\n");
1223                         }
1224                         print SLONFILE ($try_prefix . "LOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n");
1225                         print SLONFILE ($try_prefix . "MOVE SET ( ID = \@$_->[1], OLD ORIGIN = \@$from_name, NEW ORIGIN = \@$to_name);\n");
1226                         if ($g_use_try_blocks) {
1227                             print SLONFILE ("}\nON ERROR {\n" . $try_prefix . "UNLOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n" . $try_prefix . "EXIT 1;\n}\n");
1228                         }
1229                         print SLONFILE ("WAIT FOR EVENT (ORIGIN = \@$from_name, CONFIRMED = ALL, WAIT ON = \@$from_name, TIMEOUT = 0);\n");
1230                     }
1231                     else {
1232                         print SLONFILE ("\nECHO 'Moving set $_->[0]';\n");
1233                         if ($g_use_try_blocks) {
1234                             print SLONFILE ("TRY {\n");
1235                         }
1236                         print SLONFILE ($try_prefix . "LOCK SET ( ID = $_->[0], ORIGIN = $from);\n");
1237                         print SLONFILE ($try_prefix . "MOVE SET ( ID = $_->[0], OLD ORIGIN = $from, NEW ORIGIN = $to);\n");
1238                         if ($g_use_try_blocks) {
1239                             print SLONFILE ("}\nON ERROR {\n" . $try_prefix . "UNLOCK SET ( ID = $_->[0], ORIGIN = $from);\n" . $try_prefix . "EXIT 1;\n}\n");
1240                         }
1241                         print SLONFILE ("WAIT FOR EVENT (ORIGIN = $from, CONFIRMED = ALL, WAIT ON = $from, TIMEOUT = 0);\n");
1242                     }
1243                 }    
1244                 if (($subs) && ($g_resubscribe_method eq 'subscribe')) { 
1245     
1246                     foreach my $other_subs (@g_cluster) {
1247                         if (($other_subs->[6] eq "ACTIVE") && ($other_subs->[0] != $from) && ($other_subs->[0] != $to)) {
1248
1249                             if (exists $g_backups{$other_subs->[0]}) {
1250                                 $line_prefix = "# (Node $other_subs->[0] unavailable) ";
1251                             }
1252                             else {
1253                                 $line_prefix = '';
1254                             }
1255
1256                             # mess here needs cleaning up
1257                             @subprov_name = (split(';', $other_subs->[8]));
1258                             $subprov_idx = 0;
1259                             foreach $subprov (split(';', $other_subs->[5])) {
1260                                 ($node, $setlist) = (split('->', $subprov)) ;
1261                                 ($node_name, $setlist_name) = (split('->', $subprov_name[$subprov_idx])) ;
1262                                 $subprov_idx++;
1263                                 $node =~ s/n//g;
1264                                 $setlist =~ s/(\)|\(|s)//g;
1265                                 @subsets = (split(',', $setlist)) ;
1266
1267                                 if ($g_debug) {
1268                                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_resubscribe', $_->[1], $_->[0], $other_subs->[0], $other_subs->[4], $setlist, $setlist_name, $node, $node_name));
1269                                 }    
1270
1271                                 if ($_->[0] ~~ @subsets) {
1272                                     if ($node == $from) {
1273                                         if ($aliases) {
1274                                             print SLONFILE ($line_prefix . 
1275                                                 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $to_name ($to) -> " .
1276                                                 "receiver $other_subs->[4] ($other_subs->[0])';\n");
1277                                                    print SLONFILE ($line_prefix . 
1278                                                 "SUBSCRIBE SET ( ID = \@$_->[1], PROVIDER = \@$to_name, " .
1279                                                 "RECEIVER = \@$other_subs->[4], FORWARD = YES);\n");
1280                                         }
1281                                         else {
1282                                             print SLONFILE ($line_prefix . 
1283                                                 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $to -> " .
1284                                                 "receiver $other_subs->[0]';\n");
1285                                             print SLONFILE ($line_prefix . "SUBSCRIBE SET ( ID = $_->[0], PROVIDER = $to, " .
1286                                                 "RECEIVER = $other_subs->[0], FORWARD = YES);\n");
1287                                         }
1288                                     }
1289                                     else {
1290                                         if ($aliases) {
1291                                             print SLONFILE ($line_prefix . 
1292                                                 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $node_name ($node) -> " . 
1293                                                 "receiver $other_subs->[4] ($other_subs->[0])';\n");
1294                                             print SLONFILE ($line_prefix . "SUBSCRIBE SET ( ID = \@$_->[1], PROVIDER = \@$node_name, " .
1295                                                 "RECEIVER = \@$other_subs->[4], FORWARD = YES);\n");
1296                                             }
1297                                             else {
1298                                                 print SLONFILE ($line_prefix . 
1299                                                 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $node -> " .
1300                                                 "receiver $other_subs->[0]';\n");
1301                                                 print SLONFILE ($line_prefix . "SUBSCRIBE SET ( ID = $_->[0], PROVIDER = $node, " .
1302                                                 "RECEIVER = $other_subs->[0], FORWARD = YES);\n");
1303                                         }
1304                                     }
1305                                 }
1306                             }
1307                         }
1308                     }
1309                 }    
1310             }
1311
1312             if (($subs) && ($g_resubscribe_method eq 'resubscribe')) { 
1313
1314                 foreach my $other_subs (@g_cluster) {
1315                     if (($other_subs->[6] eq "ACTIVE") && ($other_subs->[0] != $from) && ($other_subs->[0] != $to)) {
1316                         if (exists $g_backups{$other_subs->[0]}) {
1317                             $line_prefix = "# (Node $other_subs->[0] unavailable) ";
1318                         }
1319                         else {
1320                             $line_prefix = '';
1321                         }
1322
1323                         @subprov_name = (split(';', $other_subs->[8]));
1324                         $subprov_idx = 0;
1325                         foreach $subprov (split(';', $other_subs->[5])) {
1326                             ($node, $setlist) = (split('->', $subprov)) ;
1327                             ($node_name, $setlist_name) = (split('->', $subprov_name[$subprov_idx])) ;
1328                             $subprov_idx++;
1329                             $node =~ s/n//g;
1330     
1331                             print SLONFILE ("\n");
1332                             if ($node == $from) {
1333                                 if ($aliases) {
1334                                     print SLONFILE ($line_prefix .
1335                                         "ECHO 'Issuing resubscribe for provider $to_name ($to) -> receiver $other_subs->[4] ($other_subs->[0])';\n");
1336                                     print SLONFILE ($line_prefix .
1337                                         "RESUBSCRIBE NODE ( ORIGIN = \@$to_name, PROVIDER = \@$to_name, RECEIVER = \@$other_subs->[4]);\n");
1338                                  }
1339                                  else {
1340                                      print SLONFILE ($line_prefix .
1341                                         "ECHO 'Issuing resubscribe for provider $to -> receiver $other_subs->[0]';\n");
1342                                     print SLONFILE ($line_prefix . 
1343                                         "RESUBSCRIBE NODE ( ORIGIN = $to, PROVIDER = $to, RECEIVER = $other_subs->[0] );\n");
1344                                  }            
1345                             }
1346                             else {
1347                                 if ($aliases) {
1348                                     print SLONFILE ($line_prefix .
1349                                         "ECHO 'Issuing resubscribe for provider $node_name ($node) -> receiver $other_subs->[4] ($other_subs->[0])';\n");
1350                                     print SLONFILE ($line_prefix . 
1351                                         "RESUBSCRIBE NODE ( ORIGIN = \@$to_name, PROVIDER = \@$node_name, RECEIVER = \@$other_subs->[4]);\n");
1352                                 }
1353                                 else {
1354                                     print SLONFILE ($line_prefix .
1355                                         "ECHO 'Issuing resubscribe for provider $node -> receiver $other_subs->[0]';\n");
1356                                     print SLONFILE ($line_prefix .
1357                                         "RESUBSCRIBE NODE ( ORIGIN = $to, PROVIDER = $node, RECEIVER = $other_subs->[0]);\n");
1358                                 }
1359                             }
1360                         }
1361                     }
1362                 }
1363             }
1364
1365         }
1366
1367         if ($aliases) {    
1368             print SLONFILE ("\nECHO 'All sets originating from $from_name (id $from) have been moved to $to_name (id $to), ensure you modify any existing slonik scripts to reflect the new origin';\n");
1369         }
1370         else {
1371             print SLONFILE ("\nECHO 'All sets originating from node $from have been moved to node $to, ensure you modify the any existing slonik scripts to reflect the new origin';\n");
1372         }
1373         close (SLONFILE);
1374     }
1375     else {
1376         printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_write_fail', "script", $filename));
1377     }
1378     return $filename;
1379 }
1380
1381 # Write slonik commands to failover sets
1382 sub writeFailover {
1383     my $prefix = shift;
1384     my $dbconninfo = shift;
1385     my $clname = shift;
1386     my $dbuser = shift;
1387     my $dbpass = shift;
1388     my $from = shift;
1389     my $to = shift;
1390     my $subs = shift;
1391     my $aliases = shift;
1392     my $logfile = shift;
1393     my $log_prefix = shift;
1394     my $filename;
1395     my $written;
1396     my $event_node;
1397     my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1398     my $filetime = sprintf ("%02d_%02d_%04d_%02d:%02d:%02d", $day, $month+1, $year+1900, $hour, $min, $sec);
1399     my $sets = false;
1400
1401     my $subprov_idx;
1402     my @subprov_name;
1403     my ($node, $setlist);
1404     my ($node_name, $setlist_name);
1405     my @subsets;
1406     my @subsets_name;
1407     my $set_idx;
1408     my @dropped;
1409
1410     if (defined($from) && defined($to)) {
1411         $filename = $prefix . "/" . $clname . "-failover_from_" . $from . "_to_" . $to . "_on_" . $filetime . ".scr";
1412     }
1413     else {
1414         $filename = $prefix . "/" . $clname . "-autofailover_on_" . $filetime . ".scr";
1415     }
1416
1417     if ($g_failover_method ne 'new') {
1418         # For pre 2.2 failover with multiple nodes, we attempt to resubscribe sets and drop other failed providers;
1419         # This will never work as well as 2.2+ failover behaviour (infact failover may not work as all in 2.0/2.1 with multiple failed nodes)
1420         # We also need to define the sets in the preamble for this.
1421         $sets = true;
1422     }
1423
1424     unless (writePreamble($filename, $dbconninfo, $clname, $dbuser, $dbpass, $sets, $aliases, $prefix, $logfile, $log_prefix, false)) {
1425         printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_incomplete_preamble'));
1426     }
1427
1428     if (open(SLONFILE, ">>", $filename)) {
1429
1430         print SLONFILE ("######\n# Actions (changes to cluster structure)\n######\n\n");
1431         if ($g_debug) {
1432             printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_failover_method',$g_failover_method));
1433         }
1434
1435         # If we are on pre 2.2 we need to drop failed subscriber nodes first regardless
1436         if ($g_failover_method ne 'new') {
1437             foreach (@g_failed) {
1438                 if (!defined($_->[3])) {
1439                     foreach my $backup (@g_cluster) {
1440                         if ($backup->[0] == $g_backups{$_->[0]}) {  # this backup node candidate is in the list of suitable nodes for {failed node}
1441                             foreach my $subscriber (@g_cluster) {
1442                                 if (defined($subscriber->[1]) && $subscriber->[1] == $_->[0] && $subscriber->[0] != $backup->[0]) {
1443                                     # mess here needs cleaning up
1444                                     @subprov_name = (split(';', $subscriber->[8]));
1445                                     $subprov_idx = 0;
1446                                     foreach my $subprov (split(';', $subscriber->[5])) {
1447                                         ($node, $setlist) = (split('->', $subprov)) ;
1448                                         ($node_name, $setlist_name) = (split('->', $subprov_name[$subprov_idx])) ;
1449                                         $subprov_idx++;
1450                                         $node =~ s/n//g;
1451     
1452                                         if ($node == $_->[0]) {
1453                                             if ($aliases) {
1454                                                 print SLONFILE ("ECHO 'Resubscribing all sets on receiver $subscriber->[4] provided by other failed node $_->[4] to backup node $backup->[4]';\n");
1455                                             }
1456                                             else {
1457                                                 print SLONFILE ("ECHO 'Resubscribing all sets on receiver $subscriber->[0]  provided by other failed node $_->[0] to backup node $backup->[0]';\n");
1458                                             }
1459                                             $setlist =~ s/(\)|\(|s)//g;
1460                                             @subsets = (split(',', $setlist));
1461                                             $setlist_name =~ s/(\)|\()//g;
1462                                             @subsets_name = (split(',', $setlist_name));
1463                                         
1464                                             $set_idx = 0;
1465                                             foreach my $subset (@subsets) {
1466                                                 if ($aliases) {
1467                                                     print SLONFILE ("SUBSCRIBE SET (ID = \@$subsets_name[$set_idx], PROVIDER = \@$backup->[4], RECEIVER = \@$subscriber->[4], FORWARD = YES);\n");
1468                                                     print SLONFILE ("WAIT FOR EVENT (ORIGIN = \@$backup->[4], CONFIRMED = \@$subscriber->[4], WAIT ON = \@$backup->[4]);\n");
1469                                                 }
1470                                                 else {
1471                                                     print SLONFILE ("SUBSCRIBE SET (ID = $subset, PROVIDER = $backup->[0], RECEIVER = $subscriber->[0], FORWARD = YES);\n");
1472                                                     print SLONFILE ("WAIT FOR EVENT (ORIGIN = $backup->[0], CONFIRMED = $subscriber->[0], WAIT ON = $backup->[0]);\n");
1473                                                 }
1474                                                 $set_idx++;
1475                                             }
1476                                             print SLONFILE ("\n");
1477                                         }
1478                                     }
1479     
1480                                     if ($aliases) {
1481                                         print SLONFILE ("ECHO 'Dropping other failed node $_->[4] ($_->[0])';\n");
1482                                          print SLONFILE ("DROP NODE (ID = \@$_->[4], EVENT NODE = \@$backup->[4]);\n\n");
1483                                     }
1484                                     else {
1485                                         print SLONFILE ("ECHO 'Dropping other failed node $_->[0]';\n");
1486                                         print SLONFILE ("DROP NODE (ID = $_->[0], EVENT NODE = $backup->[0]);\n\n");
1487                                     }   
1488                                     push(@dropped, $_->[0]);
1489                                 }
1490                                 else {
1491                                     # The node is failed, but there are no downstream subscribers
1492                                 }
1493                             }
1494                             last;
1495                         }
1496                     }
1497                 }
1498             }
1499         }
1500
1501         foreach (@g_failed) {
1502             if (($g_failover_method eq 'new') || defined($_->[3])) {
1503                 foreach my $backup (@g_cluster) {
1504                     if ($backup->[0] == $g_backups{$_->[0]}) {
1505                         ## Here we have both details of the backup node and the failed node
1506                         if ($aliases) {
1507                             print SLONFILE ("ECHO 'Failing over slony cluster from $_->[4] (id $_->[0]) to $backup->[4] (id $backup->[0])';\n");
1508                         }
1509                         else {
1510                             print SLONFILE ("ECHO 'Failing over slony cluster from node $_->[0] to node $backup->[0]';\n");
1511                         }   
1512                         last;
1513                     }
1514                 }
1515             }
1516         }
1517
1518         print SLONFILE ("FAILOVER (\n\t");
1519         $written = 0;
1520         foreach (@g_failed) {
1521             if (($g_failover_method eq 'new') || defined($_->[3])) {
1522                 foreach my $backup (@g_cluster) {
1523                     if ($backup->[0] == $g_backups{$_->[0]}) {
1524                         ## Here we have both details of the backup node and the failed node
1525                         if ($g_failover_method eq 'new') {
1526                             if( $written != 0 ) {
1527                                 print SLONFILE (",\n\t");
1528                             }
1529                             print SLONFILE ("NODE = (");
1530                         }
1531                         else {
1532                             if( $written != 0 ) {
1533                                 print SLONFILE ("\n);\nFAILOVER (\n\t");
1534                             }
1535                         }
1536                         if ($aliases) {
1537                             print SLONFILE ("ID = \@$_->[4], BACKUP NODE = \@$backup->[4]");
1538                         }
1539                         else {
1540                             print SLONFILE ("ID = $_->[0], BACKUP NODE = $backup->[0]");
1541                         }
1542                         if ($g_failover_method eq 'new') {
1543                             print SLONFILE (")");
1544                         }
1545                         last;
1546                     }
1547                 }
1548                 $written++;
1549             }
1550         }
1551         print SLONFILE ("\n);\n\n");
1552
1553         if ($g_drop_failed) {
1554             if (($g_failover_method eq 'new')  && (scalar(@g_failed) > 1)) {
1555                 foreach (@g_failed) {
1556                     if ($aliases) {
1557                         print SLONFILE ("ECHO 'Dropping failed node $_->[4] ($_->[0])';\n");
1558                     }
1559                     else {
1560                         print SLONFILE ("ECHO 'Dropping failed node $_->[0]';\n");
1561                     }   
1562                 }
1563
1564                 print SLONFILE ("DROP NODE (ID = '");
1565                 undef $event_node;
1566             }
1567             $written = 0;
1568             foreach (@g_failed) {
1569                 foreach my $backup (@g_cluster) {
1570                     if ($backup->[0] == $g_backups{$_->[0]}) {
1571                         if (!defined($event_node)) {
1572                             if ($aliases) {
1573                                 $event_node = $backup->[4];
1574                             }
1575                             else {
1576                                 $event_node = $backup->[0];
1577                             }
1578                         } 
1579                         if (($g_failover_method eq 'new')  && (scalar(@g_failed) > 1)) {
1580                             if( $written != 0 ) {
1581                                 print SLONFILE (",");
1582                             }
1583                             ## Don't bother trying to define array values 
1584                             #if ($aliases) {
1585                             #    print SLONFILE "\@$_->[4]";
1586                             #}
1587                             #else {
1588                                 print SLONFILE $_->[0];
1589                             #}
1590                             $written++;
1591                         }
1592                         elsif (($g_failover_method eq 'new') || defined($_->[3]) || !($_->[0] ~~ @dropped)) {
1593                             if ($aliases) {
1594                                 print SLONFILE ("ECHO 'Dropping failed node $_->[4] ($_->[0])';\n");
1595                                 print SLONFILE ("DROP NODE (ID = \@$_->[4], EVENT NODE = \@$backup->[4]);\n\n");
1596                             }
1597                             else {
1598                                 print SLONFILE ("ECHO 'Dropping failed node $_->[0]';\n");
1599                                 print SLONFILE ("DROP NODE (ID = $_->[0], EVENT NODE = $backup->[0]);\n\n");
1600                             }
1601                         }
1602                         last;
1603                     }
1604                 }   
1605             }
1606             if (($g_failover_method eq 'new')  && (scalar(@g_failed) > 1)) {
1607                 if ($aliases) {
1608                      print SLONFILE ("', EVENT NODE = \@$event_node);\n");
1609                 }
1610                 else {
1611                      print SLONFILE ("', EVENT NODE = $event_node);\n");
1612                 }
1613             }
1614         }
1615
1616     }
1617     else {
1618         printlog($prefix,$logfile,$log_prefix,lookupMsg('err_write_fail', "script", $filename));
1619     }
1620     return $filename;
1621
1622 }
1623
1624 # Used to return informational text from the %message hashes, pretty much entirely stolen from check_postgres (http://bucardo.org)
1625 sub lookupMsg {
1626     my $name = shift || '?';
1627     my $line_call;
1628     my $text;
1629
1630     if (exists $message{$g_lang}{$name}) {
1631         $text = $message{$g_lang}{$name};
1632     }
1633     elsif (exists $message{'en'}{$name}) {
1634         $text = $message{'en'}{$name};
1635     }
1636     else {
1637         $line_call = (caller)[2];
1638         $text = qq{Failed to lookup text "$name" at line $line_call};
1639     }
1640
1641     my $x=1;
1642     {
1643         my $val = $_[$x-1];
1644         $val = '?' if ! defined $val;
1645         last unless $text =~ s/\$$x/$val/g;
1646         $x++;
1647         redo;
1648     }
1649     return $text;
1650 }
1651
1652 # Trim quotes off a string
1653 sub qtrim {
1654     my $string = shift;
1655     $string =~ s/^('|")+//;
1656     $string =~ s/('|")+$//;
1657     return $string;
1658 }
1659
1660 # Trim a string
1661 sub trim($) {
1662     my $string = shift;
1663     $string =~ s/^\s+//;
1664     $string =~ s/\s+$//;
1665     return $string;
1666 }
1667
1668 # Print command with a linefeed
1669 sub println {
1670     print ((@_ ? join($/, @_) : $_), $/);
1671 }
1672
1673 # Print to stdout and the logfile, doing some replacements allong the way for logging
1674 sub printlog {
1675     my $prefix = shift;
1676     my $logfile_name = shift;
1677     my $log_prefix = shift;
1678     my $message = shift;
1679     my $logfile;
1680     my $date;
1681
1682     print $message;
1683
1684     if (defined($logfile_name)) {
1685
1686         # Do we have to do this all the time? Perhaps could check parameters first
1687         if ($logfile_name =~ /^\//i) {
1688             $logfile = strftime($logfile_name, localtime);
1689         }
1690         else {
1691             $logfile = "$prefix/" . strftime($logfile_name, localtime);
1692         }
1693     
1694         if ($log_prefix =~ m/(\%[mt])/) {
1695             my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1696             my ($h_sec, $h_msec) = gettimeofday;
1697             $date = sprintf ("%02d-%02d-%04d %02d:%02d:%02d.%03d", $day, $month+1, $year+1900, $hour, $min, $sec, $h_msec/1000);
1698             $log_prefix =~ s/\%m/$date/g;
1699     
1700             $date = sprintf ("%02d-%02d-%04d %02d:%02d:%02d", $day, $month+1, $year+1900, $hour, $min, $sec);
1701             $log_prefix =~ s/\%t/$date/g;
1702         }
1703         if ($log_prefix =~ m/(\%p)/) {
1704             $log_prefix =~ s/\%p/$g_pid/g;
1705         }
1706
1707         if (open(LOGFILE, ">>", $logfile)) {
1708             print LOGFILE $log_prefix . " " . $message;
1709             close (LOGFILE);
1710         }
1711         else {
1712             println(lookupMsg('err_write_fail', "logfile", $logfile));
1713         }
1714     }
1715 }
1716
1717 # Printlog command with a linefeed
1718 sub printlogln {
1719     printlog ($_[0], $_[1], $_[2], $_[3] . $/);
1720 }
1721
1722 # Insert details of any action into a database table
1723 sub logDB {
1724     my $dbconninfo = shift;
1725     my $dbuser = shift;
1726     my $dbpass = shift;
1727     my $exit_code = shift;
1728     my $reason = shift;
1729     my $prefix = shift;
1730     my $logfile = shift;
1731     my $log_prefix = shift;
1732     my $clname = shift;
1733     my $script = shift;
1734
1735     my $dsn;
1736     my $dbh;
1737     my $sth;
1738     my $query;
1739
1740     my $results;
1741     my $script_data;
1742
1743     unless($results = (read_file($logfile))) { 
1744         printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_read_fail', "logfile", $logfile));
1745     }
1746
1747     if (defined($script) && (-e $script)) {
1748         unless ($script_data = (read_file($script))) { 
1749             printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_read_fail', "script file", $script));
1750         }
1751     }
1752     else {
1753         $script_data = "No script data was generated.";
1754         $script = "No script generated.";
1755     }
1756
1757     $dsn = "DBI:Pg:$dbconninfo;";
1758     eval {
1759         $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
1760         $query = "INSERT INTO public.failovers (reason, exit_code, results, script, cluster_name)
1761               VALUES (?, ?, ?, ?, ?)";
1762
1763         $sth = $dbh->prepare($query);
1764
1765         $sth->bind_param(1, $reason);
1766         $sth->bind_param(2, $exit_code);
1767         $sth->bind_param(3, $results);
1768         $sth->bind_param(4, $script . ":\n" . $script_data);
1769         $sth->bind_param(5, $clname);
1770
1771         $sth->execute();
1772
1773         $sth->finish;
1774         $dbh->disconnect();
1775     };
1776     if ($@) {
1777         if ($g_debug) {
1778             printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
1779         }
1780         die lookupMsg('err_pgsql_connect');
1781     }
1782
1783     return true;
1784 }
1785
1786 # Returns a uuid used for the failover script directory
1787 sub getUUID {
1788     my $date_string = shift;
1789     my $g_ug  = new Data::UUID;
1790     my $g_uuid = $g_ug->create_from_name("failover_script", $date_string);
1791     my $g_uuid_str  = $g_ug->to_string($g_uuid);
1792     return $g_uuid_str;
1793 }
1794
1795 # Write out a PID file
1796 sub writePID {
1797     my $prefix = shift;
1798     my $logfile = shift;
1799     my $log_prefix = shift;
1800     my $pidfile_name = shift;
1801     my $pidfile;
1802     my $success = true;
1803  
1804     if ($pidfile_name =~ /^\//i) {
1805         $pidfile = $pidfile_name;
1806     }
1807     else {
1808         $pidfile = "$prefix/" . $pidfile_name;
1809     }
1810     eval {
1811         open (PIDFILE, ">", $pidfile);
1812         print PIDFILE $$;
1813         close (PIDFILE);
1814     };
1815     if ($@) {
1816         if ($g_debug) {
1817             printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_generic', $!));       
1818         }
1819         printlogln($prefix,$logfile,$log_prefix, lookupMsg('err_write_fail', "pid file", $pidfile));
1820         $success = false;
1821     }
1822     return $success;
1823 }
1824
1825 # Remove the PID file
1826 sub removePID {
1827     my $prefix = shift;
1828     my $logfile = shift;
1829     my $log_prefix = shift;
1830     my $pidfile_name = shift;
1831     my $pidfile;
1832     my $success = true;
1833
1834     if ($pidfile_name =~ /^\//i) {
1835         $pidfile = $pidfile_name;
1836     }
1837     else {
1838         $pidfile = "$prefix/" . $pidfile_name;
1839     }
1840     eval {
1841         if (-f $pidfile) {
1842             unlink $pidfile;
1843         }
1844         else {
1845             printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_generic', 'PID file never existed to be removed'));
1846         } 
1847     };
1848     if ($@) {
1849         if ($g_debug) {
1850             printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_generic', $!));
1851         }
1852         printlogln($prefix,$logfile,$log_prefix, lookupMsg('err_unlink_fail', "pid file", $pidfile));
1853         $success = false;
1854     }
1855     return $success;
1856 }
1857
1858 # Check all sets from an originationg node are contained in the list provided by another node
1859 sub checkProvidesAllSets { 
1860     my ($originSets, $providerSets) = @_;
1861     my %test_hash;
1862
1863     undef @test_hash{@$originSets};       # add a hash key for each element of @$originSets
1864     delete @test_hash{@$providerSets};    # remove all keys for elements of @$providerSets
1865
1866     return !%test_hash;              # return false if any keys are left in the hash
1867 }
1868
1869 # Check any sets from an originationg node are contained in the list subscribed to by another node
1870 sub checkSubscribesAnySets {
1871     my ($originSets, $subscriberSets) = @_;
1872     my $before;
1873     my $after;
1874     my %test_hash;
1875
1876     undef @test_hash{@$originSets};       # add a hash key for each element of @$originSets
1877     $before = scalar(keys %test_hash);
1878     delete @test_hash{@$subscriberSets};    # remove all keys for elements of @$subscriberSets
1879     $after = scalar(keys %test_hash);
1880     return ($before != $after);        # return false if no keys were removed from the hash
1881 }
1882
1883 # Read configuration details from a configuration file
1884 sub getConfig {
1885     my $cfgfile = shift;
1886     my @fields;
1887     my $success = false;
1888     my $value;
1889
1890     if (open(CFGFILE, "<", $cfgfile)) {
1891         foreach (<CFGFILE>) {
1892             chomp $_;
1893             for ($_) {
1894                 s/\r//;
1895                 #s/\#.*//;
1896                 s/#(?=(?:(?:[^']|[^"]*+'){2})*+[^']|[^"]*+\z).*//;
1897             }
1898             if (length(trim($_))) {
1899                 @fields = split('=', $_, 2);
1900                 given(lc($fields[0])) {
1901                     $value = qtrim(trim($fields[1]));
1902                     when(/\blang\b/i) {
1903                         $g_lang = $value;
1904                     }
1905                     when(/\bslony_database_host\b/i) {
1906                         $g_dbhost = $value;
1907                     }
1908                     when(/\bslony_database_port\b/i) {
1909                         $g_dbport = checkInteger($value);
1910                     }
1911                     when(/\bslony_database_name\b/i) {
1912                         $g_dbname = $value;
1913                     }
1914                     when(/\bslony_database_user\b/i) {
1915                         $g_dbuser = $value; 
1916                     }
1917                     when(/\bslony_database_password\b/i) {
1918                         $g_dbpass = $value; 
1919                     }
1920                     when(/\bslony_cluster_name\b/i) {
1921                         $g_clname = $value; 
1922                     }
1923                     when(/\benable_debugging\b/i) {
1924                         $g_debug = checkBoolean($value);
1925                     }
1926                     when(/\bprefix_directory\b/i) {
1927                         $g_prefix = $value;
1928                     }
1929                     when(/\bseparate_working_directory\b/i) {
1930                         $g_separate_working = checkBoolean($value);
1931                     }
1932                     when(/\bpid_filename\b/i) {
1933                         $g_pidfile = $value;
1934                     }
1935                     when(/\bfailover_offline_subscriber_only\b/i) {
1936                         $g_fail_subonly = checkBoolean($value);
1937                     }
1938                     when(/\bdrop_failed_nodes\b/i) {
1939                         $g_drop_failed = checkBoolean($value);
1940                     }
1941                     when(/\blog_line_prefix\b/i) {
1942                         $g_log_prefix = $value;
1943                     }
1944                     when(/\blog_filename\b/i) {
1945                         $g_logfile = $value;
1946                     }
1947                     when(/\blog_to_postgresql\b/i) {
1948                         $g_log_to_db = checkBoolean($value);
1949                     }
1950                     when(/\blog_database_host\b/i) {
1951                         $g_logdb_host = $value;
1952                     }
1953                     when(/\blog_database_port\b/i) {
1954                         $g_logdb_port = checkInteger($value);
1955                     }
1956                     when(/\blog_database_name\b/i) {
1957                         $g_logdb_name = $value;
1958                     }
1959                     when(/\blog_database_user\b/i) {
1960                         $g_logdb_user = $value;
1961                     }
1962                     when(/\blog_database_password\b/i) {
1963                         $g_logdb_pass = $value;
1964                     }
1965                     when(/\benable_try_blocks\b/i) {
1966                         $g_use_try_blocks = checkBoolean($value);
1967                     }
1968                     when(/\bpull_aliases_from_comments\b/i) {
1969                         $g_use_comment_aliases = checkBoolean($value);
1970                     }
1971                     when(/\bslonik_path\b/i) {
1972                         $g_slonikpath = $value;
1973                     }
1974                     when(/\blockset_method\b/i) {
1975                         $g_lockset_method = $value;
1976                     }
1977                     when(/\benable_autofailover\b/i) {
1978                         $g_autofailover = checkBoolean($value);
1979                     }
1980                     when(/\bautofailover_poll_interval\b/i) {
1981                         $g_autofailover_poll_interval = checkInteger($value);
1982                     }
1983                     when(/\bautofailover_node_retry\b/i) {
1984                         $g_autofailover_retry = checkInteger($value);
1985                     }
1986                     when(/\bautofailover_sleep_time\b/i) {
1987                         $g_autofailover_retry_sleep = checkInteger($value);
1988                     }
1989                     when(/\bautofailover_forwarding_providers\b/i) {
1990                         $g_autofailover_provs = checkBoolean($value);
1991                     }
1992                     when(/\bautofailover_config_any_node\b/i) {
1993                         $g_autofailover_config_any = checkBoolean($value);
1994                     }
1995                     when(/\bautofailover_perspective_sleep_time\b/i) {
1996                         $g_autofailover_perspective_sleep = checkInteger($value);
1997                     }
1998                     when(/\bautofailover_majority_only\b/i) {
1999                         $g_autofailover_majority_only = checkBoolean($value);
2000                     }
2001                     when(/\bautofailover_is_quorum\b/i) {
2002                         $g_autofailover_is_quorum  = checkBoolean($value);
2003                     }
2004                 }
2005             }
2006         }
2007         close (CFGFILE);
2008
2009         $success = true;
2010     }
2011     else {
2012         println(lookupMsg('err_fail_config'));
2013     }
2014
2015     return $success;
2016 }
2017
2018 # Interpret a textual representation of a boolean value 
2019 sub checkBoolean {
2020     my $text = shift;
2021     my $value = undef;
2022     if ( grep /^$text$/i, ("y","yes","t","true","on") ) {
2023         $value = true;
2024     }
2025     elsif ( grep /^$text$/i, ("n","no","f","false","off") ) {
2026         $value = false;
2027     }
2028     return $value;
2029 }
2030
2031 # Check if a text value is a valid integer
2032 sub checkInteger {
2033     my $integer = shift;
2034     my $value = undef;
2035
2036     if (($integer * 1) eq $integer) {
2037         $value = int($integer);
2038     }
2039     return $value;
2040 }
2041
2042 # Run a slonik command and capture all output via autoflushing channel
2043 sub runSlonik {
2044     my $script = shift;
2045     my $prefix = shift;
2046     my $logfile = shift;
2047     my $log_prefix = shift;
2048     my $success;
2049
2050     if ($g_debug) {
2051          printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_slonik_script', $script));
2052     }
2053     if (open(SLONIKSTATUS, "-|", "slonik $script 2>&1")) {
2054         while (<SLONIKSTATUS>) {
2055             printlogln($prefix,$logfile,$log_prefix,lookupMsg('slonik_output', $_));
2056         }
2057         close(SLONIKSTATUS);
2058         $success = true;
2059     }
2060     else {
2061         printlogln($prefix,$logfile,$log_prefix, lookupMsg('err_running_slonik', $!));
2062         $success = false;
2063     }
2064     return $success;
2065 }
2066
2067 # Experimental logic to watch the cluster status and perform an automatic failover
2068 sub autoFailover {
2069     my $dbconninfo = shift;
2070     my $clname = shift;
2071     my $dbuser = shift;
2072     my $dbpass = shift;
2073     my $prefix = shift;
2074     my $logfile = shift;
2075     my $log_prefix = shift;
2076
2077     my $cluster_time;
2078     my $failed;
2079     my $actions;
2080     my $current_retry;
2081     my $cluster_loaded;
2082     my $cluster_loaded_from;
2083     my @cluster;
2084     my $node_count;
2085     my $version;
2086
2087     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init'));
2088     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_cnf', ($g_autofailover_config_any ? 'any' : 'specified target')));
2089     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_pol', $g_autofailover_poll_interval));
2090     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_ret', $g_autofailover_retry, $g_autofailover_retry_sleep));
2091     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_set', ($g_autofailover_provs ? 'will' : 'will not')));
2092
2093     while (true) {  
2094         # Probe current cluster configuration every minute 
2095         if (!defined($cluster_time) || (time()-$cluster_time > 60)) {
2096
2097             $cluster_loaded = false;
2098             if (!defined($cluster_time) || !$g_autofailover_config_any) {
2099                 eval {
2100                     ($node_count, $version) = loadCluster($dbconninfo, $clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2101                     die lookupMsg('err_cluster_empty') if ($node_count == 0);
2102                     @cluster = @g_cluster;
2103                     die lookupMsg('err_cluster_lone') if ($node_count == 1);
2104                     $cluster_loaded = true;
2105                     $cluster_loaded_from = 'conninfo specified in config';
2106                 };
2107                 if ($@) {
2108                     printlogln($prefix,$logfile,$log_prefix, lookupMsg('load_cluster_fail', 'from supplied configuration'));
2109                     if ($g_debug) {
2110                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2111                     }
2112                 }
2113             }
2114             else {
2115                 foreach (@cluster) {
2116                     if ($_->[6]  eq "ACTIVE") {
2117                         unless ($cluster_loaded) {
2118                             eval {
2119                                 ($node_count, $version) = loadCluster($_->[2], $clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2120                                 die lookupMsg('err_cluster_empty') if ($node_count == 0);
2121                                 @cluster = @g_cluster;
2122                                 die lookupMsg('err_cluster_lone') if ($node_count == 1);
2123                                 $cluster_loaded = true;
2124                                 $cluster_loaded_from = $_->[0];
2125                             };
2126                             if ($@) {
2127                                 printlogln($prefix,$logfile,$log_prefix, lookupMsg('load_cluster_fail', 'from node ' . $_->[0] . ': trying next node'));
2128                                 if ($g_debug) {
2129                                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2130                                 }
2131                             }
2132                         }
2133                     }
2134                 }
2135             }
2136
2137             if ($cluster_loaded) {
2138                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_load_cluster', (!defined($cluster_time) ? "Loaded" : "Reloaded"), $version, $clname, $node_count, $cluster_loaded_from));
2139                 $cluster_time = time();
2140             }
2141             else {
2142                 printlogln($prefix,$logfile,$log_prefix, lookupMsg('load_cluster_fail', 'from any node'));
2143             }
2144         }
2145
2146         if ($cluster_loaded) {
2147             $current_retry = 0; 
2148             undef $failed;
2149             while(($current_retry <= $g_autofailover_retry) && ((!defined($failed)) || ($failed > 0))) {
2150                 # Check status of cluster
2151                 $failed = checkFailed($clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2152                 if ($failed == 0) {
2153                     if ($g_debug) {
2154                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_cluster_good'));
2155                     }
2156                     if ($current_retry > 0) {
2157                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('cluster_fixed'));
2158                     }
2159                 }
2160                 $current_retry++;
2161                 if (($failed > 0) && ($current_retry <= $g_autofailover_retry)) {
2162                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('cluster_failed', $failed,$g_autofailover_retry_sleep,$current_retry,$g_autofailover_retry));
2163                     usleep($g_autofailover_retry_sleep * 1000);
2164                 }
2165             }
2166             if ($failed > 0) {
2167                 if ((!$g_autofailover_majority_only || checkSplit($prefix, $logfile, $log_prefix)) && (($g_autofailover_perspective_sleep <= 0) || checkPerspective($clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix))) {
2168                     $actions = findBackup($clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2169                     if ($actions > 0) {
2170                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_proceed'));
2171                         foreach my $failed ( keys %g_backups ) {
2172                             printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_detail', $failed, $g_backups{$failed}));
2173                         }
2174                         $g_script = writeFailover($prefix, $dbconninfo, $clname, $dbuser, $dbpass, undef, undef, $g_subs_follow_origin, $g_use_comment_aliases, $logfile, $log_prefix);   
2175                         #unless (runSlonik($g_script, $prefix, $logfile, $log_prefix)) {
2176                         #    printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_execute_fail', 'slonik script', $g_script));
2177                         #}
2178                         $cluster_loaded = false;
2179
2180                         print "SCRIPT: $g_script\n";
2181                         exit(0);
2182                     }
2183                     else {
2184                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_halt', $failed));
2185                     }
2186                 }
2187             }
2188             usleep($g_autofailover_poll_interval * 1000);
2189         }
2190         else {
2191             sleep(10);
2192         }
2193
2194     }
2195 }
2196
2197 # Count of failed and live nodes to perform very basic split-brain check
2198 sub checkSplit {
2199     my $prefix = shift;
2200     my $logfile = shift;
2201     my $log_prefix = shift;
2202
2203     my $majority = false; 
2204     my $failed = scalar(@g_unresponsive);
2205     my $survivers = (scalar(@g_cluster) - scalar(@g_unresponsive));
2206
2207     if ($survivers > $failed) {
2208         $majority = true; 
2209         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_split_check', $survivers, ($survivers+$failed)));
2210     }
2211     elsif (($survivers == $failed) && $g_autofailover_is_quorum) {
2212         $majority = true; 
2213         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_split_check', ($survivers . '+quorum'), ($survivers+$failed)));
2214     }
2215     else {
2216         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_split_check_fail', $survivers));
2217     }
2218
2219     return $majority;
2220 }
2221
2222 # Check each nodes perspective of the failure to try to ensure the issue isn't that this script just can't connect to the origin/provider
2223 # The idea here is just to wait for a short period of time and see if the lag time for the nodes has increased by the same amount
2224 sub checkPerspective {
2225     my $clname = shift;
2226     my $dbuser = shift;
2227     my $dbpass = shift;
2228     my $prefix = shift;
2229     my $logfile = shift;
2230     my $log_prefix = shift;
2231
2232     my $dsn;
2233     my $dbh;
2234     my $sth;
2235     my $query;
2236     my $qw_clname;
2237     my $param_on;
2238     my $agreed = false;
2239     my @unresponsive_ids;
2240     my $lag_idx;
2241     my $lag_confirmed;
2242     my @lag_info1;
2243     my @lag_info2;
2244     my $bad = 0;
2245
2246     foreach (@g_unresponsive) {
2247         push(@unresponsive_ids, $_->[0]);
2248     }
2249     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check', join(", ", @unresponsive_ids), scalar(@g_unresponsive), scalar(@g_cluster)));
2250
2251     foreach (@g_cluster) {
2252         unless ($_->[0] ~~ @unresponsive_ids)  {
2253             $dsn = "DBI:Pg:$_->[2];";
2254             eval {
2255                 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2256                 $qw_clname = $dbh->quote_identifier("_" . $clname);
2257
2258                 $query = "SELECT a.st_origin, a.st_received, extract(epoch from a.st_lag_time)::integer
2259                         FROM _test_replication.sl_status a
2260                         INNER JOIN _test_replication.sl_node b on a.st_origin = b.no_id
2261                         INNER JOIN _test_replication.sl_node c on a.st_received = c.no_id
2262                         WHERE a.st_received IN (" . substr('?, ' x scalar(@unresponsive_ids), 0, -2) . ") ORDER BY a.st_origin, a.st_received;";
2263
2264                 $sth = $dbh->prepare($query);
2265
2266                 $param_on = 1; 
2267                 foreach (@unresponsive_ids) {
2268                     $sth->bind_param($param_on, $_);
2269                     $param_on++;
2270                 }
2271                 $sth->execute();
2272
2273                 while (my @node_lag = $sth->fetchrow) { 
2274                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_data', 'Check1', $_->[0], $node_lag[0], $node_lag[1], $node_lag[2]));
2275                     push(@lag_info1, \@node_lag);
2276                 }
2277
2278                 $sth->finish;
2279                 $dbh->disconnect();
2280             };
2281             if ($@) {
2282                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_fail', $_->[0], $@));
2283                 $bad++;
2284             } 
2285         }
2286     }
2287
2288     if ($bad == 0) {
2289         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_sleep', $g_autofailover_perspective_sleep));
2290         usleep($g_autofailover_perspective_sleep * 1000);
2291
2292         foreach (@g_cluster) {
2293             unless ($_->[0] ~~ @unresponsive_ids)  {
2294                 $dsn = "DBI:Pg:$_->[2];";
2295                 eval {
2296                     $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2297                     $qw_clname = $dbh->quote_identifier("_" . $clname);
2298
2299                     $query = "SELECT a.st_origin, a.st_received, extract(epoch from a.st_lag_time)::integer
2300                             FROM _test_replication.sl_status a
2301                             INNER JOIN _test_replication.sl_node b on a.st_origin = b.no_id
2302                             INNER JOIN _test_replication.sl_node c on a.st_received = c.no_id
2303                             WHERE a.st_received IN (" . substr('?, ' x scalar(@unresponsive_ids), 0, -2) . ") ORDER BY a.st_origin, a.st_received;";
2304
2305                     $sth = $dbh->prepare($query);
2306
2307                     $param_on = 1;
2308                     foreach (@unresponsive_ids) {
2309                         $sth->bind_param($param_on, $_);
2310                         $param_on++;
2311                     }
2312                     $sth->execute();
2313
2314                     while (my @node_lag = $sth->fetchrow) {
2315                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_data', 'Check2', $_->[0], $node_lag[0], $node_lag[1], $node_lag[2]));
2316                         push(@lag_info2, \@node_lag);
2317                     }
2318
2319                     $sth->finish;
2320                     $dbh->disconnect();
2321                 };
2322                 if ($@) {
2323                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_fail', $_->[0], $@));
2324                     $bad++;
2325                 }
2326             }
2327         }
2328
2329         $lag_idx = 0;
2330         $lag_confirmed = 0;
2331         foreach (@lag_info1) {
2332             if ($g_debug) {
2333                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', ("Node $_->[0] lag between checks on node $_->[1] is " . ($lag_info2[$lag_idx]->[2]-$_->[2]) . " seconds")));
2334             }
2335
2336             if ((($lag_info2[$lag_idx]->[2]-$_->[2])*1000) >= $g_autofailover_perspective_sleep) {
2337                 $lag_confirmed++;
2338             }
2339             $lag_idx++;
2340         }  
2341     }
2342
2343     if ($bad > 0) {
2344         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_unknown'));
2345     }   
2346     elsif ($lag_idx == $lag_confirmed) {
2347         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_true'));
2348         $agreed = true;
2349     } 
2350     else {
2351         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_false'));
2352     }
2353
2354     return $agreed;
2355 }
2356
2357 # Check if any nodes have failed by connecting and probing the Slony schema
2358 sub checkFailed {
2359     my $clname = shift;
2360     my $dbuser = shift;
2361     my $dbpass = shift;
2362     my $prefix = shift;
2363     my $logfile = shift;
2364     my $log_prefix = shift;
2365
2366     my $dsn;
2367     my $dbh;
2368     my $sth;
2369     my $query;
2370     my $result_count = 0;
2371     my $prov_failed = 0;
2372     my $subonly_failed = 0;
2373
2374     undef @g_unresponsive;
2375
2376     foreach (@g_cluster) {
2377         if ($_->[6] eq "ACTIVE") {
2378             if ($g_debug) {
2379                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_check',$_->[0], ($_->[4] // "unnamed"),(defined($_->[9]) ? "provider of sets $_->[9]" : "sole subscriber"),$_->[2]));
2380             }
2381
2382             if ($g_debug) {
2383                 if ((defined($_->[3])) || ($g_autofailover_provs && defined($_->[9]))) {
2384                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_active_check', 'provider', $_->[0]));
2385                 }
2386                 else {
2387                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_active_check', 'subscriber only', $_->[0]));
2388                 }
2389             }
2390
2391             $dsn = "DBI:Pg:$_->[2];";
2392             eval {
2393                 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2394                 $query = "SELECT count(*) FROM pg_namespace WHERE nspname = ?";
2395                 $sth = $dbh->prepare($query);
2396                 $sth->bind_param(1, "_" . $clname);
2397                 $sth->execute();
2398
2399                 $result_count = $result_count+$sth->rows;
2400     
2401                 $sth->finish;
2402                 $dbh->disconnect();
2403
2404                 if (exists($g_unresponsive_subonly{$_->[0]})) {
2405                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_recovery_subonly', $_->[0]));
2406                     delete $g_unresponsive_subonly{$_->[0]};
2407                 } 
2408             };
2409             if ($@) {
2410                 if ($g_debug) {
2411                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2412                 }
2413                 push(@g_unresponsive, \@$_); 
2414                 if ((defined($_->[3])) || ($g_autofailover_provs && defined($_->[9]))) {
2415                     if (defined($_->[3])) {
2416                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_unresponsive', $_->[0]));
2417                     }
2418                     else {
2419                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_unresponsive_prov', $_->[0]));
2420                     }
2421                     unless ($g_failover_method ne 'new' && !defined($_->[3])) {
2422                         $prov_failed++;
2423                     }
2424                 }
2425                 else {
2426                     if (!exists($g_unresponsive_subonly{$_->[0]})) {
2427                         printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_unresponsive_subonly', $_->[0]));
2428                         $g_unresponsive_subonly{$_->[0]} = true;
2429                     } 
2430                     if ($g_fail_subonly) {
2431                         $subonly_failed++;
2432                     }
2433                 }
2434             }
2435         }
2436         else {
2437             if ($g_debug) {
2438                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_check',$_->[0], ($_->[4] // "unnamed"), lc($_->[6] // "unknown") .  ' node', $_->[2]));
2439             }
2440         }
2441     }
2442     if ($prov_failed > 0) {
2443         return ($prov_failed+$subonly_failed);
2444     }
2445     else {
2446         return $prov_failed;
2447     }
2448 }
2449
2450 # Attempt to try and find the most suitable backup node for a failed node
2451 sub findBackup {
2452     my $clname = shift;
2453     my $dbuser = shift;
2454     my $dbpass = shift;
2455     my $prefix = shift;
2456     my $logfile = shift;
2457     my $log_prefix = shift;
2458
2459     my $dsn;
2460     my $dbh;
2461     my $sth;
2462     my $query;
2463     my $qw_clname;
2464     my $result_count = 0;
2465     my $lowest_lag_time;
2466     my $latest_last_event;
2467     my $best_node_id;    
2468     my $best_node_is_direct;    
2469     my $best_node_can_forward;    
2470     my @sets_from;
2471     my @sets_to;
2472     my @sets_to_prov;
2473     my %backup_for_set_chosen;
2474
2475     undef %g_backups;
2476     undef @g_failed;
2477
2478     foreach (@g_unresponsive) {
2479         if ($g_fail_subonly || (defined($_->[3])) || ($g_autofailover_provs && defined($_->[9]))) {
2480             printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_find', ($_->[9] // "none"), $_->[0]));
2481
2482             undef $best_node_id;
2483             $lowest_lag_time = (1<<$Config{ivsize}*8-1)-1;
2484             $latest_last_event = 0;
2485             $best_node_is_direct = false;    
2486             $best_node_can_forward = false;    
2487
2488             if (defined($_->[9]) && (exists $backup_for_set_chosen{$_->[9]})) {
2489                 $best_node_id = $backup_for_set_chosen{$_->[9]};
2490                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_found', $_->[9], $_->[0]));
2491             }
2492             else {
2493                 foreach my $subscriber (@g_cluster) {
2494                     if ($subscriber->[0] != $_->[0]) {
2495                         if ($g_debug) {
2496                             printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_check_sub',$subscriber->[0]));
2497                         }
2498    
2499                         # Here the strings containing the sets are converted to arrays
2500                         # Origin / Forwarded sets
2501                         undef @sets_to_prov; 
2502                         if (defined($subscriber->[10])) {
2503                             @sets_to_prov = split(',',$subscriber->[10]);
2504                         }
2505                         if (defined($subscriber->[3])) {
2506                             if (@sets_to_prov) {
2507                                 @sets_to_prov = (@sets_to_prov, split(',',$subscriber->[3]));
2508                             }
2509                             else {
2510                                 @sets_to_prov = split(',',$subscriber->[3]);
2511                             }
2512                         }
2513                         if (!defined($subscriber->[10]) && !defined($subscriber->[3])) {
2514                             @sets_to_prov = (0);
2515                         }
2516
2517                         # Origin / Subscribed sets.
2518                         undef @sets_to;
2519                         if (defined($subscriber->[7])) {
2520                             @sets_to = split(',',$subscriber->[7]);
2521                         }
2522                         if (defined($subscriber->[3])) {
2523                             if (@sets_to) {
2524                                 @sets_to = (@sets_to, split(',',$subscriber->[3]));
2525                             }
2526                             else {
2527                                @sets_to = split(',',$subscriber->[3]);
2528                             }
2529                         }
2530                         if (!defined($subscriber->[7]) && !defined($subscriber->[3])) {
2531                             @sets_to = (0);
2532                         }
2533
2534                         # Sets provided by the failed node.
2535                         undef @sets_from;
2536                         if (defined($_->[9])) {
2537                             @sets_from = split(',',$_->[9]);
2538                         }
2539                         else {
2540                             @sets_from = (0);
2541                             @sets_to = (0);
2542                         }
2543
2544                         $dsn = "DBI:Pg:$subscriber->[2]";
2545         
2546                         eval {
2547                             $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2548                             $qw_clname = $dbh->quote_identifier("_" . $clname);
2549
2550                             #print "\tNODE " . $subscriber->[0] . ") SETS TO = " . join(',', @sets_to) . " SETS FROM =  " . join(',', @sets_from) . " SETS TO PROV = " . join(',', @sets_to_prov) . "\n";
2551
2552                             if (defined($subscriber->[3]) && checkProvidesAllSets(\@sets_from, \@sets_to)) {
2553                                 $query = "SELECT 0, ev_seqno, (ev_origin = ?)
2554                                     FROM $qw_clname.sl_event
2555                                     WHERE ev_origin = $qw_clname.getlocalnodeid(?)
2556                                     ORDER BY ev_seqno DESC LIMIT 1";
2557                             }
2558                             else {
2559                                 $query = "SELECT extract(epoch from (current_timestamp-a.con_timestamp)), a.con_seqno, (a.con_origin = ?) AS direct
2560                                     FROM $qw_clname.sl_confirm a
2561                                     INNER JOIN $qw_clname.sl_event b on b.ev_seqno = a.con_seqno AND a.con_origin = b.ev_origin
2562                                     INNER JOIN $qw_clname.sl_subscribe c ON c.sub_provider = a.con_origin AND c.sub_receiver = a.con_received
2563                                     WHERE c.sub_active AND a.con_received = $qw_clname.getlocalnodeid(?)
2564                                     ORDER BY a.con_seqno DESC LIMIT 1;";
2565                             }
2566
2567                             $sth = $dbh->prepare($query);
2568                             $sth->bind_param(1, $_->[0]);
2569                             $sth->bind_param(2, "_" . $clname);
2570                             $sth->execute();
2571
2572                             while (my @subinfo = $sth->fetchrow) {
2573                                 # If the failed provider node isn't an origin for any sets, we classify any direct subscribers to it as indeirect
2574                                 # because they are indirect to the origin.
2575                                 if ($subinfo[2] && defined($_->[9]) && !defined($_->[3])) {
2576                                     $subinfo[2] = false;
2577                                 }
2578
2579                                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_node_detail', 
2580                                                                                     $subscriber->[0], 
2581                                                                                     ($subinfo[2]?"directly":"indirectly"), 
2582                                                                                     (defined($_->[3])?"origin":(defined($_->[9])?"provider":"subscriber only")), 
2583                                                                                     $_->[0],
2584                                                                                     (defined($subscriber->[10])?$subscriber->[10]:(defined($subscriber->[3])?$subscriber->[3]:"<NONE>")),
2585                                                                                     $subinfo[0], $subinfo[1]));
2586
2587                                 # If select this node as the backup node if:
2588                                 #   1) The node is a subscriber to all sets on the failed node
2589                                 #   2) In order of preference:
2590                                 #      The node is one of the direct subscribers to the failed node on the most recent event and is a forwarding provider
2591                                 #      OR 
2592                                 #      The node is one of the direct subscribers to the failed node on the most recent event and is not a forwarding provider
2593                                 #      OR
2594                                 #      The node is an indirect subscriber to the failed node with the lowest lag time
2595                                 if (!checkProvidesAllSets(\@sets_from, \@sets_to)) {
2596                                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_unsuitable', $subscriber->[0]));
2597                                 }
2598                                 elsif (($subinfo[2] && (!$best_node_is_direct || $subinfo[1] > $latest_last_event || (!$best_node_can_forward && checkProvidesAllSets(\@sets_from, \@sets_to_prov) && $subinfo[1] == $latest_last_event))) 
2599                                     || (!$best_node_is_direct && !$subinfo[2] && $subinfo[0] < $lowest_lag_time)) {
2600                                     printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_best', $subscriber->[0], $subinfo[0], $subinfo[1]));
2601                                     $best_node_id = $subscriber->[0];
2602                                     $lowest_lag_time = $subinfo[0];
2603                                     $latest_last_event = $subinfo[1];
2604                                     $best_node_is_direct = $subinfo[2];
2605                                     $best_node_can_forward = checkProvidesAllSets(\@sets_from, \@sets_to_prov);    
2606                                 }
2607
2608                             }
2609                         };
2610                         if ($@) {
2611                             printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_check_sub_fail', $subscriber->[0]));
2612                             if ($g_debug) {
2613                                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2614                             }
2615                         }
2616                     }
2617                 }
2618             }
2619             if (defined($best_node_id)) { 
2620                 push(@g_failed, \@$_);
2621                 $g_backups{$_->[0]} = $best_node_id;
2622                 if (defined($_->[9]) && !(exists $g_backups{$_->[9]})) {
2623                     $backup_for_set_chosen{$_->[9]} = $best_node_id;
2624                 }
2625             }
2626             else {
2627                 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_fail')); 
2628             }
2629         }
2630         else {
2631             printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_skip', $_->[0]));
2632         }
2633     }
2634     return keys(%g_backups);
2635 }