]> git.8kb.co.uk Git - slony-i/pgbouncer_follower/blob - pgbouncer_follower.pl
Don't attempt to fix undefined status file
[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+
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 DBI;
26 use v5.10.1;
27 use Getopt::Long qw/GetOptions/;
28 use Digest::MD5 qw/md5 md5_hex md5_base64/;
29 use Sys::Hostname;
30 use IO::Socket;
31 use Time::HiRes qw/usleep/;
32 use sigtrap 'handler' => \&cleanExit, 'HUP', 'INT','ABRT','QUIT','TERM';
33 Getopt::Long::Configure qw/no_ignore_case/;
34
35 use vars qw{%opt};
36
37 use constant false => 0;
38 use constant true  => 1;
39
40 my $g_usage = 'Pass configuration file: pool_follower.pl -f <configuration_path> [-D]  ';
41 my $g_debug = false;
42 my $g_pidfile = "/tmp/pgbouncer_follower_%mode.pid";
43 my $g_logfile = "/tmp/pgbouncer_follower_%mode.log";
44 my $g_poll_interval = 1000;
45 my $g_user = "slony";
46 my $g_pass;
47 my $g_clname = "replication";
48 my $g_clsets = "1";
49 my @g_conninfos;
50 my @g_cluster;                  # no_id, no_comment, no_prov, orig_sets, conninfo, dbname, host, port
51 my $g_status_file = "/tmp/pgbouncer_follower_%mode.status";
52 my $g_conf_template = "/etc/pgbouncer/pgbouncer_%mode.template";
53 my $g_conf_target = "/etc/pgbouncer/pgbouncer_%mode.ini";
54 my $g_reload_command = "/etc/init.d/pgbouncer_%mode reload";
55 my $g_mode = 'rw';
56 my $g_all_databases=false;
57 my ($year, $month, $day, $hour, $min, $sec);
58 my $change_time;
59 my $g_host = hostname;
60 my ($g_addr)=inet_ntoa((gethostbyname(hostname))[4]);
61
62 die $g_usage unless GetOptions(\%opt, 'config_file|f=s', 'daemon|D',) and keys %opt and ! @ARGV;
63
64 unless (getConfig($opt{config_file})){
65     print ("There was a problem reading the configuration.\n");
66 }
67  
68 if ($g_debug) {
69     printLogLn($g_logfile, "DEBUG: Logging to my '$g_logfile'");
70     printLogLn($g_logfile, "\t Watching sets $g_clsets in Slony-I cluster '$g_clname' polling every ${g_poll_interval}ms"); 
71     printLogLn($g_logfile, "\t Following " . ($g_all_databases ? "all databases" : "replicated database only") . " on an '$g_mode' node for the above replicated sets");
72     printLogLn($g_logfile, "\t Template config '$g_conf_template' Target config '$g_conf_target'");
73     printLogLn($g_logfile, "\t Reload command is '$g_reload_command'");
74     printLogLn($g_logfile, "\t Status stored in '$g_status_file'");
75     printLogLn($g_logfile, "\t Using local address for '$g_host' as '$g_addr'");
76     #printLogLn($g_logfile, "\t '$g_user' as '$g_pass'");
77 }
78
79 if (defined($opt{daemon})) {
80     printLogLn($g_logfile, "pgbouncer_follower starting up");   
81     if (writePID($g_pidfile)) {
82         while (true) {
83             doAll();
84             if ($g_debug) {
85                 printLogLn($g_logfile, "DEBUG: Sleeping for ${g_poll_interval}ms");
86             }
87             usleep($g_poll_interval * 1000);
88         }
89     }
90 }
91 else {
92     doAll();
93 }
94
95 cleanExit(0);
96
97 sub cleanExit {
98     if (defined($opt{daemon})) {
99         printLogLn($g_logfile, "pgbouncer_follower shutting down");    
100         removePID($g_pidfile);
101     }
102     exit(0);
103 }
104
105 sub doAll {
106     my $node_to;
107
108     foreach my $conninfo (@g_conninfos) {
109         eval {
110             @g_cluster = loadCluster($g_clname, $conninfo, $g_user, $g_pass, $g_addr, $g_clsets);
111             if ($g_debug) {
112                 printLogLn($g_logfile, "DEBUG: Cluster with " . scalar(@g_cluster) . " nodes read from conninfo: $conninfo");
113                 foreach (@g_cluster) {
114                     printLogLn($g_logfile, "DEBUG: Node #" . @$_[0] . " DETAIL: " . @$_[1] . " " . @$_[2] . " " . (@$_[3] // "<NONE>") . " " . @$_[4] . " " . (@$_[5] // "<NONE>") . " " . @$_[6] . " " . @$_[7] . " " . @$_[8] . " " . @$_[9] . " " );
115                 }
116             }
117         };
118         if ($@) {
119             printLogLn($g_logfile, "ERROR: Failed using conninfo: $conninfo DETAIL: $@");
120         }
121         else {
122             last;
123         } 
124     }
125     unless (checkCluster($g_status_file)) {
126         if ($g_debug) {
127              printLogLn ($g_logfile, "DEBUG: Cluster status unchanged");
128         }
129     }
130     else {
131         printLogLn ($g_logfile, "Cluster status changed");
132         $node_to = generateConfig($g_conf_template, $g_conf_target, $g_mode, $g_all_databases, $g_clsets);
133         if (reloadConfig($g_reload_command)) {
134             printLogLn ($g_logfile, "Pool repointed to node #$node_to");
135         }
136     }
137 }
138
139 sub reloadConfig {
140     my $reload_command = shift;
141     my $success = true;
142     if(length($reload_command // '')) {
143         printLogLn($g_logfile, "Running '$reload_command'");
144         eval {
145             open(RELOAD, "-|", $reload_command . " 2>&1");
146             while (<RELOAD>) {
147                 printLogLn($g_logfile, $_);
148             }
149             close(RELOAD);
150             printLogLn($g_logfile, "Reload command has been run.");
151         };
152         if ($@) {
153             printLogLn($g_logfile, "ERROR: Failed to run reload command DETAIL: $@");
154             $success = false;
155         }
156     }
157     return $success;
158 }
159
160 sub generateConfig {
161     my $template = shift;
162     my $target = shift;
163     my $mode = shift;
164     my $all_databases = shift;
165     my $clsets = shift;
166
167     my $success = false;
168     my @sets_to_follow;
169     my @sets_origin;
170     my @sets_subscribed;
171     my $target_node_id;
172     my $target_db;
173     my $target_host;
174     my $target_sets;
175     my $target_port = 5432;
176     my $target_is_origin;
177
178     if ($g_debug) {
179         printLogLn($g_logfile, "DEBUG: All databases = " . ($g_all_databases ? 'true' : 'false'));
180     }
181
182     if (open(INFILE, "<", $template)) {
183         if (open(OUTFILE, ">", $target)) {
184             print OUTFILE "# Configuration file autogenerated at " . getRuntime() . " from $template\n";
185             foreach (<INFILE>) {
186                if (m/\[databases]/) {
187
188                     # Try and choose a node; we always assign the origin initially regardless of rw/ro status
189                     # when in ro mode and if we then  find a suitable subscriber we'll reassign to it.
190                     foreach my $node (@g_cluster) {
191                         if ($clsets ne 'all') {
192                             @sets_to_follow = split(',', $clsets);
193                             if (defined($node->[3])) {
194                                 @sets_origin =  split(',', $node->[3]);
195                             }
196                             else {
197                                 undef @sets_origin;
198                             }
199                             if (defined($node->[6])) {
200                                 @sets_subscribed =  split(',', $node->[6]);
201                             }
202                             else {
203                                 undef @sets_subscribed;
204                             }
205                         }
206
207                         if (($clsets eq 'all' && defined($node->[3])) || (@sets_to_follow && @sets_origin && checkProvidesAllSets(\@sets_to_follow, \@sets_origin))) {
208                             if (defined($node->[8])) {
209                                 $target_db = $node->[7];
210                                 $target_host = $node->[8];
211                                 $target_node_id = $node->[0];
212                                 $target_sets = $node->[3];
213                                 $target_is_origin = true;
214                             }
215                             if (defined($node->[9])) {
216                                 $target_port = $node->[9];
217                             }
218                             if ($mode eq "rw") {
219                                 last;
220                             }
221                         }
222                         elsif (($mode eq "ro") && (($clsets eq 'all') || (@sets_to_follow && @sets_subscribed && checkProvidesAllSets(\@sets_to_follow, \@sets_subscribed)))) {    
223                             if (defined($node->[8])) {
224                                 $target_db = $node->[7];
225                                 $target_host = $node->[8];
226                                 $target_node_id = $node->[0];
227                                 $target_sets = ($node->[6] // $node->[3]);
228                                 $target_is_origin = false;
229                             }
230                             if (defined($node->[9])) {
231                                 $target_port = $node->[9];
232                             }
233                             last;
234                         }
235                     }
236                     if (defined($target_host)) {
237                         $_ = "# Configuration for " . ($target_is_origin ? "origin" : "subscriber") . " of sets $target_sets node #$target_node_id $target_host:$target_port\n" . $_;
238                         printLogLn ($g_logfile, "DEBUG: Configuration for " . ($target_is_origin ? "origin" : "subscriber") . " of sets $target_sets node #$target_node_id $target_host:$target_port");
239                         if ($all_databases) {
240                             $_ =~ s/(\[databases\])/$1\n\* = host=$target_host port=$target_port/;
241                         }
242                         else {
243                             $_ =~ s/(\[databases\])/$1\n$target_db = host=$target_host port=$target_port dbname=$target_db/;
244                         }
245                     }
246                     else {
247                             $_ = "# Could not find any node providing sets $g_clsets in mode $mode\n";
248                             printLogLn ($g_logfile, "DEBUG: Could not find any node providing sets $g_clsets in mode $mode");
249                     }
250                     
251                } 
252                print OUTFILE $_;
253             }
254             close (OUTFILE); 
255         }
256         else {
257             print ("ERROR: Can't open file $target\n");
258         }
259         close(INFILE);
260     }
261     else {
262         print ("ERROR: Can't open file $template\n");
263     }
264     return $target_node_id;
265 }
266
267 sub checkCluster {
268     my $infile = shift;
269     my $changed = false;
270     my $current_cluster;
271     my $previous_cluster;
272     foreach (@g_cluster) {
273         $current_cluster = md5_hex(($current_cluster // "") . $_->[0] . $_->[2] . (defined($_->[3]) ? 't' : 'f'));
274         if ($g_debug) {
275             printLogLn($g_logfile, "DEBUG: Node " . $_->[0] . " detail = " . $_->[2] . (defined($_->[3]) ? 't' : 'f'));
276         }
277     }
278    
279     if (-f $infile) {
280         if (open(CLUSTERFILE, "<", $infile)) {
281             $previous_cluster = <CLUSTERFILE>;
282             close(CLUSTERFILE);
283         }
284         else {
285             printLogLn ($g_logfile, "ERROR: Can't open file $infile for reading");
286         }
287     }
288
289     if (open(CLUSTERFILE, ">", $infile)) {
290         print CLUSTERFILE $current_cluster;
291         close(CLUSTERFILE);
292     }
293     else {
294         printLogLn ($g_logfile, "ERROR: Can't open file $infile for writing");
295     }
296
297     if ((($previous_cluster // "")ne "") && (($current_cluster // "") ne "") && ($current_cluster ne $previous_cluster)){
298         $changed = true;
299     }
300
301     return $changed
302 }
303
304 sub loadCluster {
305     my $clname = shift;
306     my $conninfo = shift;
307     my $dbuser = shift;
308     my $dbpass = shift;
309     my $addr = shift;
310     my $clsets = shift;
311     my $param_on = 1;
312
313     my $dsn;
314     my $dbh;
315     my $sth;
316     my $query;
317     my $version;
318     my $qw_clname;
319     my @cluster;
320
321     $dsn = "DBI:Pg:$conninfo};";
322
323     eval {
324         $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
325         $qw_clname = $dbh->quote_identifier("_" . $clname);
326
327         $query = "SELECT $qw_clname.getModuleVersion()";
328         $sth = $dbh->prepare($query);
329         $sth->execute();
330         ($version) = $sth->fetchrow; 
331         $sth->finish;
332
333         $query = "WITH x AS (
334                 SELECT a.no_id, 
335                     a.no_comment, 
336                     COALESCE(b.sub_provider, 0) AS no_prov, 
337                     NULLIF(array_to_string(array(SELECT set_id FROM $qw_clname.sl_set WHERE set_origin = a.no_id" .
338                     ($clsets ne "all" ? " AND set_id IN (" . substr('?, ' x scalar(split(',', $clsets)), 0, -2) . ")" : "") 
339                     . " ORDER BY set_id), ','), '') AS origin_sets,
340                     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,
341                     string_agg(CASE WHEN b.sub_receiver = a.no_id AND b.sub_forward AND b.sub_active" .
342                     ($clsets ne "all" ? " AND b.sub_set IN (" . substr('?, ' x scalar(split(',', $clsets)), 0, -2) . ")" : "") 
343                     . " THEN b.sub_set::text END, ',' ORDER BY b.sub_set) AS prov_sets,
344                     COALESCE(c.pa_conninfo,(SELECT pa_conninfo FROM $qw_clname.sl_path WHERE pa_server = $qw_clname.getlocalnodeid(?) LIMIT 1)) AS no_conninfo
345                 FROM $qw_clname.sl_node a
346                 LEFT JOIN $qw_clname.sl_subscribe b ON a.no_id = b.sub_receiver AND b.sub_set <> 999 
347                 LEFT JOIN $qw_clname.sl_path c ON c.pa_server = a.no_id AND c.pa_client = $qw_clname.getlocalnodeid(?)
348                 LEFT JOIN $qw_clname.sl_set d ON d.set_origin = a.no_id
349                 GROUP BY b.sub_provider, a.no_id, a.no_comment, c.pa_conninfo, a.no_active
350                 ORDER BY (COALESCE(b.sub_provider, 0) = 0) DESC, a.no_id ASC
351                 ), z AS (
352                 SELECT *,  
353                     CASE WHEN x.no_conninfo ilike '%dbname=%' THEN(regexp_matches(x.no_conninfo, E'dbname=(.+?)\\\\M', 'ig'))[1] END AS database,
354                     CASE WHEN x.no_conninfo ilike '%host=%' THEN(regexp_matches(x.no_conninfo, E'host=(.+?)(?=\\\\s|\$)', 'ig'))[1] END AS host,
355                     CASE WHEN x.no_conninfo ilike '%port=%' THEN(regexp_matches(x.no_conninfo, E'port=(.+?)\\\\M', 'ig'))[1] ELSE '5432' END AS port
356                 FROM x 
357                 )
358                 SELECT * FROM z 
359                 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";
360
361         if ($g_debug) { 
362             printLogLn($g_logfile, "DEBUG: " . $query);
363         }
364
365         $sth = $dbh->prepare($query);
366
367         if ($clsets ne "all") {
368             for (0..1) { 
369                 foreach my $param (split(",", $clsets)) {
370                     $sth->bind_param($param_on, $param);
371                     $param_on++;
372                 } 
373             }
374         }
375         $sth->bind_param($param_on, "_" . $clname);
376         $param_on++;
377         $sth->bind_param($param_on, "_" . $clname);
378         $param_on++;
379         $sth->bind_param($param_on, (isInet($addr) ? $addr : '255.255.255.255'));
380         $sth->execute();
381
382         while (my @node = $sth->fetchrow) {
383             push(@cluster,  \@node);
384         }
385
386         $sth->finish;
387         $dbh->disconnect();
388     };
389     if ($@) { 
390         printLogLn($g_logfile, "ERROR: Failed to execute query against Postgres server: $@");
391     }
392
393     return @cluster;
394 }
395
396 sub getConfig {
397     my @fields;
398     my $success = false;
399     my $infile = shift;
400     my $value;
401
402     if (open(CFGFILE, "<", $infile)) {
403         foreach (<CFGFILE>) {
404             chomp $_;
405             for ($_) {
406                 s/\r//;
407                 #s/\#.*//;
408                 s/#(?=(?:(?:[^']|[^"]*+'){2})*+[^']|[^"]*+\z).*//;
409             } 
410             if (length(trim($_))) {
411                 @fields = split('=', $_, 2);
412                 $value = qtrim(trim($fields[1]));
413                 given(lc($fields[0])) {
414                     when(/\bdebug\b/i) {
415                         $g_debug = checkBoolean($value);
416                     }
417                     when(/\bpid_file\b/i) {
418                         $g_pidfile = $value;
419                     }
420                     when(/\blog_file\b/i) {
421                         $g_logfile = $value;
422                     }
423                     when(/\bslony_user\b/i) {
424                         $g_user = $value;
425                     }
426                     when(/\bslony_pass\b/i) {
427                         $g_pass = $value;
428                     }
429                     when(/\bslony_cluster_name\b/i) {
430                         $g_clname = $value;
431                     }
432                     when(/\bslony_sets_to_follow\b/i) {
433                         $g_clsets = $value;
434                     }
435                     when(/\bserver_conninfo\b/i) {
436                         push(@g_conninfos, $value);
437                     }
438                     when(/\bfollower_poll_interval\b/i) {
439                         $g_poll_interval = checkInteger($value);
440                     }
441                     when(/\bstatus_file\b/i) {
442                         $g_status_file = $value;
443                     } 
444                     when(/\bpool_conf_template\b/i) {
445                         $g_conf_template = $value;
446                     } 
447                     when(/\bpool_conf_target\b/i) {
448                         $g_conf_target = $value;
449                     } 
450                     when(/\bpool_reload_command\b/i) {
451                         $g_reload_command = $value;
452                     } 
453                     when(/\bpool_mode\b/i) {
454                         $g_mode = lc($value);
455                     } 
456                     when(/\bpool_all_databases\b/i) {
457                         $g_all_databases = checkBoolean($value);
458                     }
459                 }  
460             }
461         }
462         close (CFGFILE);
463         if (defined($g_user) && (scalar(@g_conninfos) > 0)) {
464            $success = true;
465         }
466         # Replace %mode and %clname here for actual value
467         for ($g_pidfile, $g_logfile, $g_status_file, $g_conf_template, $g_conf_target, $g_reload_command) {
468             s/\%mode/$g_mode/g;
469             s/\%clname/$g_clname/g;
470         }
471
472
473     }
474     else {
475         printLogLn($g_logfile, "ERROR: Could not read configuration from '$infile'");
476     }
477     return $success;
478 }
479
480 sub writePID {
481     my $pidfile = shift;
482     my $success = true;
483
484     eval {
485         open (PIDFILE, ">", $pidfile);
486         print PIDFILE $$;
487         close (PIDFILE);
488         if ($g_debug) {
489             printLogLn($g_logfile, "DEBUG: Created PID file '$pidfile' for process $$");
490         }
491     };
492     if ($@) {
493         printLogLn($g_logfile, "ERROR: unable to write pidfile at '$pidfile' DETAIL $!");       
494         $success = false;
495     }
496     return $success;
497 }
498
499 sub removePID {
500     my $pidfile = shift;
501     my $success = true;
502
503     eval {
504         if (-f $pidfile) {
505             unlink $pidfile;
506             if ($g_debug) {
507                 printLogLn($g_logfile, "DEBUG: Removed PID file '$pidfile'");
508             }
509         }
510         elsif ($g_debug){
511             printLogLn($g_logfile, "DEBUG: PID file '$pidfile' never existed to be removed");
512         } 
513     };
514     if ($@) {
515         printLogLn($g_logfile, "ERROR: unable to remove pidfile at '$pidfile' DETAIL $!");       
516         $success = false;
517     }
518     return $success
519 }
520
521 sub checkBoolean {
522     my $text = shift;
523     my $value = undef;
524     if ( grep /^$text$/i, ("y","yes","t","true","on") ) {
525         $value = true;
526     }
527     elsif ( grep /^$text$/i, ("n","no","f","false","off") ) {
528         $value = false;
529     }
530     return $value;
531 }
532
533 sub checkInteger {
534     my $integer = shift;
535     my $value = undef;
536
537     if (($integer * 1) eq $integer) {
538         $value = int($integer);
539     }
540     return $value;
541 }
542
543 sub checkProvidesAllSets { 
544     my ($originSets, $providerSets) = @_;
545     my %test_hash;
546
547     undef @test_hash{@$originSets};       # add a hash key for each element of @$originSets
548     delete @test_hash{@$providerSets};    # remove all keys for elements of @$providerSets
549
550     return !%test_hash;              # return false if any keys are left in the hash
551 }
552
553 sub isInet {
554     my $address = shift;
555     my $success = true;
556
557     my(@octets) = $address =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
558     if (@octets == 4) {
559         foreach (@octets) {
560             unless ($_ <= 255) {
561                 $success = false;
562             }
563         }
564     }
565     else {
566         $success = false;
567     }
568
569     return $success;
570 }
571
572 sub qtrim {
573     my $string = shift;
574     $string =~ s/^('|")+//;
575     $string =~ s/('|")+$//;
576     return $string;
577 }
578
579 sub trim {
580     my $string = shift;
581     $string =~ s/^\s+//;
582     $string =~ s/\s+$//;
583     return $string;
584 }
585
586 sub getRuntime {
587     my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
588     my $time = sprintf ("%02d:%02d:%02d on %02d/%02d/%04d", $hour, $min, $sec, $day, $month+1, $year+1900);
589     return $time;
590 }
591
592 sub printLog {
593     my $logfile = shift;
594     my $message = shift;
595
596     print $message;
597
598     if (open(LOGFILE, ">>", $logfile)) {
599         print LOGFILE getRuntime() . " " . $message;
600         close (LOGFILE);
601     }
602     else {
603         printLn("ERROR: Unable to write to logfile $logfile");
604     }
605 }
606
607 sub printLogLn {
608     printLog ($_[0], $_[1] . $/);
609 }
610
611 sub printLn {
612     print ((@_ ? join($/, @_) : $_), $/);
613 }