]> git.8kb.co.uk Git - slony-i/pgbouncer_follower/blob - pgbouncer_follower.pl
Fix scenario where xlog locations differ but apply_lag has returned 0
[slony-i/pgbouncer_follower] / pgbouncer_follower.pl
1 #!/usr/bin/perl
2
3 # Script:   pgbouncer_follower.pl
4 # Copyright:    22/04/2012: v1.0.1 Glyn Astill <glyn@8kb.co.uk>
5 # Requires: Perl 5.10.1+, PostgreSQL 9.0+ Slony-I 2.0+ OR Streaming Replication
6 #
7 # This script is a command-line utility to monitor Slony-I clusters
8 # and reconfigure pgbouncer to follow replication sets.
9 #
10 # This script is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This script is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this script.  If not, see <http://www.gnu.org/licenses/>.
22
23 use strict;
24 use warnings;
25 use experimental 'smartmatch';
26 use DBI;
27 use v5.10.1;
28 use Getopt::Long qw/GetOptions/;
29 use Digest::MD5 qw/md5 md5_hex md5_base64/;
30 use Sys::Hostname;
31 use IO::Socket;
32 use Time::HiRes qw/usleep/;
33 use sigtrap 'handler' => \&cleanExit, 'HUP', 'INT','ABRT','QUIT','TERM';
34 Getopt::Long::Configure qw/no_ignore_case/;
35
36 use vars qw{%opt};
37
38 use constant false => 0;
39 use constant true  => 1;
40
41 my $g_usage = 'Pass configuration file: pool_follower.pl -f <configuration_path> [-D]  ';
42 my $g_method = "slony";
43 my $g_debug = false;
44 my $g_pidfile = "/tmp/pgbouncer_follower_%mode.pid";
45 my $g_logfile = "/tmp/pgbouncer_follower_%mode.log";
46 my $g_poll_interval = 1000;
47 my $g_user = "slony";
48 my $g_pass;
49 my $g_clname = "replication";
50 my $g_clsets = "1";
51 my @g_conninfos;
52 my @g_cluster;                  # no_id, no_comment, no_prov, orig_sets, conninfo, dbname, host, port
53 my $g_status_file = "/tmp/pgbouncer_follower_%mode.status";
54 my $g_conf_template = "/etc/pgbouncer/pgbouncer_%mode.template";
55 my $g_conf_target = "/etc/pgbouncer/pgbouncer_%mode.ini";
56 my $g_reload_command = "/etc/init.d/pgbouncer_%mode reload";
57 my $g_mode = 'rw';
58 my $g_all_databases=false;
59 my $g_auth_user='';
60 my ($year, $month, $day, $hour, $min, $sec);
61 my $change_time;
62 my $g_host = hostname;
63 my ($g_addr)=inet_ntoa((gethostbyname(hostname))[4]);
64 my $g_origins_only = false;
65 my $g_best_config = false;
66 my $g_max_lag = 0;
67
68 die $g_usage unless GetOptions(\%opt, 'config_file|f=s', 'daemon|D',) and keys %opt and ! @ARGV;
69
70 unless (getConfig($opt{config_file})){
71     print ("There was a problem reading the configuration.\n");
72 }
73  
74 if ($g_debug) {
75     printLogLn($g_logfile, "DEBUG: Logging to my '$g_logfile'");
76     if ($g_method eq 'slony') {
77         printLogLn($g_logfile, "\t Watching sets $g_clsets in Slony-I cluster '$g_clname' polling every ${g_poll_interval}ms"); 
78         printLogLn($g_logfile, "\t Following " . ($g_all_databases ? "all databases" : "replicated database only") . " on an '$g_mode' node for the above replicated sets");
79     }
80     elsif ($g_method eq 'wal')  {
81         printLogLn($g_logfile, "\t Watching streaming replication lag polling every ${g_poll_interval}ms"); 
82     }
83     else {
84         printLogLn($g_logfile, "\t ERROR: Unknown replication method: '$g_method'"); 
85         exit(1);
86     }
87     printLogLn($g_logfile, "\t Template config '$g_conf_template' Target config '$g_conf_target'");
88     printLogLn($g_logfile, "\t Reload command is '$g_reload_command'");
89     printLogLn($g_logfile, "\t Status stored in '$g_status_file'");
90     printLogLn($g_logfile, "\t Using local address for '$g_host' as '$g_addr'");
91     if (($g_max_lag > 0) && ($g_mode = 'ro')) {
92         printLogLn($g_logfile, "\t Max lag for read only targets will be $g_max_lag seconds");
93     }
94     #printLogLn($g_logfile, "\t '$g_user' as '$g_pass'");
95 }
96
97 if (defined($opt{daemon})) {
98     printLogLn($g_logfile, "pgbouncer_follower starting up");   
99     if (writePID($g_pidfile)) {
100         while (true) {
101             doAll();
102             if ($g_debug) {
103                 printLogLn($g_logfile, "DEBUG: Sleeping for ${g_poll_interval}ms");
104             }
105             usleep($g_poll_interval * 1000);
106         }
107     }
108 }
109 else {
110     doAll();
111 }
112
113 cleanExit(0);
114
115 sub cleanExit {
116     if (defined($opt{daemon})) {
117         printLogLn($g_logfile, "pgbouncer_follower shutting down");    
118         removePID($g_pidfile);
119     }
120     exit(0);
121 }
122
123 sub doAll {
124     my $node_to;
125     my $conninfo_read = 0;
126
127     foreach my $conninfo (@g_conninfos) {
128         $conninfo_read++;
129         eval {
130             if ($g_method eq 'slony') {
131                 @g_cluster = loadCluster($g_clname, $conninfo, $g_user, $g_pass, $g_addr, $g_clsets);
132             }
133             elsif ($g_method eq 'wal') {
134                 @g_cluster = loadBinCluster($g_user, $g_pass);
135             }
136             if ($g_debug) {
137                 printLogLn($g_logfile, "DEBUG: ($conninfo_read) " . (($g_method eq 'slony')?'Slony':'Streaming replication') . " cluster with " . scalar(@g_cluster) . " nodes " . (($g_method eq 'slony')?"read from conninfo: $conninfo":"provided via config conninfos"));
138                 foreach (@g_cluster) {
139                     printLogLn($g_logfile, "DEBUG: Node #" . @$_[0] . " DETAIL: " . @$_[1] . " " . @$_[2] . " " . (@$_[3] // "<NONE>") . " " . @$_[4] . " " . (@$_[5] // "<NONE>") . " " . @$_[6] . " " . @$_[7] . " " . @$_[8] . " " . @$_[9] . " " . @$_[10] . " "  . @$_[11]);
140                 }
141             }
142         };
143         if ($@) {
144             printLogLn($g_logfile, "ERROR: Failed using conninfo: $conninfo DETAIL: $@");
145         }
146         elsif($g_best_config) {
147             if ($g_debug) {
148                 printLogLn($g_logfile, "DEBUG: Found current origin to read config from");
149             }
150             last;
151         } 
152     }
153     unless (checkCluster($g_status_file)) {
154         if ($g_debug) {
155              printLogLn ($g_logfile, "DEBUG: Cluster status unchanged");
156         }
157     }
158     else {
159         printLogLn ($g_logfile, "Cluster status changed");
160         $node_to = generateConfig($g_conf_template, $g_conf_target, $g_mode, $g_all_databases, $g_clsets);
161         if (reloadConfig($g_reload_command)) {
162             printLogLn ($g_logfile, "Pool repointed to node #$node_to");
163         }
164     }
165 }
166
167 sub reloadConfig {
168     my $reload_command = shift;
169     my $success = true;
170     if(length($reload_command // '')) {
171         printLogLn($g_logfile, "Running '$reload_command'");
172         eval {
173             open(RELOAD, "-|", $reload_command . " 2>&1");
174             while (<RELOAD>) {
175                 printLogLn($g_logfile, $_);
176             }
177             close(RELOAD);
178             printLogLn($g_logfile, "Reload command has been run.");
179         };
180         if ($@) {
181             printLogLn($g_logfile, "ERROR: Failed to run reload command DETAIL: $@");
182             $success = false;
183         }
184     }
185     return $success;
186 }
187
188 sub generateConfig {
189     my $template = shift;
190     my $target = shift;
191     my $mode = shift;
192     my $all_databases = shift;
193     my $clsets = shift;
194
195     my $success = false;
196     my @sets_to_follow;
197     my @sets_origin;
198     my @sets_subscribed;
199     my $target_node_id;
200     my $target_db;
201     my $target_host;
202     my $target_sets;
203     my $target_port = 5432;
204     my $target_is_origin;
205     my $target_auth = "";
206
207     if ($g_debug) {
208         printLogLn($g_logfile, "DEBUG: All databases = " . ($all_databases ? 'true' : 'false'));
209     }
210
211     if ($g_auth_user ne "") {
212         $target_auth = " auth_user=" . $g_auth_user;
213     }
214
215     if (open(INFILE, "<", $template)) {
216         if (open(OUTFILE, ">", $target)) {
217             print OUTFILE "# Configuration file autogenerated at " . getRuntime() . " from $template\n";
218             foreach (<INFILE>) {
219                if (m/\[databases]/) {
220
221                     # Try and choose a node; we always assign the origin initially regardless of rw/ro status
222                     # when in ro mode and if we then  find a suitable subscriber we'll reassign to it.
223                     foreach my $node (@g_cluster) {
224                        
225
226                         # If the node is lagging anyway skip it 
227                         if (($g_mode eq 'ro') && ($g_max_lag > 0) && ($node->[11])) {
228                             printLogLn ($g_logfile, "Lag on node $node->[0] exceeds $g_max_lag seconds");
229                             next;
230                         }
231
232                         if ($clsets ne 'all') {
233                             @sets_to_follow = split(',', $clsets);
234                             if (defined($node->[3])) {
235                                 @sets_origin =  split(',', $node->[3]);
236                             }
237                             else {
238                                 undef @sets_origin;
239                             }
240                             if (defined($node->[5])) {
241                                 @sets_subscribed =  split(',', $node->[5]);
242                             }
243                             else {
244                                 undef @sets_subscribed;
245                             }
246                         }
247
248                         if (($clsets eq 'all' && defined($node->[3])) || (@sets_to_follow && @sets_origin && checkProvidesAllSets(\@sets_to_follow, \@sets_origin))) {
249                             if (defined($node->[8])) {
250                                 $target_db = $node->[7];
251                                 $target_host = $node->[8];
252                                 $target_node_id = $node->[0];
253                                 $target_sets = $node->[3];
254                                 $target_is_origin = true;
255                             }
256                             if (defined($node->[9])) {
257                                 $target_port = $node->[9];
258                             }
259                             if ($mode eq "rw") {
260                                 last;
261                             }
262                         }
263                         elsif (($mode eq "ro") && (($clsets eq 'all') || (@sets_to_follow && @sets_subscribed && checkProvidesAllSets(\@sets_to_follow, \@sets_subscribed)))) {    
264                             if (defined($node->[8])) {
265                                 $target_db = $node->[7];
266                                 $target_host = $node->[8];
267                                 $target_node_id = $node->[0];
268                                 $target_sets = ($node->[5] // $node->[3]);
269                                 $target_is_origin = false;
270                             }
271                             if (defined($node->[9])) {
272                                 $target_port = $node->[9];
273                             }
274                             last;
275                         }
276                     }
277                     if (defined($target_host)) {
278                         $_ = "# Configuration for " . ($target_is_origin ? "origin" : "subscriber") . " of sets $target_sets node #$target_node_id $target_host:$target_port\n" . $_;
279                         if ($g_debug) {
280                             printLogLn ($g_logfile, "DEBUG: Configuration for " . ($target_is_origin ? "origin" : "subscriber") . " of sets $target_sets node #$target_node_id $target_host:$target_port");
281                         }
282                         if ($all_databases || $target_db eq '*') {
283                             $_ =~ s/(\[databases\])/$1\n\* = host=$target_host port=$target_port$target_auth/;
284                         }
285                         else {
286                             $_ =~ s/(\[databases\])/$1\n$target_db = host=$target_host port=$target_port dbname=$target_db$target_auth/;
287                         }
288                     }
289                     else {
290                             $_ = "# Could not find any node providing sets $g_clsets in mode $mode\n";
291                             printLogLn ($g_logfile, "DEBUG: Could not find any node providing sets $g_clsets in mode $mode");
292                     }
293                     
294                } 
295                print OUTFILE $_;
296             }
297             close (OUTFILE); 
298         }
299         else {
300             print ("ERROR: Can't open file $target\n");
301         }
302         close(INFILE);
303     }
304     else {
305         print ("ERROR: Can't open file $template\n");
306     }
307     return $target_node_id;
308 }
309
310 sub checkCluster {
311     my $infile = shift;
312     my $changed = false;
313     my $current_state = md5_hex('INIT');
314     my $previous_state;
315     foreach (@g_cluster) {
316         if (!$g_origins_only || defined($_->[3])) {
317             $current_state = md5_hex(($current_state // "") . $_->[0] . $_->[2] . (defined($_->[3]) ? 't' : 'f') . $_->[6] . $_->[11]);
318             if ($g_debug) {
319                 printLogLn($g_logfile, "DEBUG: Node " . $_->[0] . " detail = " . $_->[2] . (defined($_->[3]) ? 't' : 'f') . $_->[6] . $_->[11]);
320             }
321         }
322     }
323    
324     if (-f $infile) {
325         if (open(CLUSTERFILE, "<", $infile)) {
326             $previous_state = <CLUSTERFILE>;
327             close(CLUSTERFILE);
328         }
329         else {
330             printLogLn ($g_logfile, "ERROR: Can't open file $infile for reading");
331         }
332     }
333
334     unless (-f $infile && ($current_state eq $previous_state)) {
335         if ($g_debug) {
336                 printLogLn($g_logfile, "DEBUG: Writing to status file");
337         }
338         if (open(CLUSTERFILE, ">", $infile)) {
339             print CLUSTERFILE $current_state;
340             close(CLUSTERFILE);
341         }
342         else {
343             printLogLn ($g_logfile, "ERROR: Can't open file $infile for writing");
344         }
345     }
346
347     if ((($previous_state // "") ne "") && ($current_state ne $previous_state)){
348         $changed = true;
349     }
350
351     return $changed
352 }
353
354 sub loadCluster {
355     my $clname = shift;
356     my $conninfo = shift;
357     my $dbuser = shift;
358     my $dbpass = shift;
359     my $addr = shift;
360     my $clsets = shift;
361     my $param_on = 1;
362
363     my $dsn;
364     my $dbh;
365     my $sth;
366     my $query;
367     my $version;
368     my $qw_clname;
369     my @cluster;
370
371     $g_best_config = false;
372     $dsn = "DBI:Pg:$conninfo};";
373
374     eval {
375         $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
376         $qw_clname = $dbh->quote_identifier("_" . $clname);
377
378         $query = "SELECT $qw_clname.getModuleVersion()";
379         $sth = $dbh->prepare($query);
380         $sth->execute();
381         ($version) = $sth->fetchrow; 
382         $sth->finish;
383
384         $query = "WITH x AS (
385                 SELECT a.no_id, 
386                     a.no_comment, 
387                     COALESCE(b.sub_provider, 0) AS no_prov, 
388                     NULLIF(array_to_string(array(SELECT set_id FROM $qw_clname.sl_set WHERE set_origin = a.no_id" .
389                     ($clsets ne "all" ? " AND set_id IN (" . substr('?, ' x scalar(split(',', $clsets)), 0, -2) . ")" : "") 
390                     . " ORDER BY set_id), ','), '') AS origin_sets,
391                     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,
392                     string_agg(CASE WHEN b.sub_receiver = a.no_id AND b.sub_forward AND b.sub_active" .
393                     ($clsets ne "all" ? " AND b.sub_set IN (" . substr('?, ' x scalar(split(',', $clsets)), 0, -2) . ")" : "") 
394                     . " THEN b.sub_set::text END, ',' ORDER BY b.sub_set) AS prov_sets,
395                     COALESCE(c.pa_conninfo,(SELECT pa_conninfo FROM $qw_clname.sl_path WHERE pa_server = $qw_clname.getlocalnodeid(?) LIMIT 1)) AS no_conninfo
396                 FROM $qw_clname.sl_node a
397                 LEFT JOIN $qw_clname.sl_subscribe b ON a.no_id = b.sub_receiver AND b.sub_set <> 999 
398                 LEFT JOIN $qw_clname.sl_path c ON c.pa_server = a.no_id AND c.pa_client = $qw_clname.getlocalnodeid(?)
399                 LEFT JOIN $qw_clname.sl_set d ON d.set_origin = a.no_id
400                 GROUP BY b.sub_provider, a.no_id, a.no_comment, c.pa_conninfo, a.no_active
401                 ORDER BY (COALESCE(b.sub_provider, 0) = 0) DESC, a.no_id ASC
402                 ), z AS (
403                 SELECT x.*,  
404                     CASE WHEN x.no_conninfo ilike '%dbname=%' THEN(regexp_matches(x.no_conninfo, E'dbname=(.+?)\\\\M', 'ig'))[1] END AS database,
405                     CASE WHEN x.no_conninfo ilike '%host=%' THEN(regexp_matches(x.no_conninfo, E'host=(.+?)(?=\\\\s|\$)', 'ig'))[1] END AS host,
406                     CASE WHEN x.no_conninfo ilike '%port=%' THEN(regexp_matches(x.no_conninfo, E'port=(.+?)\\\\M', 'ig'))[1] ELSE '5432' END AS port,
407                     (no_id = $qw_clname.getlocalnodeid(?)) AS this_node,
408                     COALESCE((? BETWEEN 1 AND extract(epoch from s.st_lag_time)),false) AS lag_exceeded
409                 FROM x 
410                 LEFT JOIN $qw_clname.sl_status s ON s.st_received = x.no_id
411                 WHERE x.no_conninfo != '<event pending>'
412                 )
413                 SELECT * FROM z 
414                 ORDER BY origin_sets, @(CASE WHEN (host ~ '^[0-9]{1,3}(.[0-9]{1,3}){3}\$') THEN host::inet ELSE '255.255.255.255'::inet END - ?::inet) ASC";
415
416         if ($g_debug) { 
417 #            printLogLn($g_logfile, "DEBUG: " . $query);
418         }
419
420         $sth = $dbh->prepare($query);
421
422         if ($clsets ne "all") {
423             for (0..1) { 
424                 foreach my $param (split(",", $clsets)) {
425                     $sth->bind_param($param_on, $param);
426                     $param_on++;
427                 } 
428             }
429         }
430         # This param is taken 3 times
431         for (0..2) {
432             $sth->bind_param($param_on, "_" . $clname);
433             $param_on++;
434         }
435         $sth->bind_param($param_on, $g_max_lag);
436         $param_on++;
437         $sth->bind_param($param_on, (isInet($addr) ? $addr : '255.255.255.255'));
438         $sth->execute();
439
440         while (my @node = $sth->fetchrow) {
441             # If some origin sets exist for this node row (we can assume they're the sets we're following since they're filtered in the query)
442             # and the row is flagged as this_node then we have found the best node to read the configuration from.
443             if (defined($node[3]) && $node[10]) {
444                 $g_best_config = true;
445             }
446             push(@cluster,  \@node);
447         }
448
449         $sth->finish;
450         $dbh->disconnect();
451     };
452     if ($@) { 
453         printLogLn($g_logfile, "ERROR: Failed to execute query against Postgres server: $@");
454     }
455
456     return @cluster;
457 }
458
459 sub loadBinCluster {
460     my $dbuser = shift;
461     my $dbpass = shift;
462
463     my $dsn;
464     my $dbh;
465     my $sth;
466     my $query;
467     my $recovery;
468     my $xlog_location;
469     my $apply_lag;
470     my $primaries = 0;
471
472     my @parts;
473     my $timeline;
474     my $location;
475     my $primary_location;
476
477     my $hostname;
478     my $port;
479     my $database;
480     my @tmp_cluster;
481     my @cluster;
482     my $node_id = 1;
483     $g_best_config = true;
484
485     foreach my $conninfo (@g_conninfos) {
486         $dsn = "DBI:Pg:$conninfo};";
487
488         eval {
489             $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
490             # Check to see if the server is a secondary, and also pull the current xlog
491             # location and the apply lag using pg_last_xact_replay_timestamp to get the
492             # last commit timestamp from the primary applied on the secondary.
493             # We will need to compare the current receive location to the primary xlog 
494             # location, if they differ we can then use the apply_lag value; we'll have 
495             # to post-process this.
496             # In 9.6+ we might want to pull the system identifier from pg_controldata view too
497             $query = "SELECT pg_is_in_recovery(), 
498                           CASE 
499                               WHEN pg_is_in_recovery() THEN pg_last_xlog_receive_location() 
500                               ELSE pg_current_xlog_location() 
501                           END,
502                           COALESCE(extract(epoch from current_timestamp-pg_last_xact_replay_timestamp()),0)";
503             $sth = $dbh->prepare($query);
504             $sth->execute();
505             ($recovery, $xlog_location, $apply_lag) = $sth->fetchrow;
506             $sth->finish;
507
508             ($port) = $conninfo =~ m/port=(.+?)(\s|$)/g; 
509             ($hostname) = $conninfo =~ m/host=(.+?)(\s|$)/g; 
510             ($database) = $conninfo =~ m/dbname=(.+?)(\s|$)/g; 
511             @parts = split('/', $xlog_location, 2);
512             $timeline = qtrim(trim($parts[0]));
513             $location = hex(qtrim(trim($parts[1])));
514
515             if ($g_debug) {
516                 printLogLn($g_logfile, "DEBUG: Server: $hostname:$port " . ($recovery ? 'secondary' : 'primary') . " at $xlog_location ($timeline/$location)");
517             }
518
519             # For WAL replication we assume if we can contact a server then it is active,
520             # which isn't strictly true, but nodes that have fallen behind can be excluded
521             # via the max_ro_lag setting.  We also substitute timeline+1 for the slony 
522             # replication set.
523             if (!$recovery) {
524                 $primaries++;
525                 $primary_location = $xlog_location;
526                 my @node=(1,'Primary',0,$timeline,"ACTIVE",($timeline+1),$conninfo,$database,$hostname,$port,1,$xlog_location,$apply_lag);
527                 push(@tmp_cluster,  \@node);
528             }
529             else {
530                 $node_id++;     
531                 my @node=($node_id,"Secondary".($node_id-1),1,undef,"ACTIVE",($timeline+1),$conninfo,$database,$hostname,$port,$node_id,$xlog_location,$apply_lag);
532                 push(@tmp_cluster,  \@node);
533             }
534         };
535         if ($@) {
536             printLogLn($g_logfile, "ERROR: Could not connect to server with conninfo: $conninfo DETAIL: $@");
537         }
538     }
539
540     # Error if more than one primary discovered.
541     if ($primaries != 1) {
542         printLogLn($g_logfile, "ERROR: Invalid quantity of primaries: $primaries");
543         die "no primaries found";
544     }
545     # Do the post processing we mentioned above, once we know xlog locations differ
546     # then we can say the apply lag is correct, else it's just there has been no
547     # activity on the master. In the case the xlog locations differ but apply_lag
548     # is 0 then it means no WAL has been applied since srver start; cludge here
549     # and set lag to 1 week.
550     else {
551         foreach (@tmp_cluster) {
552             if (@$_[11] eq $primary_location) {
553                 $apply_lag = 0;
554             }
555             else {
556                 $apply_lag = @$_[12] if (@$_[12] > 0);
557                 $apply_lag = 604800 if (@$_[12] = 0);
558             }
559             my @node=(@$_[0],@$_[1],@$_[2],@$_[3],@$_[4],@$_[5],@$_[6],@$_[7],@$_[8],@$_[9],@$_[10],$apply_lag);
560             push(@cluster,  \@node);
561         }
562     }
563
564     return @cluster;
565 }
566
567 sub getConfig {
568     my @fields;
569     my $success = false;
570     my $infile = shift;
571     my $value;
572
573     if (open(CFGFILE, "<", $infile)) {
574         foreach (<CFGFILE>) {
575             chomp $_;
576             for ($_) {
577                 s/\r//;
578                 #s/\#.*//;
579                 s/#(?=(?:(?:[^']|[^"]*+'){2})*+[^']|[^"]*+\z).*//;
580             } 
581             if (length(trim($_))) {
582                 @fields = split('=', $_, 2);
583                 $value = qtrim(trim($fields[1]));
584                 given(lc($fields[0])) {
585                     when(/\breplication_method\b/i) {
586                         $g_method = $value;
587                     }
588                     when(/\bdebug\b/i) {
589                         $g_debug = checkBoolean($value);
590                     }
591                     when(/\bpid_file\b/i) {
592                         $g_pidfile = $value;
593                     }
594                     when(/\blog_file\b/i) {
595                         $g_logfile = $value;
596                     }
597                     when(/\bslony_user\b/i) { # Depreciated
598                         $g_user = $value;
599                     }
600                     when(/\bslony_pass\b/i) { # Depreciated
601                         $g_pass = $value;
602                     }
603                     when(/\breplication_user\b/i) {
604                         $g_user = $value;
605                     }
606                     when(/\breplication_pass\b/i) {
607                         $g_pass = $value;
608                     }
609                     when(/\bslony_cluster_name\b/i) {
610                         $g_clname = $value;
611                     }
612                     when(/\bslony_sets_to_follow\b/i) {
613                         $g_clsets = $value;
614                     }
615                     when(/\bserver_conninfo\b/i) {
616                         push(@g_conninfos, $value);
617                     }
618                     when(/\bfollower_poll_interval\b/i) {
619                         $g_poll_interval = checkInteger($value);
620                     }
621                     when(/\bstatus_file\b/i) {
622                         $g_status_file = $value;
623                     } 
624                     when(/\bpool_conf_template\b/i) {
625                         $g_conf_template = $value;
626                     } 
627                     when(/\bpool_conf_target\b/i) {
628                         $g_conf_target = $value;
629                     } 
630                     when(/\bpool_reload_command\b/i) {
631                         $g_reload_command = $value;
632                     } 
633                     when(/\bpool_mode\b/i) {
634                         $g_mode = lc($value);
635                     } 
636                     when(/\bpool_all_databases\b/i) {
637                         $g_all_databases = checkBoolean($value);
638                     }
639                     when(/\bauth_user\b/i) {
640                         $g_auth_user = $value;
641                     }
642                     when(/\bonly_follow_origins\b/i) {
643                         $g_origins_only = checkBoolean($value);
644                     }
645                     when(/\bmax_ro_lag\b/i) {
646                         $g_max_lag = checkInteger($value);
647                     }
648                 }  
649             }
650         }
651         close (CFGFILE);
652         if (defined($g_user) && (scalar(@g_conninfos) > 0)) {
653            $success = true;
654         }
655         # Replace %mode and %clname here for actual value
656         for ($g_pidfile, $g_logfile, $g_status_file, $g_conf_template, $g_conf_target, $g_reload_command) {
657             s/\%mode/$g_mode/g;
658             s/\%clname/$g_clname/g;
659         }
660
661
662     }
663     else {
664         printLogLn($g_logfile, "ERROR: Could not read configuration from '$infile'");
665     }
666     return $success;
667 }
668
669 sub writePID {
670     my $pidfile = shift;
671     my $success = true;
672
673     eval {
674         open (PIDFILE, ">", $pidfile);
675         print PIDFILE $$;
676         close (PIDFILE);
677         if ($g_debug) {
678             printLogLn($g_logfile, "DEBUG: Created PID file '$pidfile' for process $$");
679         }
680     };
681     if ($@) {
682         printLogLn($g_logfile, "ERROR: unable to write pidfile at '$pidfile' DETAIL $!");       
683         $success = false;
684     }
685     return $success;
686 }
687
688 sub removePID {
689     my $pidfile = shift;
690     my $success = true;
691
692     eval {
693         if (-f $pidfile) {
694             unlink $pidfile;
695             if ($g_debug) {
696                 printLogLn($g_logfile, "DEBUG: Removed PID file '$pidfile'");
697             }
698         }
699         elsif ($g_debug){
700             printLogLn($g_logfile, "DEBUG: PID file '$pidfile' never existed to be removed");
701         } 
702     };
703     if ($@) {
704         printLogLn($g_logfile, "ERROR: unable to remove pidfile at '$pidfile' DETAIL $!");       
705         $success = false;
706     }
707     return $success
708 }
709
710 sub checkBoolean {
711     my $text = shift;
712     my $value = undef;
713     if ( grep /^$text$/i, ("y","yes","t","true","on") ) {
714         $value = true;
715     }
716     elsif ( grep /^$text$/i, ("n","no","f","false","off") ) {
717         $value = false;
718     }
719     return $value;
720 }
721
722 sub checkInteger {
723     my $integer = shift;
724     my $value = undef;
725
726     if (($integer * 1) eq $integer) {
727         $value = int($integer);
728     }
729     return $value;
730 }
731
732 sub checkProvidesAllSets { 
733     my ($originSets, $providerSets) = @_;
734     my %test_hash;
735
736     undef @test_hash{@$originSets};       # add a hash key for each element of @$originSets
737     delete @test_hash{@$providerSets};    # remove all keys for elements of @$providerSets
738
739     return !%test_hash;              # return false if any keys are left in the hash
740 }
741
742 sub isInet {
743     my $address = shift;
744     my $success = true;
745
746     my(@octets) = $address =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
747     if (@octets == 4) {
748         foreach (@octets) {
749             unless ($_ <= 255) {
750                 $success = false;
751             }
752         }
753     }
754     else {
755         $success = false;
756     }
757
758     return $success;
759 }
760
761 sub qtrim {
762     my $string = shift;
763     $string =~ s/^('|")+//;
764     $string =~ s/('|")+$//;
765     return $string;
766 }
767
768 sub trim {
769     my $string = shift;
770     $string =~ s/^\s+//;
771     $string =~ s/\s+$//;
772     return $string;
773 }
774
775 sub getRuntime {
776     my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
777     my $time = sprintf ("%02d:%02d:%02d on %02d/%02d/%04d", $hour, $min, $sec, $day, $month+1, $year+1900);
778     return $time;
779 }
780
781 sub printLog {
782     my $logfile = shift;
783     my $message = shift;
784
785     print $message;
786
787     if (open(LOGFILE, ">>", $logfile)) {
788         print LOGFILE getRuntime() . " " . $message;
789         close (LOGFILE);
790     }
791     else {
792         printLn("ERROR: Unable to write to logfile $logfile");
793     }
794 }
795
796 sub printLogLn {
797     printLog ($_[0], $_[1] . $/);
798 }
799
800 sub printLn {
801     print ((@_ ? join($/, @_) : $_), $/);
802 }