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+
7 # This script is a command-line utility to monitor Slony-I clusters
8 # and reconfigure pgbouncer to follow replication sets.
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.
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.
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/>.
27 use Getopt::Long qw/GetOptions/;
28 use Digest::MD5 qw/md5 md5_hex md5_base64/;
31 use Time::HiRes qw/usleep/;
32 use sigtrap 'handler' => \&cleanExit, 'HUP', 'INT','ABRT','QUIT','TERM';
33 Getopt::Long::Configure qw/no_ignore_case/;
37 use constant false => 0;
38 use constant true => 1;
40 my $g_usage = 'Pass configuration file: pool_follower.pl -f <configuration_path> [-D] ';
42 my $g_pidfile = "/tmp/pgbouncer_follower_%mode.pid";
43 my $g_logfile = "/tmp/pgbouncer_follower_%mode.log";
44 my $g_poll_interval = 1000;
47 my $g_clname = "replication";
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";
56 my $g_all_databases=false;
57 my ($year, $month, $day, $hour, $min, $sec);
59 my $g_host = hostname;
60 my ($g_addr)=inet_ntoa((gethostbyname(hostname))[4]);
61 my $g_origins_only = false;
63 die $g_usage unless GetOptions(\%opt, 'config_file|f=s', 'daemon|D',) and keys %opt and ! @ARGV;
65 unless (getConfig($opt{config_file})){
66 print ("There was a problem reading the configuration.\n");
70 printLogLn($g_logfile, "DEBUG: Logging to my '$g_logfile'");
71 printLogLn($g_logfile, "\t Watching sets $g_clsets in Slony-I cluster '$g_clname' polling every ${g_poll_interval}ms");
72 printLogLn($g_logfile, "\t Following " . ($g_all_databases ? "all databases" : "replicated database only") . " on an '$g_mode' node for the above replicated sets");
73 printLogLn($g_logfile, "\t Template config '$g_conf_template' Target config '$g_conf_target'");
74 printLogLn($g_logfile, "\t Reload command is '$g_reload_command'");
75 printLogLn($g_logfile, "\t Status stored in '$g_status_file'");
76 printLogLn($g_logfile, "\t Using local address for '$g_host' as '$g_addr'");
77 #printLogLn($g_logfile, "\t '$g_user' as '$g_pass'");
80 if (defined($opt{daemon})) {
81 printLogLn($g_logfile, "pgbouncer_follower starting up");
82 if (writePID($g_pidfile)) {
86 printLogLn($g_logfile, "DEBUG: Sleeping for ${g_poll_interval}ms");
88 usleep($g_poll_interval * 1000);
99 if (defined($opt{daemon})) {
100 printLogLn($g_logfile, "pgbouncer_follower shutting down");
101 removePID($g_pidfile);
109 foreach my $conninfo (@g_conninfos) {
111 @g_cluster = loadCluster($g_clname, $conninfo, $g_user, $g_pass, $g_addr, $g_clsets);
113 printLogLn($g_logfile, "DEBUG: Cluster with " . scalar(@g_cluster) . " nodes read from conninfo: $conninfo");
114 foreach (@g_cluster) {
115 printLogLn($g_logfile, "DEBUG: Node #" . @$_[0] . " DETAIL: " . @$_[1] . " " . @$_[2] . " " . (@$_[3] // "<NONE>") . " " . @$_[4] . " " . (@$_[5] // "<NONE>") . " " . @$_[6] . " " . @$_[7] . " " . @$_[8] . " " . @$_[9] . " " );
120 printLogLn($g_logfile, "ERROR: Failed using conninfo: $conninfo DETAIL: $@");
126 unless (checkCluster($g_status_file)) {
128 printLogLn ($g_logfile, "DEBUG: Cluster status unchanged");
132 printLogLn ($g_logfile, "Cluster status changed");
133 $node_to = generateConfig($g_conf_template, $g_conf_target, $g_mode, $g_all_databases, $g_clsets);
134 if (reloadConfig($g_reload_command)) {
135 printLogLn ($g_logfile, "Pool repointed to node #$node_to");
141 my $reload_command = shift;
143 if(length($reload_command // '')) {
144 printLogLn($g_logfile, "Running '$reload_command'");
146 open(RELOAD, "-|", $reload_command . " 2>&1");
148 printLogLn($g_logfile, $_);
151 printLogLn($g_logfile, "Reload command has been run.");
154 printLogLn($g_logfile, "ERROR: Failed to run reload command DETAIL: $@");
162 my $template = shift;
165 my $all_databases = shift;
176 my $target_port = 5432;
177 my $target_is_origin;
180 printLogLn($g_logfile, "DEBUG: All databases = " . ($g_all_databases ? 'true' : 'false'));
183 if (open(INFILE, "<", $template)) {
184 if (open(OUTFILE, ">", $target)) {
185 print OUTFILE "# Configuration file autogenerated at " . getRuntime() . " from $template\n";
187 if (m/\[databases]/) {
189 # Try and choose a node; we always assign the origin initially regardless of rw/ro status
190 # when in ro mode and if we then find a suitable subscriber we'll reassign to it.
191 foreach my $node (@g_cluster) {
192 if ($clsets ne 'all') {
193 @sets_to_follow = split(',', $clsets);
194 if (defined($node->[3])) {
195 @sets_origin = split(',', $node->[3]);
200 if (defined($node->[5])) {
201 @sets_subscribed = split(',', $node->[5]);
204 undef @sets_subscribed;
208 if (($clsets eq 'all' && defined($node->[3])) || (@sets_to_follow && @sets_origin && checkProvidesAllSets(\@sets_to_follow, \@sets_origin))) {
209 if (defined($node->[8])) {
210 $target_db = $node->[7];
211 $target_host = $node->[8];
212 $target_node_id = $node->[0];
213 $target_sets = $node->[3];
214 $target_is_origin = true;
216 if (defined($node->[9])) {
217 $target_port = $node->[9];
223 elsif (($mode eq "ro") && (($clsets eq 'all') || (@sets_to_follow && @sets_subscribed && checkProvidesAllSets(\@sets_to_follow, \@sets_subscribed)))) {
224 if (defined($node->[8])) {
225 $target_db = $node->[7];
226 $target_host = $node->[8];
227 $target_node_id = $node->[0];
228 $target_sets = ($node->[5] // $node->[3]);
229 $target_is_origin = false;
231 if (defined($node->[9])) {
232 $target_port = $node->[9];
237 if (defined($target_host)) {
238 $_ = "# Configuration for " . ($target_is_origin ? "origin" : "subscriber") . " of sets $target_sets node #$target_node_id $target_host:$target_port\n" . $_;
240 printLogLn ($g_logfile, "DEBUG: Configuration for " . ($target_is_origin ? "origin" : "subscriber") . " of sets $target_sets node #$target_node_id $target_host:$target_port");
242 if ($all_databases) {
243 $_ =~ s/(\[databases\])/$1\n\* = host=$target_host port=$target_port/;
246 $_ =~ s/(\[databases\])/$1\n$target_db = host=$target_host port=$target_port dbname=$target_db/;
250 $_ = "# Could not find any node providing sets $g_clsets in mode $mode\n";
251 printLogLn ($g_logfile, "DEBUG: Could not find any node providing sets $g_clsets in mode $mode");
260 print ("ERROR: Can't open file $target\n");
265 print ("ERROR: Can't open file $template\n");
267 return $target_node_id;
274 my $previous_cluster;
275 foreach (@g_cluster) {
276 if (!$g_origins_only || defined($_->[3])) {
277 $current_cluster = md5_hex(($current_cluster // "") . $_->[0] . $_->[2] . (defined($_->[3]) ? 't' : 'f') . $_->[6]);
279 printLogLn($g_logfile, "DEBUG: Node " . $_->[0] . " detail = " . $_->[2] . (defined($_->[3]) ? 't' : 'f') . $_->[6]);
285 if (open(CLUSTERFILE, "<", $infile)) {
286 $previous_cluster = <CLUSTERFILE>;
290 printLogLn ($g_logfile, "ERROR: Can't open file $infile for reading");
294 unless (-f $infile && ($current_cluster eq $previous_cluster)) {
296 printLogLn($g_logfile, "DEBUG: Writing to status file");
298 if (open(CLUSTERFILE, ">", $infile)) {
299 print CLUSTERFILE $current_cluster;
303 printLogLn ($g_logfile, "ERROR: Can't open file $infile for writing");
307 if ((($previous_cluster // "") ne "") && (($current_cluster // "") ne "") && ($current_cluster ne $previous_cluster)){
316 my $conninfo = shift;
331 $dsn = "DBI:Pg:$conninfo};";
334 $dbh = DBI->connect($dsn, $dbuser, $dbpass, {RaiseError => 1});
335 $qw_clname = $dbh->quote_identifier("_" . $clname);
337 $query = "SELECT $qw_clname.getModuleVersion()";
338 $sth = $dbh->prepare($query);
340 ($version) = $sth->fetchrow;
343 $query = "WITH x AS (
346 COALESCE(b.sub_provider, 0) AS no_prov,
347 NULLIF(array_to_string(array(SELECT set_id FROM $qw_clname.sl_set WHERE set_origin = a.no_id" .
348 ($clsets ne "all" ? " AND set_id IN (" . substr('?, ' x scalar(split(',', $clsets)), 0, -2) . ")" : "")
349 . " ORDER BY set_id), ','), '') AS origin_sets,
350 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,
351 string_agg(CASE WHEN b.sub_receiver = a.no_id AND b.sub_forward AND b.sub_active" .
352 ($clsets ne "all" ? " AND b.sub_set IN (" . substr('?, ' x scalar(split(',', $clsets)), 0, -2) . ")" : "")
353 . " THEN b.sub_set::text END, ',' ORDER BY b.sub_set) AS prov_sets,
354 COALESCE(c.pa_conninfo,(SELECT pa_conninfo FROM $qw_clname.sl_path WHERE pa_server = $qw_clname.getlocalnodeid(?) LIMIT 1)) AS no_conninfo
355 FROM $qw_clname.sl_node a
356 LEFT JOIN $qw_clname.sl_subscribe b ON a.no_id = b.sub_receiver AND b.sub_set <> 999
357 LEFT JOIN $qw_clname.sl_path c ON c.pa_server = a.no_id AND c.pa_client = $qw_clname.getlocalnodeid(?)
358 LEFT JOIN $qw_clname.sl_set d ON d.set_origin = a.no_id
359 GROUP BY b.sub_provider, a.no_id, a.no_comment, c.pa_conninfo, a.no_active
360 ORDER BY (COALESCE(b.sub_provider, 0) = 0) DESC, a.no_id ASC
363 CASE WHEN x.no_conninfo ilike '%dbname=%' THEN(regexp_matches(x.no_conninfo, E'dbname=(.+?)\\\\M', 'ig'))[1] END AS database,
364 CASE WHEN x.no_conninfo ilike '%host=%' THEN(regexp_matches(x.no_conninfo, E'host=(.+?)(?=\\\\s|\$)', 'ig'))[1] END AS host,
365 CASE WHEN x.no_conninfo ilike '%port=%' THEN(regexp_matches(x.no_conninfo, E'port=(.+?)\\\\M', 'ig'))[1] ELSE '5432' END AS port
369 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";
372 printLogLn($g_logfile, "DEBUG: " . $query);
375 $sth = $dbh->prepare($query);
377 if ($clsets ne "all") {
379 foreach my $param (split(",", $clsets)) {
380 $sth->bind_param($param_on, $param);
385 $sth->bind_param($param_on, "_" . $clname);
387 $sth->bind_param($param_on, "_" . $clname);
389 $sth->bind_param($param_on, (isInet($addr) ? $addr : '255.255.255.255'));
392 while (my @node = $sth->fetchrow) {
393 push(@cluster, \@node);
400 printLogLn($g_logfile, "ERROR: Failed to execute query against Postgres server: $@");
412 if (open(CFGFILE, "<", $infile)) {
413 foreach (<CFGFILE>) {
418 s/#(?=(?:(?:[^']|[^"]*+'){2})*+[^']|[^"]*+\z).*//;
420 if (length(trim($_))) {
421 @fields = split('=', $_, 2);
422 $value = qtrim(trim($fields[1]));
423 given(lc($fields[0])) {
425 $g_debug = checkBoolean($value);
427 when(/\bpid_file\b/i) {
430 when(/\blog_file\b/i) {
433 when(/\bslony_user\b/i) {
436 when(/\bslony_pass\b/i) {
439 when(/\bslony_cluster_name\b/i) {
442 when(/\bslony_sets_to_follow\b/i) {
445 when(/\bserver_conninfo\b/i) {
446 push(@g_conninfos, $value);
448 when(/\bfollower_poll_interval\b/i) {
449 $g_poll_interval = checkInteger($value);
451 when(/\bstatus_file\b/i) {
452 $g_status_file = $value;
454 when(/\bpool_conf_template\b/i) {
455 $g_conf_template = $value;
457 when(/\bpool_conf_target\b/i) {
458 $g_conf_target = $value;
460 when(/\bpool_reload_command\b/i) {
461 $g_reload_command = $value;
463 when(/\bpool_mode\b/i) {
464 $g_mode = lc($value);
466 when(/\bpool_all_databases\b/i) {
467 $g_all_databases = checkBoolean($value);
469 when(/\bonly_follow_origins\b/i) {
470 $g_origins_only = checkBoolean($value);
476 if (defined($g_user) && (scalar(@g_conninfos) > 0)) {
479 # Replace %mode and %clname here for actual value
480 for ($g_pidfile, $g_logfile, $g_status_file, $g_conf_template, $g_conf_target, $g_reload_command) {
482 s/\%clname/$g_clname/g;
488 printLogLn($g_logfile, "ERROR: Could not read configuration from '$infile'");
498 open (PIDFILE, ">", $pidfile);
502 printLogLn($g_logfile, "DEBUG: Created PID file '$pidfile' for process $$");
506 printLogLn($g_logfile, "ERROR: unable to write pidfile at '$pidfile' DETAIL $!");
520 printLogLn($g_logfile, "DEBUG: Removed PID file '$pidfile'");
524 printLogLn($g_logfile, "DEBUG: PID file '$pidfile' never existed to be removed");
528 printLogLn($g_logfile, "ERROR: unable to remove pidfile at '$pidfile' DETAIL $!");
537 if ( grep /^$text$/i, ("y","yes","t","true","on") ) {
540 elsif ( grep /^$text$/i, ("n","no","f","false","off") ) {
550 if (($integer * 1) eq $integer) {
551 $value = int($integer);
556 sub checkProvidesAllSets {
557 my ($originSets, $providerSets) = @_;
560 undef @test_hash{@$originSets}; # add a hash key for each element of @$originSets
561 delete @test_hash{@$providerSets}; # remove all keys for elements of @$providerSets
563 return !%test_hash; # return false if any keys are left in the hash
570 my(@octets) = $address =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
587 $string =~ s/^('|")+//;
588 $string =~ s/('|")+$//;
600 my ($year, $month, $day, $hour, $min, $sec) = (localtime(time))[5,4,3,2,1,0];
601 my $time = sprintf ("%02d:%02d:%02d on %02d/%02d/%04d", $hour, $min, $sec, $day, $month+1, $year+1900);
611 if (open(LOGFILE, ">>", $logfile)) {
612 print LOGFILE getRuntime() . " " . $message;
616 printLn("ERROR: Unable to write to logfile $logfile");
621 printLog ($_[0], $_[1] . $/);
625 print ((@_ ? join($/, @_) : $_), $/);