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+
8 # This script is a command-line utility to manage switchover and failover
9 # of replication sets in Slony-I clusters.
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.
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.
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/>.
27 use Getopt::Long qw/GetOptions/;
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/;
36 use constant false => 0;
37 use constant true => 1;
39 my $g_script_version = '1.0.3';
41 my $g_pidfile = '/var/run/slony_failover.pid';
42 my $g_pid_written = false;
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;
54 my $g_use_try_blocks = false;
55 my $g_lockset_method = 'multiple';
56 my $g_logfile = 'failover.log';
58 my $g_silence_notice = false;
69 my $g_dbuser = 'slony';
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.
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;
96 my %g_unresponsive_subonly;
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}
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}
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);
334 # Handle command line options
335 Getopt::Long::Configure('no_ignore_case');
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;
340 if (defined($opt{cfgfile})) {
341 unless (getConfig($opt{cfgfile})) {
342 println(lookupMsg('err_no_config'));
347 if (defined($opt{dbname})) {
348 $g_dbname = $opt{dbname};
350 if (defined($opt{clname})) {
351 $g_clname = $opt{clname};
353 if (defined($opt{host})) {
354 $g_dbhost = $opt{host};
356 if (defined($opt{port})) {
357 $g_dbport = $opt{port};
359 if (defined($opt{dbuser})) {
360 $g_dbuser = $opt{dbuser};
362 if (defined($opt{dbpass})) {
363 $g_dbpass = $opt{dbpass};
367 # Fill in any missing values with defaults or display message and die
368 if (!defined($g_dbname)) {
369 println(lookupMsg('err_no_database'));
370 die lookupMsg('usage');
372 if (!defined($g_clname)) {
373 println(lookupMsg('err_no_cluster'));
374 die lookupMsg('usage');
376 if (!defined($g_dbhost)) {
377 println(lookupMsg('err_no_host'));
378 die lookupMsg('usage');
382 # Build conninfo from supplied datbase name/host/port
383 $g_dbconninfo = "dbname=$g_dbname;host=$g_dbhost;port=$g_dbport";
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));
392 if ($g_separate_working) {
393 if ($g_prefix !~ m/\/$/) {
397 # Get a uuid for working directory
398 $g_prefix .= getUUID($g_date);
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));
407 # Set postgres path if provided
408 if (defined($g_slonikpath) && ($g_slonikpath ne "")) {
409 $ENV{PATH} .= ":$g_slonikpath";
412 # Check if autofailover is enabled, if so check configuration and enter autofailover mode
413 if (($g_autofailover) && !defined($opt{infoprint})) {
415 # Write out a PID file
416 if (writePID($g_prefix, $g_logfile, $g_log_prefix, $g_pidfile)) {
417 $g_pid_written = true;
420 cleanExit(1, "system");
423 # Go into endless loop for autofailover
424 autoFailover($g_dbconninfo, $g_clname, $g_dbuser, $g_dbpass, $g_prefix, $g_logfile, $g_log_prefix);
427 # Read slony configuration and output some basic information
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);
434 println(lookupMsg('load_cluster_fail', 'from supplied configuration'));
435 cleanExit(2, "system");
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);
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);
449 if ($g_node_count <= 0) {
450 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_cluster_empty'));
451 cleanExit(3, "system");
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)));
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'));
462 printlogln($g_prefix,$g_logfile,$g_log_prefix,"\t$_");
464 printlog($g_prefix,$g_logfile,$g_log_prefix,"\n");
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");
472 elsif ($g_node_from == -1) {
473 cleanExit(5, "system");
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");
480 elsif ($g_node_to == -1) {
481 cleanExit(7, "system");
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");
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);
492 if ($g_available_node_count <= 0) {
493 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_cluster_offline'));
494 cleanExit(9, "system");
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");
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'));
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'));
510 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('info_req_nodes_available', $g_available_node_count, $g_node_count));
512 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_action', 'MOVE SET'));
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");
521 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_surrender'));
522 cleanExit(12, "system");
526 if ($g_input !~ /^[Y|O]$/i) {
527 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit_noaction'));
528 cleanExit(13, "user");
531 if (!$g_use_comment_aliases) {
532 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_aliases'));
535 if ($g_input =~ /^[Y|O]$/i) {
536 $g_use_comment_aliases = true;
541 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_summary'));
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]));
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'));
552 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_drop_nodes'));
554 if ($g_input ~~ /^[Y|O]$/i) {
555 $g_drop_failed = true;
558 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_reason'));
560 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_continue'));
563 if ($g_input !~ /^[Y|O]$/i) {
564 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit_noaction'));
565 cleanExit(14, "user");
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);
572 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_preserve'));
575 if ($g_input =~ /^[Y|O]$/i) {
576 $g_subs_follow_origin = true;
579 printlog($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('interactive_reason'));
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);
586 # Complete and run script if required
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));
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));
599 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit_noaction'));
603 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('err_read_fail', 'slonik script', $g_script));
604 cleanExit(15, "system");
607 cleanExit(0, "script completion");
609 ###########################################################################################################################################
612 my $exit_code = shift;
615 printlogln($g_prefix,$g_logfile,$g_log_prefix,lookupMsg('exit', $type));
619 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);
623 if ($g_pid_written) {
624 removePID($g_prefix, $g_logfile, $g_log_prefix, $g_pidfile);
631 cleanExit(100,'signal');
642 my $log_prefix = shift;
648 my $result_count = 0;
649 my $critical_count = 0;
655 undef @g_unresponsive;
658 foreach (@g_cluster) {
659 if ($_->[0] == $from) {
660 @origsets = split(',', $_->[3]);
665 foreach (@g_cluster) {
667 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>") . ")"));
670 $dsn = "DBI:Pg:$_->[2];";
672 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
673 $query = "SELECT count(*) FROM pg_namespace WHERE nspname = ?";
674 $sth = $dbh->prepare($query);
675 $sth->bind_param(1, "_" . $clname);
678 $result_count = $result_count+$sth->rows;
685 # 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.
686 printlogln($prefix,$logfile,$log_prefix,lookupMsg('wrn_node_unavailable', $_->[0]));
688 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
690 if ($_->[0] == $to) {
691 $critical_count = -1;
693 elsif ($_->[0] == $from) {
694 $critical_count = -2;
697 foreach my $subprov (split(';', $_->[5])) {
698 my ($node, $setlist) = (split('->', $subprov)) ;
700 $setlist =~ s/(\)|\(|s)//g;
701 @subsets = (split(',', $setlist));
703 if (($critical_count >= 0) && (checkSubscribesAnySets(\@origsets, \@subsets))) {
708 # Only push nodes with active subscribers to sets into failed list unless explicitly told to
709 if (($g_fail_subonly) || (defined($_->[9]))) {
710 push(@g_failed, \@$_);
711 $g_backups{$_->[0]} = $to;
713 push(@g_unresponsive, \@$_);
717 return ($result_count, $critical_count);
721 my $dbconninfo = shift;
727 my $log_prefix = shift;
738 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_cluster_load', $dbconninfo));
741 $dsn = "DBI:Pg:$dbconninfo;";
743 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
744 $qw_clname = $dbh->quote_identifier("_" . $clname);
746 $query = "SELECT $qw_clname.getModuleVersion()";
747 $sth = $dbh->prepare($query);
749 ($version) = $sth->fetchrow;
752 $query = "WITH z AS (
753 SELECT a.no_id, b.sub_provider AS no_prov,
754 COALESCE(c.pa_conninfo,(SELECT pa_conninfo FROM $qw_clname.sl_path WHERE pa_server = $qw_clname.getlocalnodeid(?) LIMIT 1)) AS no_conninfo,
755 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,
756 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 prov_sets,
757 coalesce(trim(regexp_replace(substring(a.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_','g')), 'node' || a.no_id) AS no_name,
758 '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,
759 coalesce(trim(regexp_replace(substring(d.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_','g')), 'node' || b.sub_provider, '')
760 || '->(' || 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,
761 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,
762 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,
763 string_agg(CASE WHEN b.sub_receiver = a.no_id THEN b.sub_set::text END,',' ORDER BY b.sub_set,',') AS sub_sets
764 FROM $qw_clname.sl_node a
765 LEFT OUTER JOIN $qw_clname.sl_subscribe b ON a.no_id = b.sub_receiver
766 LEFT OUTER JOIN $qw_clname.sl_path c ON c.pa_server = a.no_id AND c.pa_client = $qw_clname.getlocalnodeid(?)
767 LEFT OUTER JOIN $qw_clname.sl_node d ON b.sub_provider = d.no_id
768 LEFT OUTER JOIN $qw_clname.sl_set e ON b.sub_set = e.set_id
769 GROUP BY b.sub_provider, a.no_id, a.no_comment, c.pa_conninfo, d.no_comment, a.no_active
773 nullif(string_agg(no_prov::text, ',' ORDER BY no_prov),'') AS no_provs,
775 nullif(string_agg(origin_sets::text, ',' ORDER BY origin_sets),'') AS origin_sets,
777 nullif(string_agg(sub_tree, ';' ORDER BY sub_tree),'') AS no_sub_tree,
779 nullif(string_agg(prov_sets::text, ',' ORDER BY prov_sets),'') AS prov_sets,
780 nullif(string_agg(sub_tree_name, ';' ORDER BY sub_tree_name),'') AS no_sub_tree_name,
781 nullif(string_agg(prov_sets_active::text, ',' ORDER BY prov_sets_active),'') AS prov_sets_active,
782 nullif(string_agg(sub_sets::text, ',' ORDER BY sub_sets),'') AS no_subs
783 FROM z GROUP BY no_id, no_conninfo, no_name, no_status";
784 $sth = $dbh->prepare($query);
786 $sth->bind_param(1, "_" . $clname);
787 $sth->bind_param(2, "_" . $clname);
791 while (my @node = $sth->fetchrow) {
792 #printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', join(' - ', @node)));
793 push(@g_cluster, \@node);
802 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
804 die lookupMsg('err_pgsql_connect');
807 #if (substr($version,0,1) < 2) {
808 # printlogln($prefix,$logfile,$log_prefix,lookupMsg('wrn_not_tested', $version));
810 if (($g_use_try_blocks) && ($g_lockset_method eq 'multiple') && (substr($version,0,3) <= 9.9)) {
811 # 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.
812 printlogln($prefix,$logfile,$log_prefix, lookupMsg('note_multiple_try', $version));
813 $g_lockset_method = 'single';
815 if (substr($version,0,3) >= 2.2) {
816 $g_failover_method = 'new';
817 $g_resubscribe_method = 'resubscribe';
820 unless ($g_silence_notice) {
821 if ((substr($version,0,3) >= 2.0) && (substr($version,0,3) < 2.2)) {
822 printlogln($prefix,$logfile,$log_prefix,lookupMsg('wrn_failover_issues', $version));
824 printlogln($prefix,$logfile,$log_prefix,lookupMsg('note_autofail_fwd_only'));
825 $g_silence_notice = true;
827 if ($g_fail_subonly) {
828 printlogln($prefix,$logfile,$log_prefix,lookupMsg('note_fail_sub_only'));
829 $g_fail_subonly = false;
835 return (scalar(@g_cluster), $version);
839 my $dbconninfo = shift;
841 my $nodenumber = shift;
846 my $log_prefix = shift;
856 $dsn = "DBI:Pg:$dbconninfo;";
858 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
859 $qw_clname = $dbh->quote_identifier("_" . $clname);
860 $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;";
862 $sth = $dbh->prepare($query);
863 $sth->bind_param(1, $nodenumber);
867 while (my @set = $sth->fetchrow) {
868 push(@g_sets, \@set);
876 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
878 die lookupMsg('err_pgsql_connect');
881 return scalar(@g_sets);
885 my $dbconninfo = shift;
891 my $log_prefix = shift;
901 $dsn = "DBI:Pg:$dbconninfo;";
903 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
904 $qw_clname = $dbh->quote_identifier("_" . $clname);
905 $query = "SELECT a.st_origin || ' (' || coalesce(trim(regexp_replace(substring(b.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_', 'g')), 'node' || b.no_id) || ')<->'
906 || a.st_received || ' (' || coalesce(trim(regexp_replace(substring(c.no_comment from E'\\\\((.+)\\\\)'), '[^0-9A-Za-z]','_', 'g')), 'node' || c.no_id) || ') Events: '
907 || a.st_lag_num_events || ' Time: ' || a.st_lag_time
908 FROM $qw_clname.sl_status a
909 INNER JOIN $qw_clname.sl_node b on a.st_origin = b.no_id
910 INNER JOIN $qw_clname.sl_node c on a.st_received = c.no_id";
912 $sth = $dbh->prepare($query);
915 while (my $lag = $sth->fetchrow) {
924 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
926 die lookupMsg('err_pgsql_connect');
929 return scalar(@g_lags);
936 my $log_prefix = shift;
937 my $last_choice = shift;
946 $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');
947 printlog($prefix,$logfile,$log_prefix,"$line");
948 $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')));
949 printlog($prefix,$logfile,$log_prefix,"$line");
951 foreach (@g_cluster) {
952 $line = sprintf "%-4s %-14s %-10s %-24s %-s\n", $_->[0], $_->[4], $_->[6], ($_->[1] // "<NONE>"), (lookupMsg('interactive_detail_1') . ($_->[3] // "<NONE>"));
953 printlog($prefix,$logfile,$log_prefix,"$line");
954 $line = sprintf "%-55s %-s\n", " ", (lookupMsg('interactive_detail_2') . ($_->[7] // "<NONE>"));
955 printlog($prefix,$logfile,$log_prefix,"$line");
956 $line = sprintf "%-55s %-s\n", " ", (lookupMsg('interactive_detail_3') . ($_->[5] // "<NONE>"));
957 printlogln($prefix,$logfile,$log_prefix,"$line");
958 $options{$_->[0]} = {name => $_->[4], sets => ($_->[3] // ""), status => $_->[6], provider => $_->[7]};
960 if ($type !~ m/info/i) {
961 printlog($prefix,$logfile,$log_prefix,lookupMsg('interactive_choose_node', $type));
965 if(exists($options{$choice})) {
966 if ($options{$choice}->{status} ne "ACTIVE") {
967 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_inactive', $choice, lc($options{$choice}->{status})));
970 elsif (($type =~ m/from/i) && (length(trim($options{$choice}->{sets})) <= 0)) {
971 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_origin', $choice));
974 elsif ($type =~ m/to/i) {
975 if (length(trim($options{$choice}->{provider})) <= 0) {
976 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_provider', $choice));
980 foreach my $old_origin (@g_cluster) {
981 if ($old_origin->[0] == $last_choice) {
982 @sets_from = split(',', $old_origin->[3]);
983 @sets_to = split(',', $options{$choice}->{provider});
984 if (checkProvidesAllSets(\@sets_from, \@sets_to)) {
988 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_provider_sets',$choice,$old_origin->[3],$options{$choice}->{providers}));
995 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_no_configuration', $last_choice));
1001 printlog($prefix,$logfile,$log_prefix,lookupMsg('interactive_confirm',$type,$choice,$options{$choice}->{name}));
1004 if ($ok !~ /^[Y|O]$/i) {
1005 printlogln($prefix,$logfile,$log_prefix,lookupMsg('exit_noaction'));
1010 elsif (!length($choice)) {
1011 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_must_enter_node_id'));
1015 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_not_a_node_id', $choice));
1024 my $filename = shift;
1025 my $dbconninfo = shift;
1030 my $aliases = shift;
1032 my $logfile = shift;
1033 my $log_prefix = shift;
1034 my $comment_all_failed = shift;
1037 my $success = false;
1039 my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1040 my $date = sprintf ("%02d:%02d:%02d on %02d/%02d/%04d", $hour, $min, $sec, $day, $month+1, $year+1900);
1042 if (open(SLONFILE, ">", $filename)) {
1043 print SLONFILE ("# Script autogenerated on $date\n\n");
1044 print SLONFILE ("######\n# Preamble (cluster structure)\n######\n\n# Cluster name\n");
1046 print SLONFILE ("DEFINE slony_cluster_name $clname;\n");
1047 print SLONFILE ("CLUSTER NAME = \@slony_cluster_name;\n\n");
1050 print SLONFILE ("CLUSTER NAME = $clname;\n\n");
1052 foreach (@g_cluster) {
1054 if (($comment_all_failed) && (exists $g_backups{$_->[0]})) {
1055 $line_prefix = "# (Node $_->[0] unavailable) ";
1057 elsif (!$g_fail_subonly) {
1058 foreach my $unresponsive (@g_unresponsive) {
1059 if (($_->[0] == $unresponsive->[0]) && !defined($_->[9]) && ($g_failover_method eq 'new')) {
1060 $line_prefix = "# (Node $_->[0] unavailable subscriber only) ";
1064 print SLONFILE ("# Preamble for node $_->[0] named $_->[4]\n");
1066 print SLONFILE ($line_prefix . "DEFINE $_->[4] $_->[0];\n");
1067 print SLONFILE ($line_prefix . "DEFINE $_->[4]_conninfo '$_->[2]';\n");
1068 print SLONFILE ($line_prefix . "NODE \@$_->[4] ADMIN CONNINFO = \@$_->[4]_conninfo;\n\n");
1071 print SLONFILE ($line_prefix . "NODE $_->[0] ADMIN CONNINFO = '$_->[2]';\n\n");
1073 if (($aliases) && ($sets)) {
1074 $set_count = loadSets($dbconninfo, $clname, $_->[0], $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
1075 if ($set_count > 0) {
1076 print SLONFILE ("# Sets provided (currently) by node $_->[0]\n");
1077 foreach my $set (@g_sets) {
1078 print SLONFILE ($line_prefix . "DEFINE $set->[1] $set->[0];\n");
1080 print SLONFILE ("\n");
1087 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_write_fail', "script", $filename));
1095 my $dbconninfo = shift;
1102 my $aliases = shift;
1103 my $logfile = shift;
1104 my $log_prefix = shift;
1109 my $try_prefix = "";
1110 my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1111 my $filetime = sprintf ("%02d_%02d_%04d_%02d:%02d:%02d", $day, $month+1, $year+1900, $hour, $min, $sec);
1112 my $filename = $prefix . "/" . $clname . "-move_sets_from_" . $from . "_to_" . $to . "_on_" . $filetime . ".scr";
1114 if ($g_use_try_blocks) {
1121 my ($node, $setlist);
1122 my ($node_name, $setlist_name);
1125 unless (writePreamble($filename, $dbconninfo, $clname, $dbuser, $dbpass, true, $aliases, $prefix, $logfile, $log_prefix, true)) {
1126 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_incomplete_preamble'));
1129 foreach (@g_cluster) {
1130 if ($_->[0] == $from) {
1131 $from_name = $_->[4];
1133 elsif ($_->[0] == $to) {
1138 if (open(SLONFILE, ">>", $filename)) {
1140 print SLONFILE ("######\n# Actions (changes to cluster structure)\n######\n");
1142 $set_count = loadSets($dbconninfo, $clname, $from, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
1143 if ($set_count > 0) {
1145 if ($g_lockset_method ne "single") {
1146 if ($g_use_try_blocks) {
1147 print SLONFILE ("TRY {\n");
1151 print SLONFILE ($try_prefix . "ECHO 'Locking set $_->[1] ($_->[0])';\n");
1152 print SLONFILE ($try_prefix . "LOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n");
1155 print SLONFILE ($try_prefix . "ECHO 'Locking set $_->[0]';\n");
1156 print SLONFILE ($try_prefix . "LOCK SET ( ID = $_->[0], ORIGIN = $from);\n");
1160 print SLONFILE ("\n");
1163 print SLONFILE ($try_prefix . "ECHO 'Moving set $_->[1] ($_->[0])';\n");
1164 print SLONFILE ($try_prefix . "MOVE SET ( ID = \@$_->[1], OLD ORIGIN = \@$from_name, NEW ORIGIN = \@$to_name);\n");
1167 print SLONFILE ($try_prefix . "ECHO 'Moving set $_->[0]';\n");
1168 print SLONFILE ($try_prefix . "MOVE SET ( ID = $_->[0], OLD ORIGIN = $from, NEW ORIGIN = $to);\n");
1172 if ($g_use_try_blocks) {
1173 print SLONFILE ("}\nON ERROR {\n");
1176 print SLONFILE ($try_prefix . "ECHO 'Unlocking set $_->[1] ($_->[0])';\n");
1177 print SLONFILE ($try_prefix . "UNLOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n");
1180 print SLONFILE ($try_prefix . "ECHO 'Unlocking set $_->[0]';\n");
1181 print SLONFILE ($try_prefix . "UNLOCK SET ( ID = $_->[0], ORIGIN = $from);\n");
1184 print SLONFILE ("\tEXIT 1;\n}\nON SUCCESS {\n");
1187 print SLONFILE ($try_prefix . "WAIT FOR EVENT (ORIGIN = \@$from_name, CONFIRMED = ALL, WAIT ON = \@$from_name, TIMEOUT = 0);\n");
1190 print SLONFILE ($try_prefix . "WAIT FOR EVENT (ORIGIN = $from, CONFIRMED = ALL, WAIT ON = $from, TIMEOUT = 0);\n");
1192 if ($g_use_try_blocks) {
1193 print SLONFILE ("}\n");
1197 if ($g_lockset_method eq "single") {
1199 print SLONFILE ("\nECHO 'Moving set $_->[1] ($_->[0])';\n");
1200 if ($g_use_try_blocks) {
1201 print SLONFILE ("TRY {\n");
1203 print SLONFILE ($try_prefix . "LOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n");
1204 print SLONFILE ($try_prefix . "MOVE SET ( ID = \@$_->[1], OLD ORIGIN = \@$from_name, NEW ORIGIN = \@$to_name);\n");
1205 if ($g_use_try_blocks) {
1206 print SLONFILE ("}\nON ERROR {\n" . $try_prefix . "UNLOCK SET ( ID = \@$_->[1], ORIGIN = \@$from_name);\n" . $try_prefix . "EXIT 1;\n}\n");
1208 print SLONFILE ("WAIT FOR EVENT (ORIGIN = \@$from_name, CONFIRMED = ALL, WAIT ON = \@$from_name, TIMEOUT = 0);\n");
1211 print SLONFILE ("\nECHO 'Moving set $_->[0]';\n");
1212 if ($g_use_try_blocks) {
1213 print SLONFILE ("TRY {\n");
1215 print SLONFILE ($try_prefix . "LOCK SET ( ID = $_->[0], ORIGIN = $from);\n");
1216 print SLONFILE ($try_prefix . "MOVE SET ( ID = $_->[0], OLD ORIGIN = $from, NEW ORIGIN = $to);\n");
1217 if ($g_use_try_blocks) {
1218 print SLONFILE ("}\nON ERROR {\n" . $try_prefix . "UNLOCK SET ( ID = $_->[0], ORIGIN = $from);\n" . $try_prefix . "EXIT 1;\n}\n");
1220 print SLONFILE ("WAIT FOR EVENT (ORIGIN = $from, CONFIRMED = ALL, WAIT ON = $from, TIMEOUT = 0);\n");
1223 if (($subs) && ($g_resubscribe_method eq 'subscribe')) {
1225 foreach my $other_subs (@g_cluster) {
1226 if (($other_subs->[6] eq "ACTIVE") && ($other_subs->[0] != $from) && ($other_subs->[0] != $to)) {
1228 if (exists $g_backups{$other_subs->[0]}) {
1229 $line_prefix = "# (Node $other_subs->[0] unavailable) ";
1235 # mess here needs cleaning up
1236 @subprov_name = (split(';', $other_subs->[8]));
1238 foreach $subprov (split(';', $other_subs->[5])) {
1239 ($node, $setlist) = (split('->', $subprov)) ;
1240 ($node_name, $setlist_name) = (split('->', $subprov_name[$subprov_idx])) ;
1243 $setlist =~ s/(\)|\(|s)//g;
1244 @subsets = (split(',', $setlist)) ;
1247 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_resubscribe', $_->[1], $_->[0], $other_subs->[0], $other_subs->[4], $setlist, $setlist_name, $node, $node_name));
1250 if ($_->[0] ~~ @subsets) {
1251 if ($node == $from) {
1253 print SLONFILE ($line_prefix .
1254 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $to_name ($to) -> " .
1255 "receiver $other_subs->[4] ($other_subs->[0])';\n");
1256 print SLONFILE ($line_prefix .
1257 "SUBSCRIBE SET ( ID = \@$_->[1], PROVIDER = \@$to_name, " .
1258 "RECEIVER = \@$other_subs->[4], FORWARD = YES);\n");
1261 print SLONFILE ($line_prefix .
1262 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $to -> " .
1263 "receiver $other_subs->[0]';\n");
1264 print SLONFILE ($line_prefix . "SUBSCRIBE SET ( ID = $_->[0], PROVIDER = $to, " .
1265 "RECEIVER = $other_subs->[0], FORWARD = YES);\n");
1270 print SLONFILE ($line_prefix .
1271 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $node_name ($node) -> " .
1272 "receiver $other_subs->[4] ($other_subs->[0])';\n");
1273 print SLONFILE ($line_prefix . "SUBSCRIBE SET ( ID = \@$_->[1], PROVIDER = \@$node_name, " .
1274 "RECEIVER = \@$other_subs->[4], FORWARD = YES);\n");
1277 print SLONFILE ($line_prefix .
1278 "ECHO 'Issuing subscribe for set $_->[1] ($_->[0]) provider $node -> " .
1279 "receiver $other_subs->[0]';\n");
1280 print SLONFILE ($line_prefix . "SUBSCRIBE SET ( ID = $_->[0], PROVIDER = $node, " .
1281 "RECEIVER = $other_subs->[0], FORWARD = YES);\n");
1291 if (($subs) && ($g_resubscribe_method eq 'resubscribe')) {
1293 foreach my $other_subs (@g_cluster) {
1294 if (($other_subs->[6] eq "ACTIVE") && ($other_subs->[0] != $from) && ($other_subs->[0] != $to)) {
1295 if (exists $g_backups{$other_subs->[0]}) {
1296 $line_prefix = "# (Node $other_subs->[0] unavailable) ";
1302 @subprov_name = (split(';', $other_subs->[8]));
1304 foreach $subprov (split(';', $other_subs->[5])) {
1305 ($node, $setlist) = (split('->', $subprov)) ;
1306 ($node_name, $setlist_name) = (split('->', $subprov_name[$subprov_idx])) ;
1310 print SLONFILE ("\n");
1311 if ($node == $from) {
1313 print SLONFILE ($line_prefix .
1314 "ECHO 'Issuing resubscribe for provider $to_name ($to) -> receiver $other_subs->[4] ($other_subs->[0])';\n");
1315 print SLONFILE ($line_prefix .
1316 "RESUBSCRIBE NODE ( ORIGIN = \@$to_name, PROVIDER = \@$to_name, RECEIVER = \@$other_subs->[4]);\n");
1319 print SLONFILE ($line_prefix .
1320 "ECHO 'Issuing resubscribe for provider $to -> receiver $other_subs->[0]';\n");
1321 print SLONFILE ($line_prefix .
1322 "RESUBSCRIBE NODE ( ORIGIN = $to, PROVIDER = $to, RECEIVER = $other_subs->[0] );\n");
1327 print SLONFILE ($line_prefix .
1328 "ECHO 'Issuing resubscribe for provider $node_name ($node) -> receiver $other_subs->[4] ($other_subs->[0])';\n");
1329 print SLONFILE ($line_prefix .
1330 "RESUBSCRIBE NODE ( ORIGIN = \@$to_name, PROVIDER = \@$node_name, RECEIVER = \@$other_subs->[4]);\n");
1333 print SLONFILE ($line_prefix .
1334 "ECHO 'Issuing resubscribe for provider $node -> receiver $other_subs->[0]';\n");
1335 print SLONFILE ($line_prefix .
1336 "RESUBSCRIBE NODE ( ORIGIN = $to, PROVIDER = $node, RECEIVER = $other_subs->[0]);\n");
1347 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");
1350 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");
1355 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_write_fail', "script", $filename));
1362 my $dbconninfo = shift;
1369 my $aliases = shift;
1370 my $logfile = shift;
1371 my $log_prefix = shift;
1375 my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1376 my $filetime = sprintf ("%02d_%02d_%04d_%02d:%02d:%02d", $day, $month+1, $year+1900, $hour, $min, $sec);
1381 my ($node, $setlist);
1382 my ($node_name, $setlist_name);
1388 if (defined($from) && defined($to)) {
1389 $filename = $prefix . "/" . $clname . "-failover_from_" . $from . "_to_" . $to . "_on_" . $filetime . ".scr";
1392 $filename = $prefix . "/" . $clname . "-autofailover_on_" . $filetime . ".scr";
1395 if ($g_failover_method ne 'new') {
1396 # For pre 2.2 failover with multiple nodes, we attempt to resubscribe sets and drop other failed providers;
1397 # 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)
1398 # We also need to define the sets in the preamble for this.
1402 unless (writePreamble($filename, $dbconninfo, $clname, $dbuser, $dbpass, $sets, $aliases, $prefix, $logfile, $log_prefix, false)) {
1403 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_incomplete_preamble'));
1406 if (open(SLONFILE, ">>", $filename)) {
1408 print SLONFILE ("######\n# Actions (changes to cluster structure)\n######\n\n");
1410 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_failover_method',$g_failover_method));
1413 # If we are on pre 2.2 we need to drop failed subscriber nodes first regardless
1414 if ($g_failover_method ne 'new') {
1415 foreach (@g_failed) {
1416 if (!defined($_->[3])) {
1417 foreach my $backup (@g_cluster) {
1418 if ($backup->[0] == $g_backups{$_->[0]}) { # this backup node candidate is in the list of suitable nodes for {failed node}
1419 foreach my $subscriber (@g_cluster) {
1420 if (defined($subscriber->[1]) && $subscriber->[1] == $_->[0] && $subscriber->[0] != $backup->[0]) {
1421 # mess here needs cleaning up
1422 @subprov_name = (split(';', $subscriber->[8]));
1424 foreach my $subprov (split(';', $subscriber->[5])) {
1425 ($node, $setlist) = (split('->', $subprov)) ;
1426 ($node_name, $setlist_name) = (split('->', $subprov_name[$subprov_idx])) ;
1430 if ($node == $_->[0]) {
1432 print SLONFILE ("ECHO 'Resubscribing all sets on receiver $subscriber->[4] provided by other failed node $_->[4] to backup node $backup->[4]';\n");
1435 print SLONFILE ("ECHO 'Resubscribing all sets on receiver $subscriber->[0] provided by other failed node $_->[0] to backup node $backup->[0]';\n");
1437 $setlist =~ s/(\)|\(|s)//g;
1438 @subsets = (split(',', $setlist));
1439 $setlist_name =~ s/(\)|\()//g;
1440 @subsets_name = (split(',', $setlist_name));
1443 foreach my $subset (@subsets) {
1445 print SLONFILE ("SUBSCRIBE SET (ID = \@$subsets_name[$set_idx], PROVIDER = \@$backup->[4], RECEIVER = \@$subscriber->[4], FORWARD = YES);\n");
1446 print SLONFILE ("WAIT FOR EVENT (ORIGIN = \@$backup->[4], CONFIRMED = \@$subscriber->[4], WAIT ON = \@$backup->[4]);\n");
1449 print SLONFILE ("SUBSCRIBE SET (ID = $subset, PROVIDER = $backup->[0], RECEIVER = $subscriber->[0], FORWARD = YES);\n");
1450 print SLONFILE ("WAIT FOR EVENT (ORIGIN = $backup->[0], CONFIRMED = $subscriber->[0], WAIT ON = $backup->[0]);\n");
1454 print SLONFILE ("\n");
1459 print SLONFILE ("ECHO 'Dropping other failed node $_->[4] ($_->[0])';\n");
1460 print SLONFILE ("DROP NODE (ID = \@$_->[4], EVENT NODE = \@$backup->[4]);\n\n");
1463 print SLONFILE ("ECHO 'Dropping other failed node $_->[0]';\n");
1464 print SLONFILE ("DROP NODE (ID = $_->[0], EVENT NODE = $backup->[0]);\n\n");
1466 push(@dropped, $_->[0]);
1469 # The node is failed, but there are no downstream subscribers
1479 foreach (@g_failed) {
1480 if (($g_failover_method eq 'new') || defined($_->[3])) {
1481 foreach my $backup (@g_cluster) {
1482 if ($backup->[0] == $g_backups{$_->[0]}) {
1483 ## Here we have both details of the backup node and the failed node
1485 print SLONFILE ("ECHO 'Failing over slony cluster from $_->[4] (id $_->[0]) to $backup->[4] (id $backup->[0])';\n");
1488 print SLONFILE ("ECHO 'Failing over slony cluster from node $_->[0] to node $backup->[0]';\n");
1496 print SLONFILE ("FAILOVER (\n\t");
1498 foreach (@g_failed) {
1499 if (($g_failover_method eq 'new') || defined($_->[3])) {
1500 foreach my $backup (@g_cluster) {
1501 if ($backup->[0] == $g_backups{$_->[0]}) {
1502 ## Here we have both details of the backup node and the failed node
1503 if ($g_failover_method eq 'new') {
1504 if( $written != 0 ) {
1505 print SLONFILE (",\n\t");
1507 print SLONFILE ("NODE = (");
1510 if( $written != 0 ) {
1511 print SLONFILE ("\n);\nFAILOVER (\n\t");
1515 print SLONFILE ("ID = \@$_->[4], BACKUP NODE = \@$backup->[4]");
1518 print SLONFILE ("ID = $_->[0], BACKUP NODE = $backup->[0]");
1520 if ($g_failover_method eq 'new') {
1521 print SLONFILE (")");
1529 print SLONFILE ("\n);\n\n");
1531 if ($g_drop_failed) {
1532 if (($g_failover_method eq 'new') && (scalar(@g_failed) > 1)) {
1533 foreach (@g_failed) {
1535 print SLONFILE ("ECHO 'Dropping failed node $_->[4] ($_->[0])';\n");
1538 print SLONFILE ("ECHO 'Dropping failed node $_->[0]';\n");
1542 print SLONFILE ("DROP NODE (ID = '");
1546 foreach (@g_failed) {
1547 foreach my $backup (@g_cluster) {
1548 if ($backup->[0] == $g_backups{$_->[0]}) {
1549 if (!defined($event_node)) {
1551 $event_node = $backup->[4];
1554 $event_node = $backup->[0];
1557 if (($g_failover_method eq 'new') && (scalar(@g_failed) > 1)) {
1558 if( $written != 0 ) {
1559 print SLONFILE (",");
1561 ## Don't bother trying to define array values
1563 # print SLONFILE "\@$_->[4]";
1566 print SLONFILE $_->[0];
1570 elsif (($g_failover_method eq 'new') || defined($_->[3]) || !($_->[0] ~~ @dropped)) {
1572 print SLONFILE ("ECHO 'Dropping failed node $_->[4] ($_->[0])';\n");
1573 print SLONFILE ("DROP NODE (ID = \@$_->[4], EVENT NODE = \@$backup->[4]);\n\n");
1576 print SLONFILE ("ECHO 'Dropping failed node $_->[0]';\n");
1577 print SLONFILE ("DROP NODE (ID = $_->[0], EVENT NODE = $backup->[0]);\n\n");
1584 if (($g_failover_method eq 'new') && (scalar(@g_failed) > 1)) {
1586 print SLONFILE ("', EVENT NODE = \@$event_node);\n");
1589 print SLONFILE ("', EVENT NODE = $event_node);\n");
1596 printlog($prefix,$logfile,$log_prefix,lookupMsg('err_write_fail', "script", $filename));
1603 my $name = shift || '?';
1607 if (exists $message{$g_lang}{$name}) {
1608 $text = $message{$g_lang}{$name};
1610 elsif (exists $message{'en'}{$name}) {
1611 $text = $message{'en'}{$name};
1614 $line_call = (caller)[2];
1615 $text = qq{Failed to lookup text "$name" at line $line_call};
1621 $val = '?' if ! defined $val;
1622 last unless $text =~ s/\$$x/$val/g;
1631 $string =~ s/^('|")+//;
1632 $string =~ s/('|")+$//;
1638 $string =~ s/^\s+//;
1639 $string =~ s/\s+$//;
1644 print ((@_ ? join($/, @_) : $_), $/);
1649 my $logfile_name = shift;
1650 my $log_prefix = shift;
1651 my $message = shift;
1657 if (defined($logfile_name)) {
1659 # Do we have to do this all the time? Perhaps could check parameters first
1660 if ($logfile_name =~ /^\//i) {
1661 $logfile = strftime($logfile_name, localtime);
1664 $logfile = "$prefix/" . strftime($logfile_name, localtime);
1667 if ($log_prefix =~ m/(\%[mt])/) {
1668 my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
1669 my ($h_sec, $h_msec) = gettimeofday;
1670 $date = sprintf ("%02d-%02d-%04d %02d:%02d:%02d.%03d", $day, $month+1, $year+1900, $hour, $min, $sec, $h_msec/1000);
1671 $log_prefix =~ s/\%m/$date/g;
1673 $date = sprintf ("%02d-%02d-%04d %02d:%02d:%02d", $day, $month+1, $year+1900, $hour, $min, $sec);
1674 $log_prefix =~ s/\%t/$date/g;
1676 if ($log_prefix =~ m/(\%p)/) {
1677 $log_prefix =~ s/\%p/$g_pid/g;
1680 if (open(LOGFILE, ">>", $logfile)) {
1681 print LOGFILE $log_prefix . " " . $message;
1685 println(lookupMsg('err_write_fail', "logfile", $logfile));
1691 printlog ($_[0], $_[1], $_[2], $_[3] . $/);
1695 my $dbconninfo = shift;
1698 my $exit_code = shift;
1701 my $logfile = shift;
1702 my $log_prefix = shift;
1714 unless($results = (read_file($logfile))) {
1715 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_read_fail', "logfile", $logfile));
1718 if (defined($script) && (-e $script)) {
1719 unless ($script_data = (read_file($script))) {
1720 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_read_fail', "script file", $script));
1724 $script_data = "No script data was generated.";
1725 $script = "No script generated.";
1728 $dsn = "DBI:Pg:$dbconninfo;";
1730 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
1731 $query = "INSERT INTO public.failovers (reason, exit_code, results, script, cluster_name)
1732 VALUES (?, ?, ?, ?, ?)";
1734 $sth = $dbh->prepare($query);
1736 $sth->bind_param(1, $reason);
1737 $sth->bind_param(2, $exit_code);
1738 $sth->bind_param(3, $results);
1739 $sth->bind_param(4, $script . ":\n" . $script_data);
1740 $sth->bind_param(5, $clname);
1749 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
1751 die lookupMsg('err_pgsql_connect');
1758 my $date_string = shift;
1759 my $g_ug = new Data::UUID;
1760 my $g_uuid = $g_ug->create_from_name("failover_script", $date_string);
1761 my $g_uuid_str = $g_ug->to_string($g_uuid);
1767 my $logfile = shift;
1768 my $log_prefix = shift;
1769 my $pidfile_name = shift;
1773 if ($pidfile_name =~ /^\//i) {
1774 $pidfile = $pidfile_name;
1777 $pidfile = "$prefix/" . $pidfile_name;
1780 open (PIDFILE, ">", $pidfile);
1786 printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_generic', $!));
1788 printlogln($prefix,$logfile,$log_prefix, lookupMsg('err_write_fail', "pid file", $pidfile));
1796 my $logfile = shift;
1797 my $log_prefix = shift;
1798 my $pidfile_name = shift;
1802 if ($pidfile_name =~ /^\//i) {
1803 $pidfile = $pidfile_name;
1806 $pidfile = "$prefix/" . $pidfile_name;
1813 printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_generic', 'PID file never existed to be removed'));
1818 printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_generic', $!));
1820 printlogln($prefix,$logfile,$log_prefix, lookupMsg('err_unlink_fail', "pid file", $pidfile));
1826 sub checkProvidesAllSets {
1827 my ($originSets, $providerSets) = @_;
1830 undef @test_hash{@$originSets}; # add a hash key for each element of @$originSets
1831 delete @test_hash{@$providerSets}; # remove all keys for elements of @$providerSets
1833 return !%test_hash; # return false if any keys are left in the hash
1836 sub checkSubscribesAnySets {
1837 my ($originSets, $subscriberSets) = @_;
1842 undef @test_hash{@$originSets}; # add a hash key for each element of @$originSets
1843 $before = scalar(keys %test_hash);
1844 delete @test_hash{@$subscriberSets}; # remove all keys for elements of @$subscriberSets
1845 $after = scalar(keys %test_hash);
1846 return ($before != $after); # return false if no keys were removed from the hash
1850 my $cfgfile = shift;
1852 my $success = false;
1855 if (open(CFGFILE, "<", $cfgfile)) {
1856 foreach (<CFGFILE>) {
1861 s/#(?=(?:(?:[^']|[^"]*+'){2})*+[^']|[^"]*+\z).*//;
1863 if (length(trim($_))) {
1864 @fields = split('=', $_, 2);
1865 given(lc($fields[0])) {
1866 $value = qtrim(trim($fields[1]));
1870 when(/\bslony_database_host\b/i) {
1873 when(/\bslony_database_port\b/i) {
1874 $g_dbport = checkInteger($value);
1876 when(/\bslony_database_name\b/i) {
1879 when(/\bslony_database_user\b/i) {
1882 when(/\bslony_database_password\b/i) {
1885 when(/\bslony_cluster_name\b/i) {
1888 when(/\benable_debugging\b/i) {
1889 $g_debug = checkBoolean($value);
1891 when(/\bprefix_directory\b/i) {
1894 when(/\bseparate_working_directory\b/i) {
1895 $g_separate_working = checkBoolean($value);
1897 when(/\bpid_filename\b/i) {
1898 $g_pidfile = $value;
1900 when(/\bfailover_offline_subscriber_only\b/i) {
1901 $g_fail_subonly = checkBoolean($value);
1903 when(/\bdrop_failed_nodes\b/i) {
1904 $g_drop_failed = checkBoolean($value);
1906 when(/\blog_line_prefix\b/i) {
1907 $g_log_prefix = $value;
1909 when(/\blog_filename\b/i) {
1910 $g_logfile = $value;
1912 when(/\blog_to_postgresql\b/i) {
1913 $g_log_to_db = checkBoolean($value);
1915 when(/\blog_database_host\b/i) {
1916 $g_logdb_host = $value;
1918 when(/\blog_database_port\b/i) {
1919 $g_logdb_port = checkInteger($value);
1921 when(/\blog_database_name\b/i) {
1922 $g_logdb_name = $value;
1924 when(/\blog_database_user\b/i) {
1925 $g_logdb_user = $value;
1927 when(/\blog_database_password\b/i) {
1928 $g_logdb_pass = $value;
1930 when(/\benable_try_blocks\b/i) {
1931 $g_use_try_blocks = checkBoolean($value);
1933 when(/\bpull_aliases_from_comments\b/i) {
1934 $g_use_comment_aliases = checkBoolean($value);
1936 when(/\bslonik_path\b/i) {
1937 $g_slonikpath = $value;
1939 when(/\blockset_method\b/i) {
1940 $g_lockset_method = $value;
1942 when(/\benable_autofailover\b/i) {
1943 $g_autofailover = checkBoolean($value);
1945 when(/\bautofailover_poll_interval\b/i) {
1946 $g_autofailover_poll_interval = checkInteger($value);
1948 when(/\bautofailover_node_retry\b/i) {
1949 $g_autofailover_retry = checkInteger($value);
1951 when(/\bautofailover_sleep_time\b/i) {
1952 $g_autofailover_retry_sleep = checkInteger($value);
1954 when(/\bautofailover_forwarding_providers\b/i) {
1955 $g_autofailover_provs = checkBoolean($value);
1957 when(/\bautofailover_config_any_node\b/i) {
1958 $g_autofailover_config_any = checkBoolean($value);
1960 when(/\bautofailover_perspective_sleep_time\b/i) {
1961 $g_autofailover_perspective_sleep = checkInteger($value);
1963 when(/\bautofailover_majority_only\b/i) {
1964 $g_autofailover_majority_only = checkBoolean($value);
1966 when(/\bautofailover_is_quorum\b/i) {
1967 $g_autofailover_is_quorum = checkBoolean($value);
1977 println(lookupMsg('err_fail_config'));
1986 if ( grep /^$text$/i, ("y","yes","t","true","on") ) {
1989 elsif ( grep /^$text$/i, ("n","no","f","false","off") ) {
1996 my $integer = shift;
1999 if (($integer * 1) eq $integer) {
2000 $value = int($integer);
2009 my $logfile = shift;
2010 my $log_prefix = shift;
2014 printlogln($prefix,$logfile,$log_prefix, lookupMsg('dbg_slonik_script', $script));
2016 if (open(SLONIKSTATUS, "-|", "slonik $script 2>&1")) {
2017 while (<SLONIKSTATUS>) {
2018 printlogln($prefix,$logfile,$log_prefix,lookupMsg('slonik_output', $_));
2020 close(SLONIKSTATUS);
2024 printlogln($prefix,$logfile,$log_prefix, lookupMsg('err_running_slonik', $!));
2031 my $dbconninfo = shift;
2036 my $logfile = shift;
2037 my $log_prefix = shift;
2044 my $cluster_loaded_from;
2049 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init'));
2050 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_cnf', ($g_autofailover_config_any ? 'any' : 'specified target')));
2051 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_pol', $g_autofailover_poll_interval));
2052 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_ret', $g_autofailover_retry, $g_autofailover_retry_sleep));
2053 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_init_set', ($g_autofailover_provs ? 'will' : 'will not')));
2056 # Probe current cluster configuration every minute
2057 if (!defined($cluster_time) || (time()-$cluster_time > 60)) {
2059 $cluster_loaded = false;
2060 if (!defined($cluster_time) || !$g_autofailover_config_any) {
2062 ($node_count, $version) = loadCluster($dbconninfo, $clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2063 die lookupMsg('err_cluster_empty') if ($node_count == 0);
2064 @cluster = @g_cluster;
2065 die lookupMsg('err_cluster_lone') if ($node_count == 1);
2066 $cluster_loaded = true;
2067 $cluster_loaded_from = 'conninfo specified in config';
2070 printlogln($prefix,$logfile,$log_prefix, lookupMsg('load_cluster_fail', 'from supplied configuration'));
2072 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2077 foreach (@cluster) {
2078 if ($_->[6] eq "ACTIVE") {
2079 unless ($cluster_loaded) {
2081 ($node_count, $version) = loadCluster($_->[2], $clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2082 die lookupMsg('err_cluster_empty') if ($node_count == 0);
2083 @cluster = @g_cluster;
2084 die lookupMsg('err_cluster_lone') if ($node_count == 1);
2085 $cluster_loaded = true;
2086 $cluster_loaded_from = $_->[0];
2089 printlogln($prefix,$logfile,$log_prefix, lookupMsg('load_cluster_fail', 'from node ' . $_->[0] . ': trying next node'));
2091 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2099 if ($cluster_loaded) {
2100 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_load_cluster', (!defined($cluster_time) ? "Loaded" : "Reloaded"), $version, $clname, $node_count, $cluster_loaded_from));
2101 $cluster_time = time();
2104 printlogln($prefix,$logfile,$log_prefix, lookupMsg('load_cluster_fail', 'from any node'));
2108 if ($cluster_loaded) {
2111 while(($current_retry <= $g_autofailover_retry) && ((!defined($failed)) || ($failed > 0))) {
2112 # Check status of cluster
2113 $failed = checkFailed($clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2116 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_cluster_good'));
2118 if ($current_retry > 0) {
2119 printlogln($prefix,$logfile,$log_prefix,lookupMsg('cluster_fixed'));
2123 if (($failed > 0) && ($current_retry <= $g_autofailover_retry)) {
2124 printlogln($prefix,$logfile,$log_prefix,lookupMsg('cluster_failed', $failed,$g_autofailover_retry_sleep,$current_retry,$g_autofailover_retry));
2125 usleep($g_autofailover_retry_sleep * 1000);
2129 if ((!$g_autofailover_majority_only || checkSplit($prefix, $logfile, $log_prefix)) && (($g_autofailover_perspective_sleep <= 0) || checkPerspective($clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix))) {
2130 $actions = findBackup($clname, $dbuser, $dbpass, $prefix, $logfile, $log_prefix);
2132 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_proceed'));
2133 foreach my $failed ( keys %g_backups ) {
2134 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_detail', $failed, $g_backups{$failed}));
2136 $g_script = writeFailover($prefix, $dbconninfo, $clname, $dbuser, $dbpass, undef, undef, $g_subs_follow_origin, $g_use_comment_aliases, $logfile, $log_prefix);
2137 unless (runSlonik($g_script, $prefix, $logfile, $log_prefix)) {
2138 printlogln($prefix,$logfile,$log_prefix,lookupMsg('err_execute_fail', 'slonik script', $g_script));
2140 $cluster_loaded = false;
2142 #print "SCRIPT: $g_script\n";
2146 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_halt', $failed));
2150 usleep($g_autofailover_poll_interval * 1000);
2161 my $logfile = shift;
2162 my $log_prefix = shift;
2164 my $majority = false;
2165 my $failed = scalar(@g_unresponsive);
2166 my $survivers = (scalar(@g_cluster) - scalar(@g_unresponsive));
2168 if ($survivers > $failed) {
2170 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_split_check', $survivers, ($survivers+$failed)));
2172 elsif (($survivers == $failed) && $g_autofailover_is_quorum) {
2174 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_split_check', ($survivers . '+quorum'), ($survivers+$failed)));
2177 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_split_check_fail', $survivers));
2183 # 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
2184 # 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.
2185 sub checkPerspective {
2190 my $logfile = shift;
2191 my $log_prefix = shift;
2200 my @unresponsive_ids;
2207 foreach (@g_unresponsive) {
2208 push(@unresponsive_ids, $_->[0]);
2210 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check', join(", ", @unresponsive_ids), scalar(@g_unresponsive), scalar(@g_cluster)));
2212 foreach (@g_cluster) {
2213 unless ($_->[0] ~~ @unresponsive_ids) {
2214 $dsn = "DBI:Pg:$_->[2];";
2216 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2217 $qw_clname = $dbh->quote_identifier("_" . $clname);
2219 $query = "SELECT a.st_origin, a.st_received, extract(epoch from a.st_lag_time)::integer
2220 FROM _test_replication.sl_status a
2221 INNER JOIN _test_replication.sl_node b on a.st_origin = b.no_id
2222 INNER JOIN _test_replication.sl_node c on a.st_received = c.no_id
2223 WHERE a.st_received IN (" . substr('?, ' x scalar(@unresponsive_ids), 0, -2) . ") ORDER BY a.st_origin, a.st_received;";
2225 $sth = $dbh->prepare($query);
2228 foreach (@unresponsive_ids) {
2229 $sth->bind_param($param_on, $_);
2234 while (my @node_lag = $sth->fetchrow) {
2235 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_data', 'Check1', $_->[0], $node_lag[0], $node_lag[1], $node_lag[2]));
2236 push(@lag_info1, \@node_lag);
2243 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_fail', $_->[0], $@));
2250 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_sleep', $g_autofailover_perspective_sleep));
2251 usleep($g_autofailover_perspective_sleep * 1000);
2253 foreach (@g_cluster) {
2254 unless ($_->[0] ~~ @unresponsive_ids) {
2255 $dsn = "DBI:Pg:$_->[2];";
2257 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2258 $qw_clname = $dbh->quote_identifier("_" . $clname);
2260 $query = "SELECT a.st_origin, a.st_received, extract(epoch from a.st_lag_time)::integer
2261 FROM _test_replication.sl_status a
2262 INNER JOIN _test_replication.sl_node b on a.st_origin = b.no_id
2263 INNER JOIN _test_replication.sl_node c on a.st_received = c.no_id
2264 WHERE a.st_received IN (" . substr('?, ' x scalar(@unresponsive_ids), 0, -2) . ") ORDER BY a.st_origin, a.st_received;";
2266 $sth = $dbh->prepare($query);
2269 foreach (@unresponsive_ids) {
2270 $sth->bind_param($param_on, $_);
2275 while (my @node_lag = $sth->fetchrow) {
2276 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_data', 'Check2', $_->[0], $node_lag[0], $node_lag[1], $node_lag[2]));
2277 push(@lag_info2, \@node_lag);
2284 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_fail', $_->[0], $@));
2292 foreach (@lag_info1) {
2294 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', ("Node $_->[0] lag between checks on node $_->[1] is " . ($lag_info2[$lag_idx]->[2]-$_->[2]) . " seconds")));
2297 if ((($lag_info2[$lag_idx]->[2]-$_->[2])*1000) >= $g_autofailover_perspective_sleep) {
2305 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_unknown'));
2307 elsif ($lag_idx == $lag_confirmed) {
2308 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_true'));
2312 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_pspec_check_false'));
2323 my $logfile = shift;
2324 my $log_prefix = shift;
2330 my $result_count = 0;
2331 my $prov_failed = 0;
2332 my $subonly_failed = 0;
2334 undef @g_unresponsive;
2336 foreach (@g_cluster) {
2337 if ($_->[6] eq "ACTIVE") {
2339 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_check',$_->[0], ($_->[4] // "unnamed"),(defined($_->[9]) ? "provider of sets $_->[9]" : "sole subscriber"),$_->[2]));
2343 if ((defined($_->[3])) || ($g_autofailover_provs && defined($_->[9]))) {
2344 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_active_check', 'provider', $_->[0]));
2347 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_active_check', 'subscriber only', $_->[0]));
2351 $dsn = "DBI:Pg:$_->[2];";
2353 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2354 $query = "SELECT count(*) FROM pg_namespace WHERE nspname = ?";
2355 $sth = $dbh->prepare($query);
2356 $sth->bind_param(1, "_" . $clname);
2359 $result_count = $result_count+$sth->rows;
2364 if (exists($g_unresponsive_subonly{$_->[0]})) {
2365 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_recovery_subonly', $_->[0]));
2366 delete $g_unresponsive_subonly{$_->[0]};
2371 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2373 push(@g_unresponsive, \@$_);
2374 if ((defined($_->[3])) || ($g_autofailover_provs && defined($_->[9]))) {
2375 if (defined($_->[3])) {
2376 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_unresponsive', $_->[0]));
2379 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_unresponsive_prov', $_->[0]));
2381 unless ($g_failover_method ne 'new' && !defined($_->[3])) {
2386 if (!exists($g_unresponsive_subonly{$_->[0]})) {
2387 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_unresponsive_subonly', $_->[0]));
2388 $g_unresponsive_subonly{$_->[0]} = true;
2390 if ($g_fail_subonly) {
2398 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_autofailover_check',$_->[0], ($_->[4] // "unnamed"), lc($_->[6] // "unknown") . ' node', $_->[2]));
2402 if ($prov_failed > 0) {
2403 return ($prov_failed+$subonly_failed);
2406 return $prov_failed;
2415 my $logfile = shift;
2416 my $log_prefix = shift;
2423 my $result_count = 0;
2424 my $lowest_lag_time;
2425 my $latest_last_event;
2427 my $best_node_is_direct;
2428 my $best_node_can_forward;
2432 my %backup_for_set_chosen;
2437 foreach (@g_unresponsive) {
2438 if ($g_fail_subonly || (defined($_->[3])) || ($g_autofailover_provs && defined($_->[9]))) {
2439 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_find', ($_->[9] // "none"), $_->[0]));
2441 undef $best_node_id;
2442 $lowest_lag_time = (1<<$Config{ivsize}*8-1)-1;
2443 $latest_last_event = 0;
2444 $best_node_is_direct = false;
2445 $best_node_can_forward = false;
2447 if (defined($_->[9]) && (exists $backup_for_set_chosen{$_->[9]})) {
2448 $best_node_id = $backup_for_set_chosen{$_->[9]};
2449 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_found', $_->[9], $_->[0]));
2452 foreach my $subscriber (@g_cluster) {
2453 if ($subscriber->[0] != $_->[0]) {
2455 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_check_sub',$subscriber->[0]));
2458 # Here the strings containing the sets are converted to arrays
2459 # Origin / Forwarded sets
2460 undef @sets_to_prov;
2461 if (defined($subscriber->[10])) {
2462 @sets_to_prov = split(',',$subscriber->[10]);
2464 if (defined($subscriber->[3])) {
2465 if (@sets_to_prov) {
2466 @sets_to_prov = (@sets_to_prov, split(',',$subscriber->[3]));
2469 @sets_to_prov = split(',',$subscriber->[3]);
2472 if (!defined($subscriber->[10]) && !defined($subscriber->[3])) {
2473 @sets_to_prov = (0);
2476 # Origin / Subscribed sets.
2478 if (defined($subscriber->[7])) {
2479 @sets_to = split(',',$subscriber->[7]);
2481 if (defined($subscriber->[3])) {
2483 @sets_to = (@sets_to, split(',',$subscriber->[3]));
2486 @sets_to = split(',',$subscriber->[3]);
2489 if (!defined($subscriber->[7]) && !defined($subscriber->[3])) {
2493 # Sets provided by the failed node.
2495 if (defined($_->[9])) {
2496 @sets_from = split(',',$_->[9]);
2503 $dsn = "DBI:Pg:$subscriber->[2]";
2506 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
2507 $qw_clname = $dbh->quote_identifier("_" . $clname);
2509 #print "\tNODE " . $subscriber->[0] . ") SETS TO = " . join(',', @sets_to) . " SETS FROM = " . join(',', @sets_from) . " SETS TO PROV = " . join(',', @sets_to_prov) . "\n";
2511 if (defined($subscriber->[3]) && checkProvidesAllSets(\@sets_from, \@sets_to)) {
2512 $query = "SELECT 0, ev_seqno, (ev_origin = ?)
2513 FROM $qw_clname.sl_event
2514 WHERE ev_origin = $qw_clname.getlocalnodeid(?)
2515 ORDER BY ev_seqno DESC LIMIT 1";
2518 $query = "SELECT extract(epoch from (current_timestamp-a.con_timestamp)), a.con_seqno, (a.con_origin = ?) AS direct
2519 FROM $qw_clname.sl_confirm a
2520 INNER JOIN $qw_clname.sl_event b on b.ev_seqno = a.con_seqno AND a.con_origin = b.ev_origin
2521 INNER JOIN $qw_clname.sl_subscribe c ON c.sub_provider = a.con_origin AND c.sub_receiver = a.con_received
2522 WHERE c.sub_active AND a.con_received = $qw_clname.getlocalnodeid(?)
2523 ORDER BY a.con_seqno DESC LIMIT 1;";
2526 $sth = $dbh->prepare($query);
2527 $sth->bind_param(1, $_->[0]);
2528 $sth->bind_param(2, "_" . $clname);
2531 while (my @subinfo = $sth->fetchrow) {
2532 # If the failed provider node isn't an origin for any sets, we classify any direct subscribers to it as indeirect
2533 # because they are indirect to the origin.
2534 if ($subinfo[2] && defined($_->[9]) && !defined($_->[3])) {
2535 $subinfo[2] = false;
2538 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_node_detail',
2540 ($subinfo[2]?"directly":"indirectly"),
2541 (defined($_->[3])?"origin":(defined($_->[9])?"provider":"subscriber only")),
2543 (defined($subscriber->[10])?$subscriber->[10]:(defined($subscriber->[3])?$subscriber->[3]:"<NONE>")),
2544 $subinfo[0], $subinfo[1]));
2546 # If select this node as the backup node if:
2547 # 1) The node is a subscriber to all sets on the failed node
2548 # 2) In order of preference:
2549 # The node is one of the direct subscribers to the failed node on the most recent event and is a forwarding provider
2551 # The node is one of the direct subscribers to the failed node on the most recent event and is not a forwarding provider
2553 # The node is an indirect subscriber to the failed node with the lowest lag time
2554 if (!checkProvidesAllSets(\@sets_from, \@sets_to)) {
2555 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_unsuitable', $subscriber->[0]));
2557 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)))
2558 || (!$best_node_is_direct && !$subinfo[2] && $subinfo[0] < $lowest_lag_time)) {
2559 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_best', $subscriber->[0], $subinfo[0], $subinfo[1]));
2560 $best_node_id = $subscriber->[0];
2561 $lowest_lag_time = $subinfo[0];
2562 $latest_last_event = $subinfo[1];
2563 $best_node_is_direct = $subinfo[2];
2564 $best_node_can_forward = checkProvidesAllSets(\@sets_from, \@sets_to_prov);
2570 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_check_sub_fail', $subscriber->[0]));
2572 printlogln($prefix,$logfile,$log_prefix,lookupMsg('dbg_generic', $@));
2578 if (defined($best_node_id)) {
2579 push(@g_failed, \@$_);
2580 $g_backups{$_->[0]} = $best_node_id;
2581 if (defined($_->[9]) && !(exists $g_backups{$_->[9]})) {
2582 $backup_for_set_chosen{$_->[9]} = $best_node_id;
2586 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_fail'));
2590 printlogln($prefix,$logfile,$log_prefix,lookupMsg('autofailover_promote_skip', $_->[0]));
2593 return keys(%g_backups);