forked from bucardo/bucardo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bucardo.pm
10581 lines (8331 loc) · 390 KB
/
Bucardo.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!perl
# -*-mode:cperl; indent-tabs-mode: nil; cperl-indent-level: 4-*-
## The main Bucardo program
##
## This script should only be called via the 'bucardo' program
##
## Copyright 2006-2023 Greg Sabino Mullane <greg@turnstep.com>
##
## Please visit https://bucardo.org for more information
package Bucardo;
use 5.008003;
use strict;
use warnings;
use utf8;
use open qw( :std :utf8 );
our $VERSION = '5.6.0';
use DBI 1.51; ## How Perl talks to databases
use DBD::Pg 2.0 qw( :async ); ## How Perl talks to Postgres databases
use DBIx::Safe '1.2.4'; ## Filter out what DB calls customcode may use
use sigtrap qw( die normal-signals ); ## Call die() on HUP, INT, PIPE, or TERM
use Config qw( %Config ); ## Used to map signal names
use File::Spec qw( ); ## For portable file operations
use Data::Dumper qw( Dumper ); ## Used to dump information in email alerts
use POSIX qw( strftime strtod ); ## For grabbing the local timezone, and forcing to NV
use Sys::Hostname qw( hostname ); ## Used for host safety check, and debugging/mail sending
use IO::Handle qw( autoflush ); ## Used to prevent stdout/stderr buffering
use Sys::Syslog qw( openlog syslog ); ## In case we are logging via syslog()
use Net::SMTP qw( ); ## Used to send out email alerts
use List::Util qw( first ); ## Better than grep
use MIME::Base64 qw( encode_base64
decode_base64 ); ## For making text versions of bytea primary keys
use Time::HiRes qw( sleep gettimeofday
tv_interval ); ## For better resolution than the built-in sleep
## and for timing of events
## Formatting of Data::Dumper() calls:
$Data::Dumper::Varname = 'BUCARDO';
$Data::Dumper::Indent = 1;
## Common variables we don't want to declare over and over:
use vars qw(%SQL $sth %sth $count $info);
## Logging verbosity control
## See also the 'log_level_number' inside the config hash
use constant {
LOG_WARN => 0, ## Always shown
LOG_TERSE => 1, ## Bare minimum
LOG_NORMAL => 2, ## Normal messages
LOG_VERBOSE => 3, ## Many more details
LOG_DEBUG => 4, ## Firehose: rarely needed
LOG_DEBUG2 => 5, ## Painful level of detail
};
## Map system signal numbers to standard names
## This allows us to say kill $signumber{HUP} => $pid
my $i = 0;
my %signumber;
for (split(' ', $Config{sig_name})) {
$signumber{$_} = $i++;
}
## Prevent buffering of output:
*STDOUT->autoflush(1);
*STDERR->autoflush(1);
## Configuration of DBIx::Safe
## Specify exactly what database handles are allowed to do within custom code
## Here, 'strict' means 'inside the main transaction that Bucardo uses to make changes'
my $strict_allow = 'SELECT INSERT UPDATE DELETE quote quote_identifier';
my $nostrict_allow = "$strict_allow COMMIT ROLLBACK NOTIFY SET pg_savepoint pg_release pg_rollback_to";
my %dbix = (
source => {
strict => {
allow_command => $strict_allow,
allow_attribute => '',
allow_regex => '', ## Must be qr{} if not empty
deny_regex => '',
},
notstrict => {
allow_command => $nostrict_allow,
allow_attribute => 'RaiseError PrintError',
allow_regex => [qr{CREATE TEMP TABLE},qr{CREATE(?: UNIQUE)? INDEX}],
deny_regex => '',
},
},
target => {
strict => {
allow_command => $strict_allow,
allow_attribute => '',
allow_regex => '', ## Must be qr{} if not empty
deny_regex => '',
},
notstrict => {
allow_command => $nostrict_allow,
allow_attribute => 'RaiseError PrintError',
allow_regex => [qr{CREATE TEMP TABLE}],
deny_regex => '',
},
}
);
## Grab our full and shortened host name:
## Used for the host_safety_check as well as for emails
my $hostname = hostname;
my $shorthost = $hostname;
$shorthost =~ s/^(.+?)\..*/$1/;
## Items pulled from bucardo_config and shared everywhere:
our %config;
our %config_about;
## Set a default in case we call glog before we load the configs:
$config{log_level_number} = LOG_NORMAL;
## Sequence columns we care about and how to change them via ALTER:
my @sequence_columns = (
['last_value' => ''],
['start_value' => 'START WITH'],
['increment_by' => 'INCREMENT BY'],
['max_value' => 'MAXVALUE'],
['min_value' => 'MINVALUE'],
['is_cycled' => 'BOOL CYCLE'],
['is_called' => ''],
);
my $sequence_columns = join ',' => map { $_->[0] } @sequence_columns;
## Default statement chunk size in case config does not have it
my $default_statement_chunk_size = 10_000;
## Output messages per language
our %msg = (
'en' => {
'time-day' => q{day},
'time-days' => q{days},
'time-hour' => q{hour},
'time-hours' => q{hours},
'time-minute' => q{minute},
'time-minutes' => q{minutes},
'time-month' => q{month},
'time-months' => q{months},
'time-second' => q{second},
'time-seconds' => q{seconds},
'time-week' => q{week},
'time-weeks' => q{weeks},
'time-year' => q{year},
'time-years' => q{years},
},
'fr' => {
'time-day' => q{jour},
'time-days' => q{jours},
'time-hour' => q{heure},
'time-hours' => q{heures},
'time-minute' => q{minute},
'time-minutes' => q{minutes},
'time-month' => q{mois},
'time-months' => q{mois},
'time-second' => q{seconde},
'time-seconds' => q{secondes},
'time-week' => q{semaine},
'time-weeks' => q{semaines},
'time-year' => q{année},
'time-years' => q{années},
},
'de' => {
'time-day' => q{Tag},
'time-days' => q{Tag},
'time-hour' => q{Stunde},
'time-hours' => q{Stunden},
'time-minute' => q{Minute},
'time-minutes' => q{Minuten},
'time-month' => q{Monat},
'time-months' => q{Monate},
'time-second' => q{Sekunde},
'time-seconds' => q{Sekunden},
'time-week' => q{Woche},
'time-weeks' => q{Woche},
'time-year' => q{Jahr},
'time-years' => q{Jahr},
},
'es' => {
'time-day' => q{día},
'time-days' => q{días},
'time-hour' => q{hora},
'time-hours' => q{horas},
'time-minute' => q{minuto},
'time-minutes' => q{minutos},
'time-month' => q{mes},
'time-months' => q{meses},
'time-second' => q{segundo},
'time-seconds' => q{segundos},
'time-week' => q{semana},
'time-weeks' => q{semanas},
'time-year' => q{año},
'time-years' => q{años},
},
);
## use critic
## Figure out which language to use for output
our $lang = $ENV{LC_ALL} || $ENV{LC_MESSAGES} || $ENV{LANG} || 'en';
$lang = substr($lang,0,2);
##
## Everything else is subroutines
##
sub new {
## Create a new Bucardo object and return it
## Takes a hashref of options as the only argument
my $class = shift;
my $params = shift || {};
## The hash for this object, with default values:
my $self = {
created => scalar localtime,
mcppid => $$,
verbose => 1,
quickstart => 0,
logdest => ['.'],
warning_file => '',
logseparate => 0,
logextension => '',
logclean => 0,
dryrun => 0,
sendmail => 1,
extraname => '',
logprefix => 'BC!',
version => $VERSION,
listening => {},
pidmap => {},
exit_on_nosync => 0,
sqlprefix => "/* Bucardo $VERSION */",
};
## Add any passed-in parameters to our hash:
for (keys %$params) {
$self->{$_} = $params->{$_};
}
## Transform our hash into a genuine 'Bucardo' object:
bless $self, $class;
## Remove any previous log files if requested
if ($self->{logclean} && (my @dirs = grep {
$_ !~ /^(?:std(?:out|err)|none|syslog)/
} @{ $self->{logdest} }) ) {
## If the dir does not exists, silently proceed
for my $dir (@dirs) {
opendir my $dh, $dir or next;
## We look for any files that start with 'log.bucardo' plus another dot
for my $file (grep { /^log\.bucardo\./ } readdir $dh) {
my $fullfile = File::Spec->catfile( $dir => $file );
unlink $fullfile or warn qq{Could not remove "$fullfile": $!\n};
}
closedir $dh or warn qq{Could not closedir "$dir": $!\n};
}
}
## Zombie stopper
$SIG{CHLD} = 'IGNORE';
## Basically, dryrun does a rollback instead of a commit at the final sync step
## This is not 100% safe, if (for example) you have custom code that reaches
## outside the database to do things.
if (exists $ENV{BUCARDO_DRYRUN}) {
$self->{dryrun} = 1;
}
if ($self->{dryrun}) {
$self->glog(q{** DRYRUN - Syncs will not be committed! **}, LOG_WARN);
}
## This gets appended to the process description ($0)
if ($self->{extraname}) {
$self->{extraname} = " ($self->{extraname})";
}
## Connect to the main Bucardo database
$self->{masterdbh} = $self->connect_database();
## Load in the configuration information
$self->reload_config_database();
## Figure out if we are writing emails to a file
$self->{sendmail_file} = $ENV{BUCARDO_EMAIL_DEBUG_FILE} || $config{email_debug_file} || '';
## Where to store our PID:
$self->{pid_file} = File::Spec->catfile( $config{piddir} => 'bucardo.mcp.pid' );
## The file to ask all processes to stop:
$self->{stop_file} = File::Spec->catfile( $config{piddir} => $config{stopfile} );
## Send all log lines starting with "Warning" to a separate file
$self->{warning_file} ||= $config{warning_file};
## Make sure we are running where we are supposed to be
## This prevents items in bucardo.db that reference production
## systems from getting run on QA!
## ...or at least makes sure people have to work a lot harder
## to shoot themselves in the foot.
if (length $config{host_safety_check}) {
my $safe = $config{host_safety_check};
my $osafe = $safe;
my $ok = 0;
## Regular expression
if ($safe =~ s/^~//) {
$ok = 1 if $hostname =~ qr{$safe};
}
## Set of choices
elsif ($safe =~ s/^=//) {
for my $string (split /,/ => $safe) {
if ($hostname eq $string) {
$ok=1;
last;
}
}
}
## Simple string
elsif ($safe eq $hostname) {
$ok = 1;
}
if (! $ok) {
warn qq{Cannot start: configured to only run on "$osafe". This is "$hostname"\n};
warn qq{ This is usually done to prevent a configured Bucardo from running\n};
warn qq{ on the wrong host. Please verify the 'db' settings by doing:\n};
warn qq{bucardo list dbs\n};
warn qq{ Once you are sure the bucardo.db table has the correct values,\n};
warn qq{ you can adjust the 'host_safety_check' value\n};
exit 2;
}
}
return $self;
} ## end of new
sub start_mcp {
## Start the Bucardo daemon. Called by bucardo after setsid()
## Arguments: one
## 1. Arrayref of command-line options.
## Returns: never (exit 0 or exit 1)
my ($self, $opts) = @_;
## Store the original invocation string, then modify it
my $old0 = $0;
## May not work on all platforms, of course, but we're gonna try
$0 = "Bucardo Master Control Program v$VERSION.$self->{extraname}";
## Prefix all lines in the log file with this TLA (until overriden by a forked child)
$self->{logprefix} = 'MCP';
## If the standard pid file [from new()] already exists, cowardly refuse to run
if (-e $self->{pid_file}) {
## Grab the PID from the file if we can for better output
my $extra = '';
## Failing to open is not fatal here, just means no PID shown
my $oldpid;
if (open my $fh, '<', $self->{pid_file}) {
if (<$fh> =~ /(\d+)/) {
$oldpid = $1;
$extra = " (PID=$oldpid)";
}
close $fh or warn qq{Could not close "$self->{pid_file}": $!\n};
}
## Output to the logfile, to STDERR, then exit
if ($oldpid != $$) {
my $msg = qq{File "$self->{pid_file}" already exists$extra: cannot run until it is removed};
$self->glog($msg, LOG_WARN);
warn $msg;
exit 1;
}
}
## We also refuse to run if the global stop file exists
if (-e $self->{stop_file}) {
my $msg = qq{Cannot run while this file exists: "$self->{stop_file}"};
$self->glog($msg, LOG_WARN);
warn $msg;
## Failure to open this file is not fatal
if (open my $fh, '<', $self->{stop_file}) {
## Read in up to 10 lines from the stopfile and output them
while (<$fh>) {
$msg = "Line $.: $_";
$self->glog($msg, LOG_WARN);
warn $msg;
last if $. > 10;
}
close $fh or warn qq{Could not close "$self->{stop_file}": $!\n};
}
exit 1;
}
## We are clear to start. Output a quick hello and version to the logfile
$self->glog("Starting Bucardo version $VERSION", LOG_WARN);
$self->glog("Log level: $config{log_level}", LOG_WARN);
## Close unused file handles.
unless (grep { $_ eq 'stderr' } @{ $self->{logdest} }) {
close STDERR or warn "Could not close STDERR\n";
}
unless (grep { $_ eq 'stdout' } @{ $self->{logdest} }) {
close STDOUT or warn "Could not close STDOUT\n";
}
## Create a new (but very temporary) PID file
## We will overwrite later with a new PID once we do the initial fork
$self->create_mcp_pid_file($old0);
## Send an email message with details about this invocation
if ($self->{sendmail} or $self->{sendmail_file}) {
## Create a pretty Dumped version of the current $self object, with the password elided
## Squirrel away the old password
my $oldpass = $self->{dbpass};
## Set to something else
$self->{dbpass} = '<not shown>';
## Dump the entire object with Data::Dumper (with custom config variables)
my $dump = Dumper $self;
## Put the password back in place
$self->{dbpass} = $oldpass;
## Prepare to send an email letting people know we have started up
my $body = qq{
Master Control Program $$ was started on $hostname
Args: $old0
Version: $VERSION
};
my $subject = qq{Bucardo $VERSION started on $shorthost};
## If someone left a message in the reason file, append it, then delete the file
my $reason = get_reason('delete');
if ($reason) {
$body .= "Reason: $reason\n";
$subject .= " ($reason)";
}
## Strip leading whitespace from the body (from the qq{} above)
$body =~ s/^\s+//gsm;
## Send out the email (if sendmail or sendmail_file is enabled)
$self->send_mail({ body => "$body\n\n$dump", subject => $subject });
}
## Drop the existing database connection, fork, and get a new one
## This self-fork helps ensure our survival
my $disconnect_ok = 0;
eval {
## This connection was set in new()
$self->{masterdbh}->disconnect();
$disconnect_ok = 1;
};
$disconnect_ok or $self->glog("Warning! Disconnect failed $@", LOG_WARN);
my $seeya = fork;
if (! defined $seeya) {
die q{Could not fork mcp!};
}
## Immediately close the child process (one side of the fork)
if ($seeya) {
exit 0;
}
## Now that we've forked, overwrite the PID file with our new value
$self->create_mcp_pid_file($old0);
## Reconnect to the master database
($self->{mcp_backend}, $self->{masterdbh}) = $self->connect_database();
my $masterdbh = $self->{masterdbh};
## Let any listeners know we have gotten this far
## (We do this nice and early for impatient watchdog programs)
$self->db_notify($masterdbh, 'boot', 1);
## Store the function to use to generate clock timestamps
## We greatly prefer clock_timestamp,
## but fallback to timeofday() for 8.1 and older
$self->{mcp_clock_timestamp} =
$masterdbh->{pg_server_version} >= 80200
? 'clock_timestamp()'
: 'timeofday()::timestamptz';
## Start outputting some interesting things to the log
$self->show_db_version_and_time($masterdbh, $self->{mcp_backend}, 'Master DB ');
$self->glog("PID: $$", LOG_WARN);
$self->glog('Postgres library version: ' . $masterdbh->{pg_lib_version}, LOG_WARN);
$self->glog("bucardo: $old0", LOG_WARN);
$self->glog('Bucardo.pm: ' . $INC{'Bucardo.pm'}, LOG_WARN);
$self->glog((sprintf 'OS: %s Perl: %s %vd', $^O, $^X, $^V), LOG_WARN);
## Get an integer version of the DBD::Pg version, for later comparisons
if ($DBD::Pg::VERSION !~ /(\d+)\.(\d+)\.(\d+)/) {
die "Could not parse the DBD::Pg version: was $DBD::Pg::VERSION\n";
}
$self->{dbdpgversion} = int (sprintf '%02d%02d%02d', $1,$2,$3);
$self->glog((sprintf 'DBI version: %s DBD::Pg version: %s (%d) DBIx::Safe version: %s',
$DBI::VERSION,
$DBD::Pg::VERSION,
$self->{dbdpgversion},
$DBIx::Safe::VERSION),
LOG_WARN);
## Attempt to print the git hash to help with debugging if running a dev version
if (-d '.git') {
my $COM = 'git log -1';
my $log = '';
eval { $log = qx{$COM}; };
if ($log =~ /^commit ([a-f0-9]{40}).+Date:\s+(.+?)$/ms) {
$self->glog("Last git commit sha and date: $1 $2", LOG_NORMAL);
}
}
## Store some PIDs for later debugging use
$self->{pidmap}{$$} = 'MCP';
$self->{pidmap}{$self->{mcp_backend}} = 'Bucardo DB';
## Get the maximum key length of the "self" hash for pretty formatting
my $maxlen = 5;
for (keys %$self) {
$maxlen = length($_) if length($_) > $maxlen;
}
## Print each object, aligned, and show 'undef' for undefined values
## Yes, this prints things like HASH(0x8fbfc84), but we're okay with that
$Data::Dumper::Indent = 0;
$Data::Dumper::Terse = 1;
my $objdump = "Bucardo object:\n";
for my $key (sort keys %$self) {
my $value = $key eq 'dbpass' ? '<not shown>' : $self->{$key};
$objdump .= sprintf " %-*s => %s\n", $maxlen, $key,
(defined $value) ?
(ref $value eq 'ARRAY') ? Dumper($value)
: qq{'$value'} : 'undef';
}
$Data::Dumper::Indent = 1;
$Data::Dumper::Terse = 0;
$self->glog($objdump, LOG_TERSE);
## Dump all configuration variables to the log
$self->log_config();
## Any other files we find in the piddir directory should be considered old
## Thus, we can remove them
my $piddir = $config{piddir};
opendir my $dh, $piddir or die qq{Could not opendir "$piddir": $!\n};
## Nothing else should really be in here, but we will limit with a regex anyway
my @pidfiles = grep { /^bucardo.*\.pid$/ } readdir $dh;
closedir $dh or warn qq{Could not closedir "$piddir" $!\n};
## Loop through and remove each file found, making a note in the log
for my $pidfile (sort @pidfiles) {
my $fullfile = File::Spec->catfile( $piddir => $pidfile );
## Do not erase our own file
next if $fullfile eq $self->{pid_file};
## Everything else can get removed
if (-e $fullfile) {
if (unlink $fullfile) {
$self->glog("Warning: removed old pid file $fullfile", LOG_VERBOSE);
}
else {
## This will cause problems, but we will drive on
$self->glog("Warning: failed to remove pid file $fullfile", LOG_TERSE);
}
}
}
## We use a USR2 signal to indicate that the logs should be reopened
local $SIG{USR2} = sub {
$self->glog("Received USR2 from pid $$, who is a $self->{logprefix}", LOG_DEBUG);
## Go through and reopen anything that needs reopening
## For now, that is only plain text files
for my $logdest (sort keys %{$self->{logcodes}}) {
my $loginfo = $self->{logcodes}{$logdest};
next if $loginfo->{type} ne 'textfile';
my $filename = $loginfo->{filename};
## Reopen the same (named) file with a new filehandle
my $newfh;
if (! open $newfh, '>>', $filename) {
$self->glog("Warning! Unable to open new filehandle for $filename", LOG_WARN);
next;
}
## Turn off buffering on this handle
$newfh->autoflush(1);
## Overwrite the old sub and point to the new filehandle
my $oldfh = $loginfo->{filehandle};
$self->glog("Switching to new filehandle for log file $filename", LOG_NORMAL);
$loginfo->{code} = sub { print {$newfh} @_, $/ };
$self->glog("Completed reopen of file $filename", LOG_NORMAL);
## Close the old filehandle, then remove it from our records
close $oldfh or warn "Could not close old filehandle for $filename: $!\n";
$loginfo->{filehandle} = $newfh;
}
}; ## end of handling USR2 signals
## From this point forward, we want to die gracefully
## We setup our own subroutine to catch any die signals
local $SIG{__DIE__} = sub {
## Arguments: one
## 1. The error message
## Returns: never (exit 1 or exec new process)
my $msg = shift;
my $line = (caller)[2];
$self->glog("Warning: Killed (line $line): $msg", LOG_WARN);
## Was this a database problem?
## We can carefully handle certain classes of errors
if ($msg =~ /DBI|DBD/) {
## How many bad databases we found
my $bad = 0;
for my $db (sort keys %{ $self->{sdb} }) { ## need a better name!
if (! exists $self->{sdb}{$db}{dbh} ) {
$self->glog("Database $db has no database handle", LOG_NORMAL);
$bad++;
}
elsif (! $self->{sdb}{$db}{dbh}->ping()) {
$self->glog("Database $db failed ping check", LOG_NORMAL);
$msg = 'Ping failed';
$bad++;
}
}
if ($bad) {
my $changes = $self->check_sync_health();
if ($changes) {
## If we already made a MCP label, go there
## Else fallthrough and assume our bucardo.sync changes stick!
if ($self->{mcp_loop_started}) {
$self->glog('Going to restart the MCP loop, as syncs have changed', LOG_VERBOSE);
die 'We are going to redo the MCP loop'; ## goes to end of mcp main eval
}
}
}
}
## The error message determines if we try to resurrect ourselves or not
my $respawn = (
$msg =~ /DBI connect/ ## From DBI
or $msg =~ /Ping failed/ ## Set below
) ? 1 : 0;
## Sometimes we don't want to respawn at all (e.g. during some tests)
if (! $config{mcp_dbproblem_sleep}) {
$self->glog('Database problem, but will not attempt a respawn due to mcp_dbproblem_sleep=0', LOG_TERSE);
$respawn = 0;
}
## Create some output for the mail message
my $diesubject = "Bucardo MCP $$ was killed";
my $diebody = "MCP $$ was killed: $msg";
## Most times we *do* want to respawn
if ($respawn) {
$self->glog("Database problem, will respawn after a short sleep: $config{mcp_dbproblem_sleep}", LOG_TERSE);
$diebody .= " (will attempt respawn in $config{mcp_dbproblem_sleep} seconds)";
$diesubject .= ' (respawning)';
}
## Callers can prevent an email being sent by setting this before they die
if (! $self->{clean_exit}) {
$self->send_mail({ body => $diebody, subject => $diesubject });
}
## Kill kids, remove pidfile, update tables, etc.
$self->cleanup_mcp("Killed: $msg");
## If we are not respawning, simply exit right now
exit 1 if ! $respawn;
## We will attempt a restart, but sleep a while first to avoid constant restarts
$self->glog("Sleep time: $config{mcp_dbproblem_sleep}", LOG_TERSE);
sleep($config{mcp_dbproblem_sleep});
## Do a quick check for a stopfile
## Bail if the stopfile exists
if (-e $self->{stop_file}) {
$self->glog(qq{Found stopfile "$self->{stop_file}": exiting}, LOG_WARN);
my $message = 'Found stopfile';
## Grab the reason, if it exists, so we can propagate it onward
my $mcpreason = get_reason(0);
if ($mcpreason) {
$message .= ": $mcpreason";
}
## Stop controllers, disconnect, remove PID file, etc.
$self->cleanup_mcp("$message\n");
$self->glog('Exiting', LOG_WARN);
exit 0;
}
## We assume this is bucardo, and that we are in same directory as when called
my $RUNME = $old0;
## Check to see if $RUNME is executable as is, before we assume we're in the same directory
if (! -x $RUNME) {
$RUNME = "./$RUNME" if index ($RUNME,'.') != 0;
}
my $mcpreason = 'Attempting automatic respawn after MCP death';
$self->glog("Respawn attempt: $RUNME @{ $opts } start '$mcpreason'", LOG_TERSE);
## Replace ourselves with a new process running this command
{ exec $RUNME, @{ $opts }, 'start', $mcpreason };
$self->glog("Could not exec $RUNME: $!", LOG_WARN);
}; ## end SIG{__DIE__} handler sub
## This resets listeners, kills kids, and loads/activates syncs
my $active_syncs = $self->reload_mcp();
if (!$active_syncs && $self->{exit_on_nosync}) {
## No syncs means no reason for us to hang around, so we exit
$self->glog('No active syncs were found, so we are exiting', LOG_WARN);
$self->db_notify($masterdbh, 'nosyncs', 1);
$self->cleanup_mcp('No active syncs');
exit 1;
}
## Report which syncs are active
$self->glog("Active syncs: $active_syncs", LOG_TERSE);
## We want to reload everything if someone HUPs us
local $SIG{HUP} = sub {
$self->reload_mcp();
};
## We need KIDs to tell us their PID so we can deregister them
$self->{kidpidlist} = {};
## Let any listeners know we have gotten this far
$self->db_notify($masterdbh, 'started', 1);
## For optimization later on, we need to know which syncs are 'fullcopy'
for my $syncname (keys %{ $self->{sync} }) {
my $s = $self->{sync}{$syncname};
## Skip inactive or paused syncs
next if !$s->{mcp_active} or $s->{paused};
## Walk through each database and check the roles, discarding inactive dbs
my %rolecount;
for my $db (values %{ $s->{db} }) {
next if $db->{status} ne 'active';
$rolecount{$db->{role}}++;
}
## Default to being fullcopy
$s->{fullcopy} = 1;
## We cannot be a fullcopy sync if:
if ($rolecount{'target'} ## there are any target dbs
or $rolecount{'source'} > 1 ## there is more than one source db
or ! $rolecount{'fullcopy'}) { ## there are no fullcopy dbs
$s->{fullcopy} = 0;
}
}
## Because a sync may have gotten a notice while we were down,
## we auto-kick all eligible syncs
## We also need to see if we can prevent the VAC daemon from running,
## if there are no databases with bucardo schemas
$self->{needsvac} = 0;
for my $syncname (keys %{ $self->{sync} }) {
my $s = $self->{sync}{$syncname};
## Default to starting in a non-kicked mode
$s->{kick_on_startup} = 0;
## Skip inactive or paused syncs
next if !$s->{mcp_active} or $s->{paused};
## Skip fullcopy syncs
next if $s->{fullcopy};
## Right now, the vac daemon is only useful for source Postgres databases
## Of course, it is not needed for fullcopy syncs
for my $db (values %{ $s->{db} }) {
if ($db->{status} eq 'active'
and $db->{dbtype} eq 'postgres'
and $db->{role} eq 'source') {
## We need to increment it for any matches in sdb, regardless of which sync initially set it!
$self->{sdb}{ $db->{name} }{needsvac} = 2;
$self->{needsvac} = 1;
}
}
## Skip if autokick is false
next if ! $s->{autokick};
## Kick it!
$s->{kick_on_startup} = 1;
}
## Start the main loop
{
my $value = $self->mcp_main();
redo if $value;
}
return; ## no critic
} ## end of start_mcp
sub create_mcp_pid_file {
## Create a file containing the PID of the current MCP,
## plus a few other details
## Arguments: one
## 1. Message (usually just the original invocation line)
## Returns: undef
my $self = shift;
my $message = shift || '';
open my $pidfh, '>', $self->{pid_file}
or die qq{Cannot write to $self->{pid_file}: $!\n};
## Inside our newly created PID file, print out PID on the first line
## - print how the script was originally invoked on the second line (old $0),
## - print the current time on the third line
my $now = scalar localtime;
print {$pidfh} "$$\n$message\n$now\n";
close $pidfh or warn qq{Could not close "$self->{pid_file}": $!\n};
return;
} ## end of create_mcp_pid_file
sub mcp_main {
## The main MCP process
## Arguments: none
## Returns: undef (but almost always just exits with 0 or 1)
my $self = shift;
my $maindbh = $self->{masterdbh};
my $sync = $self->{sync};
my $SQL;
## Used to gather up and handle any notices received via the listen/notify system
my $notice;
## Used to keep track of the last time we pinged the databases
my $lastpingcheck = 0;
## Keep track of how long since we checked on the VAC daemon
my $lastvaccheck = 0;
$self->glog('Entering main loop', LOG_TERSE);
$self->{mcp_loop_started} = 1;
MCP: {
## We eval the whole loop so we can cleanly redo it if needed
my $mcp_loop_finished = 0;
eval {
## Bail if the stopfile exists
if (-e $self->{stop_file}) {
$self->glog(qq{Found stopfile "$self->{stop_file}": exiting}, LOG_WARN);
my $msg = 'Found stopfile';
## Grab the reason, if it exists, so we can propagate it onward
my $mcpreason = get_reason(0);
if ($mcpreason) {
$msg .= ": $mcpreason";
}
## Stop controllers, disconnect, remove PID file, etc.
$self->cleanup_mcp("$msg\n");
$self->glog('Exiting', LOG_WARN);
exit 0;
}
## Startup the VAC daemon as needed
## May be off via user configuration, or because of no valid databases
if ($config{bucardo_vac} and $self->{needsvac}) {
## Check on it occasionally (different than the running time)
if (time() - $lastvaccheck >= $config{mcp_vactime}) {
## Is it alive? If not, spawn
my $pidfile = "$config{piddir}/bucardo.vac.pid";
if (! -e $pidfile) {
$self->fork_vac();
}
$lastvaccheck = time();
} ## end of time to check vac
} ## end if bucardo_vac
## Every once in a while, make sure our database connections are still there
if (time() - $lastpingcheck >= $config{mcp_pingtime}) {
## This message must have "Ping failed" to match the $respawn above
$maindbh->ping or die qq{Ping failed for main database!\n};
## Check each (pingable) remote database in undefined order
for my $dbname (keys %{ $self->{sdb} }) {
my $d = $self->{sdb}{$dbname};
next if $d->{dbtype} =~ /flat|mongo|redis/o;
my $try_reconnect = 0;
if ($d->{status} eq 'stalled') {
$self->glog("Trying to connect to stalled database $dbname", LOG_VERBOSE);
$try_reconnect = 1;
}
elsif (! $d->{dbh}->ping) {
$self->glog("Ping failed for database $dbname, trying to reconnect", LOG_NORMAL);
}
if ($try_reconnect) {
## Sleep a hair so we don't reloop constantly
sleep 0.5;
undef $d->{backend};
{
local $SIG{__DIE__} = 'IGNORE';
eval {
($d->{backend}, $d->{dbh}) = $self->connect_database($dbname);
};
}
if (defined $d->{backend}) {
$self->show_db_version_and_time($d->{dbh}, $d->{backend}, qq{Database "$dbname" });
$d->{status} = 'active'; ## In case it was stalled
}
else {
$self->glog("Unable to reconnect to database $dbname!", LOG_WARN);
## We may want to throw an exception if this keeps happening
## We may also want to adjust lastpingcheck so we check more often
}
}
}
## Reset our internal counter to 'now'
$lastpingcheck = time();
} ## end of checking database connections
## Add in any messages from the main database and reset the notice hash
## Ignore things we may have sent ourselves
$notice = $self->db_get_notices($maindbh, $self->{mcp_backend});
## Add in any messages from each remote database
for my $dbname (keys %{ $self->{sdb} }) {
my $d = $self->{sdb}{$dbname};
next if $d->{dbtype} ne 'postgres';
next if $d->{status} eq 'stalled';
my $nlist = $self->db_get_notices($d->{dbh});
$d->{dbh}->rollback();
for my $name (keys %{ $nlist } ) {