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