forked from bucardo/bucardo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bucardo.pm
5691 lines (4895 loc) · 179 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
#!/usr/local/bin/perl -- -*-cperl-*-
## The main Bucardo program
##
## Copyright 2006-2009 Greg Sabino Mullane <greg@endpoint.com>
package Bucardo;
use 5.008003;
use strict;
use warnings;
our $VERSION = '3.2.7';
## Begin Moose classes
{
package BCdatabase; ## "db" table
use Moose;
my @req1 = (qw(name dbname dbuser));
my @req2 = (qw());
my @opt1 = (qw(dbhost dbpass dbconn dbservice pgpass status));
my @opt2 = (qw(dbport sourcelimit targetlimit));
for my $req (@req1) { has $req => ( is => 'rw', isa => 'Str', required => 1 ); }
for my $req (@req2) { has $req => ( is => 'rw', isa => 'Int', required => 1 ); }
for my $opt (@opt1) { has $opt => ( is => 'rw', isa => 'Str', required => 0 ); }
for my $opt (@opt2) { has $opt => ( is => 'rw', isa => 'Int', required => 0 ); }
has 'id' => ( is => 'ro', isa => 'Int' );
has 'cols' => ( is => 'ro', isa => 'ArrayRef', default => sub { [@req1,@req2,@opt1,@opt2] },);
}
{
package BCdbgroup;
use Moose;
my @req1 = (qw(name db));
my @req2 = (qw());
for my $req (@req1) { has $req => ( is => 'rw', isa => 'Str', required => 1 ); }
for my $req (@req2) { has $req => ( is => 'rw', isa => 'Int', required => 1 ); }
has 'id' => ( is => 'ro', isa => 'Int' );
has 'cols' => ( is => 'ro', isa => 'ArrayRef', default => sub { [@req1,@req2] },);
}
{
package BCgoat;
use Moose;
my @req1 = (qw(tablename db));
my @req2 = (qw());
my @opt1 = (qw(schemaname has_delta pkey ghost customselect strict_checking));
push @opt1, (qw(standard_conflict pkeytype ping analyze_after_copy makedelta rebuild_index));
my @opt2 = (qw());
for my $req (@req1) { has $req => ( is => 'rw', isa => 'Str', required => 1 ); }
for my $req (@req2) { has $req => ( is => 'rw', isa => 'Int', required => 1 ); }
for my $opt (@opt1) { has $opt => ( is => 'rw', isa => 'Str', required => 0 ); }
for my $opt (@opt2) { has $opt => ( is => 'rw', isa => 'Int', required => 0 ); }
has 'id' => ( is => 'ro', isa => 'Int' );
has 'cols' => ( is => 'ro', isa => 'ArrayRef', default => sub { [@req1,@req2,@opt1,@opt2] },);
}
{
package BCherd;
use Moose;
has 'goat' => ( is => 'rw', isa => 'Any', required => 1 );
has 'name' => ( is => 'rw', isa => 'Str', required => 1 );
has 'priority' => ( is => 'rw', isa => 'Int', required => 0 );
}
{
package BCsync;
use Moose;
my @req1 = (qw(name source));
my @req2 = (qw());
my @opt1 = (qw(synctype copytype deletemethod copyrows copyextra stayalive strict_checking ));
push @opt1, (qw(checktime status limitdbs precommand postcommand txnmode ping ));
push @opt1, (qw(targetdb targetgroup kidtime kidsalive do_listen ));
push @opt1, (qw(usecustomselect makedelta rebuild_index analyze_after_copy track_rates ));
my @opt2 = (qw());
for my $req (@req1) { has $req => ( is => 'rw', isa => 'Str', required => 1 ); }
for my $req (@req2) { has $req => ( is => 'rw', isa => 'Int', required => 1 ); }
for my $opt (@opt1) { has $opt => ( is => 'rw', isa => 'Str', required => 0 ); }
for my $opt (@opt2) { has $opt => ( is => 'rw', isa => 'Int', required => 0 ); }
has 'cols' => ( is => 'ro', isa => 'ArrayRef', default => sub { [@req1,@req2,@opt1,@opt2] },);
## These should not be set by us:
for my $opt (qw(id priority)) {
has $opt => ( is => 'ro', isa => 'Str', required => 0 );
}
}
{
package BCcustomcode;
use Moose;
my @req1 = (qw(name whenrun src_code));
my @req2 = (qw());
my @opt1 = (qw(about getdbh getrows ));
push @opt1, (qw(goat sync active priority ));
my @opt2 = (qw());
for my $req (@req1) { has $req => ( is => 'rw', isa => 'Str', required => 1 ); }
for my $req (@req2) { has $req => ( is => 'rw', isa => 'Int', required => 1 ); }
for my $opt (@opt1) { has $opt => ( is => 'rw', isa => 'Str', required => 0 ); }
for my $opt (@opt2) { has $opt => ( is => 'rw', isa => 'Int', required => 0 ); }
has 'cols' => ( is => 'ro', isa => 'ArrayRef', default => sub { [@req1,@req2,@opt1,@opt2] },);
## These should not be set by us:
for my $opt (qw(id priority)) {
has $opt => ( is => 'ro', isa => 'Str', required => 0 );
}
}
## Moose is a little messy, so we need this for now.
## Known problem: future versions of Moose will fix this.
$SIG{__DIE__} = sub {
my $line = (caller)[2];
(my $err = shift) =~ s{(.+?) at /\S+/Meta/Attribute.+}{$1}so;
##Temporary extra:
$err =~ s/(.+?)\n.+/$1/so if $err =~ /^\w/ and $err !~ /\$VAR1/o;
die "Line $line: $err\n";
};
## Begin main Bucardo object
package Bucardo;
use sigtrap qw( die normal-signals );
use Moose;
use Moose::Util::TypeConstraints;
use Time::HiRes 'sleep';
use DBI 1.51;
use DBD::Pg 2.0 ':pg_types';
my $DEFAULT = $DBD::Pg::DBDPG_DEFAULT;
use Mail::Sendmail;
use Sys::Hostname;
use IO::Handle;
use Data::Dumper;
$Data::Dumper::Varname = 'BUCARDO';
$Data::Dumper::Indent = 1;
use Getopt::Long;
use Config;
use Sys::Syslog;
use DBIx::Safe '1.2.4';
use vars qw($SQL %SQL $sth %sth $bdb $count $info);
my $x = 0;
my %signumber;
for (split(' ', $Config{sig_name})) {
$signumber{$_} = $x++;
}
*STDOUT->autoflush(1);
*STDERR->autoflush(1);
my $DEBUG = 0;
my $VERBOSE = 1;
my $QUIET = 0;
my $HELP = 0;
## Where our debug files live
my $DEBUGDIR = './tmp';
## Specify exactly what database handles are allowed to do within custom code
## Strict: inside the main txn
my %dbix = (
source => {
strict => {
allow_command => 'SELECT INSERT UPDATE DELETE',
allow_attribute => '',
allow_regex => '', ## Must be qr{} if not empty
deny_regex => ''
},
notstrict => {
allow_command => 'SELECT INSERT UPDATE DELETE COMMIT ROLLBACK SET pg_savepoint pg_release pg_rollback_to NOTIFY',
allow_attribute => 'RaiseError PrintError',
allow_regex => [qr{CREATE TEMP TABLE},qr{CREATE(?: UNIQUE)? INDEX}],
deny_regex => ''
},
},
target => {
strict => {
allow_command => 'SELECT INSERT UPDATE DELETE',
allow_attribute => '',
allow_regex => '', ## Must be qr{} if not empty
deny_regex => ''
},
notstrict => {
allow_command => 'SELECT INSERT UPDATE DELETE COMMIT ROLLBACK SET pg_savepoint pg_release pg_rollback_to NOTIFY',
allow_attribute => 'RaiseError PrintError',
allow_regex => [qr{CREATE TEMP TABLE}],
deny_regex => ''
},
}
);
## Optional cleanup for the pidfiles
## The string PIDFILE will be replaced with the actual name
my $PIDCLEANUP = "/bin/chgrp bucardo PIDFILE";
$PIDCLEANUP = '';
## Save a copy of emails to a file? (override with $ENV{BUCARDO_SENDMAIL_FILE})
my $SENDMAIL_FILE = ""; ## "./bucardo.sendmail.log";
## How long to sleep when adding back an aborted sync?
my $KIDABORTSLEEP = 1.0;
my $hostname = hostname;
my $shorthost = $hostname;
$shorthost =~ s/^(.+?)\..*/$1/;
our %config;
our %config_about;
##
## BEGIN MOOSENESS
##
has 'created' => ( is => 'ro', isa => 'Str', default => scalar localtime );
has 'ppid' => ( is => 'ro', isa => 'Int', default => $$ );
has 'verbose' => ( is => 'rw', isa => 'Int', default => 0 );
has 'debugsyslog' => ( is => 'rw', isa => 'Int', default => 1 );
has 'debugdir' => ( is => 'rw', isa => 'Str', default => './tmp' );
has 'debugfile' => ( is => 'rw', isa => 'Int', default => 0 );
has 'debugfilesep' => ( is => 'rw', isa => 'Int', default => 0 );
has 'debugname' => ( is => 'rw', isa => 'Str', default => '' );
has 'cleandebugs' => ( is => 'rw', isa => 'Int', default => 0 );
has 'debugstderr' => ( is => 'rw', isa => 'Int', default => 0 );
has 'debugstdout' => ( is => 'rw', isa => 'Int', default => 0 );
has 'dryrun' => ( is => 'rw', isa => 'Int', default => 0 );
has 'bcquiet' => ( is => 'rw', isa => 'Int', default => 0 );
has 'sendmail' => ( is => 'rw', isa => 'Int', default => 1 );
has 'extraname' => ( is => 'rw', isa => 'Str', default => '' );
has 'version' => ( is => 'ro', isa => 'Str', default => $VERSION );
has 'masterdbh' => ( is => 'ro' );
sub BUILD {
my ($self, $params) = @_;
if ($self->{debugdir}) {
$DEBUGDIR = $self->{debugdir};
}
if ($self->{cleandebugs}) {
system(qq{/bin/rm -f $DEBUGDIR/log.bucardo.*});
}
$self->{logprefix} = "BC! ";
$SIG{CHLD} = 'IGNORE'; ## Zombie stopper
if (exists $ENV{BUCARDO_DRYRUN}) {
$self->{dryrun} = 1;
print STDERR "** DRYRUN - Syncs will not be commited! **\n";
}
if ($self->{extraname}) {
$self->{extraname} = " ($self->{extraname})";
}
$self->{masterdbh} = $self->connect_database();
## Load in the configuration information
$self->reload_config_database();
if ($self->{debugsyslog}) {
openlog 'Bucardo', "pid nowait", $config{syslog_facility};
}
$self->{pidfile} = "$config{piddir}/$config{pidfile}";
$self->{stopfile} = "$config{piddir}/$config{stopfile}";
return;
}
has 'dbname' => ( is => 'rw', isa => 'Str', required => 1 );
has 'dbuser' => ( is => 'rw', isa => 'Str', required => 1 );
has 'dbpass' => ( is => 'rw', isa => 'Str', required => 0, default => '' );
has 'dbhost' => ( is => 'rw', isa => 'Str', required => 0, default => '' );
has 'dbport' => ( is => 'rw', isa => 'Str', required => 0, default => '' );
has 'dbconn' => ( is => 'rw', isa => 'Str', required => 0, default => '' );
has 'database' => ( is => 'rw', isa => 'HashRef' );
after 'database' => sub {
my ($self,$arg) = @_;
return if ! defined $arg;
my $db = BCdatabase->new($arg);
$self->{database}{id} = $self->addtable($db, "db");
## We may want to assign it immediately to a group
if (exists $arg->{dbgroup}) {
$self->dbgroup({db => $arg->{name}, name => $arg->{dbgroup}, priority => $arg->{priority}||0 });
}
return;
};
has 'dbgroup' => ( is => 'rw', isa => 'HashRef' );
after 'dbgroup' => sub {
my ($self,$arg) = @_;
return if ! defined $arg;
my $group = BCdbgroup->new($arg);
$self->make_dbgroup($arg->{name});
## If we also got a database, add it to the group
if (defined $arg->{db}) {
## Does it exist?
my $db = $self->get_db($arg->{db});
my $maindbh = $self->{masterdbh};
my $pri = $arg->{priority} || 0;
$arg->{db} =~ s/\'/''/go;
$arg->{name} =~ s/\'/''/go;
$SQL = qq{INSERT INTO bucardo.dbmap (db, dbgroup, priority)}.
qq{ VALUES ('$arg->{db}','$arg->{name}', $pri)};
$maindbh->do($SQL);
$maindbh->commit();
}
return;
};
has 'goat' => ( is => 'rw', isa => 'HashRef' );
after 'goat' => sub {
my ($self,$arg) = @_;
return if ! defined $arg;
my $goat = BCgoat->new($arg);
my $goatid = $self->addtable($goat, "goat")
or die "No id returned from addtable inside 'goat'\n";
return unless $arg->{herd};
## Add this goat to a herd
$arg->{name} = $arg->{herd};
$arg->{goat} = $goatid;
$self->herd($arg);
return;
};
sub addtable {
my ($self,$arg,$type) = @_;
return if ! defined $arg or ! ref $arg;
my @vals = grep { defined $arg->{$_} } @{$arg->cols};
my $flatargs = join "," => @vals;
my $qs = join "," => map { '?' } @vals;
my $maindbh = $self->{masterdbh};
$SQL = "INSERT INTO bucardo.$type($flatargs) VALUES ($qs)";
$sth = $maindbh->prepare($SQL) or die "Could not add a table: $!";
my $args = [map { $arg->{$_} } @vals];
$sth->execute(@$args);
$maindbh->commit();
return if $type ne 'goat';
return $self->{$type}{id} = $maindbh->selectall_arrayref("SELECT pg_catalog.lastval()")->[0][0];
}
has 'herd' => ( is => 'rw', isa => 'HashRef' );
after 'herd' => sub {
my ($self,$arg) = @_;
return if ! defined $arg;
my $herd = BCherd->new($arg);
my $goatid = $self->find_goat($herd->goat,$arg->{db});
$self->make_herd($herd->name);
my $maindbh = $self->{masterdbh};
my $pri = $arg->{priority} || 0;
my $SQL = "INSERT INTO bucardo.herdmap(goat,herd,priority) VALUES ($goatid,?,$pri)";
$sth = $maindbh->prepare($SQL);
$sth->execute($herd->name);
$maindbh->commit();
return;
};
has 'sync' => ( is => 'rw', isa => 'HashRef' );
after 'sync' => sub {
my ($self,$arg) = @_;
return if ! defined $arg;
my $sync = BCsync->new($arg);
## Make sure these are valid targets
$self->make_dbgroup($sync->targetgroup);
$self->make_herd($sync->source);
$self->{sync}{id} = $self->addtable($sync, "sync");
};
has 'customcode' => ( is => 'rw', isa => 'HashRef' );
after 'customcode' => sub {
## Add an entry to the customcode table
## To add a new entry to customcode:
## mandatory args: name, whenrun, src_code
## optional args: about, getdbh, getrows
my ($self,$arg) = @_;
defined $arg and ref $arg eq 'HASH' or die qq{First argument must be a hashref\n};
my $dbh = $self->{masterdbh};
$dbh->rollback();
## Check if we are doing a mapping
if (defined $arg->{id}) {
my $id = $arg->{id};
$id =~ /^\d+$/ or die qq{Argument "id" must be a number\n};
my $sync = (defined $arg->{sync} and length $arg->{sync}) ? $arg->{sync} : '';
my $goat = (defined $arg->{goat} and length $arg->{goat}) ? $arg->{goat} : '';
if (!length $sync and !length $goat) {
die qq{Must pass in either a sync or goat argument\n};
}
## Is this a valid code?
$SQL = "SELECT 1 FROM customcode WHERE id = $id";
$count = $dbh->selectall_arrayref($SQL);
defined $count->[0] or die qq{Code number $id does not exist\n};
## Is this a valid sync?
if (length $sync) {
$SQL = "SELECT 1 FROM sync WHERE name = ?";
$sth = $dbh->prepare($SQL);
$count = $sth->execute($sync);
$sth->finish();
$count==1 or die qq{That sync does not exist\n};
}
else {
## Is this a valid goat?
$goat =~ /^\d+$/ or die qq{Invalid goat\n};
$SQL = "SELECT 1 FROM goat WHERE id = ?";
$sth = $dbh->prepare($SQL);
$count = $sth->execute($goat);
$sth->finish();
$count==1 or die qq{That goat does not exist\n};
}
$SQL = "INSERT INTO customcode_map(code,sync,goat,active,priority) VALUES (?,?,?,?,?)";
$sth = $dbh->prepare($SQL);
$sth->execute(map { (defined $_ and length $_) ? $_ : $DEFAULT }
@$arg{qw/ id sync goat active priority /});
$dbh->commit();
return 1;
}
my $code = BCcustomcode->new($arg);
## Add this to the database
$SQL = "INSERT INTO customcode(name,about,whenrun,getdbh,getrows,src_code) VALUES (?,?,?,?,?,?)";
$sth = $dbh->prepare($SQL);
$sth->execute(map { defined $_ ? $_ : $DEFAULT } @$arg{qw/ name about whenrun getdbh getrows src_code /});
$arg->{id} = $dbh->selectall_arrayref("SELECT currval('customcode_id_seq')")->[0][0];
## Did they specify a sync or a goat?
if (defined $arg->{goat} or defined $arg->{sync}) {
$SQL = "INSERT INTO customcode_map(code,sync,goat,active,priority) VALUES (?,?,?,?,?)";
$sth = $dbh->prepare($SQL);
$sth->execute(map { defined $_ ? $_ : $DEFAULT } @$arg{qw / id sync goat active priority /});
}
$dbh->commit();
return $arg->{id};
}; ## end 'after' customcode
sub remove_customcode {
my ($self,$arg) = @_;
defined $arg and ref $arg eq 'HASH' or die qq{Argument must be a hashref\n};
my $id = (exists $arg->{id} and length $arg->{id}) ? $arg->{id} : '';
my $name = (exists $arg->{name} and length $arg->{name}) ? $arg->{name} : '';
my $code = (exists $arg->{code} and length $arg->{code}) ? $arg->{code} : '';
if (!length $id and !length $name and !length $code) {
die qq{Did not find required argument\n};
}
my $dbh = $self->{masterdbh};
if (length $code) {
$code =~ /^\d+$/ or die qq{Argument 'code' is not numeric\n};
my $sync = (exists $arg->{sync} and length $arg->{sync}) ? $arg->{sync} : '';
my $goat = (exists $arg->{goat} and length $arg->{goat}) ? $arg->{goat} : '';
if (!length $sync and !length $goat) {
die qq{Did not find required argument sync or goat\n};
}
if (length $goat) {
$goat =~ /^\d+$/ or die qq{Argument goat is not numeric\n};
$SQL = "DELETE FROM customcode_map WHERE code=? AND goat=?";
$sth = $dbh->prepare($SQL);
$count = $sth->execute($code,$goat);
}
else {
$SQL = "DELETE FROM customcode_map WHERE code=? AND sync=?";
$sth = $dbh->prepare($SQL);
$count = $sth->execute($code,$sync);
}
}
elsif (length $id) {
$id =~ /^\d+$/ or die qq{Argument 'id' is not numeric\n};
$SQL = "DELETE FROM customcode WHERE id = ?";
$sth = $dbh->prepare($SQL);
$count = $sth->execute($id);
}
else {
$SQL = "DELETE FROM customcode WHERE name = ?";
$sth = $dbh->prepare($SQL);
$count = $sth->execute($name);
}
$dbh->commit();
return $count eq '0E0' ? 0 : $count;
} ## end of remove_customcode
## Plural returns the latest list
my %thing =
(
goats => \&get_goats,
herds => \&get_herds,
syncs => \&get_syncs,
dbs => \&get_dbs,
dbgroups => \&get_dbgroups,
);
while (($a,$b) = each %thing) {
has $a => ( is => 'ro', 'isa' => 'HashRef', lazy => 1, default=> $b, );
}
sub make_dbgroup {
## Create a named dbgroup if it does not already exist
my ($self,$dbgname) = @_;
return if ! defined $dbgname;
my $dbgroups = $self->get_dbgroups();
return if exists $dbgroups->{$dbgname};
$self->glog(qq{Creating new dbgroup named "$dbgname"});
my $maindbh = $self->{masterdbh};
$SQL = "INSERT INTO bucardo.dbgroup(name) VALUES (?)";
my $sth = $maindbh->prepare($SQL);
$sth->execute($dbgname);
$maindbh->commit();
return;
} ## end of make_dbgroup
sub make_herd {
## Create a named herd if it does not exist
my ($self,$herdname) = @_;
return if ! defined $herdname;
my $herds = $self->get_herds();
return if exists $herds->{$herdname};
$self->glog(qq{Creating new herd named "$herdname"});
my $maindbh = $self->{masterdbh};
$SQL = "INSERT INTO bucardo.herd(name) VALUES (?)";
my $sth = $maindbh->prepare($SQL);
$sth->execute($herdname);
$maindbh->commit();
return;
} ## end of make_herd
sub find_goat {
## Return a goat id, given an id, a tablename, or a goat object
my ($self,$beast,$dbid) = @_;
my $goats = $self->get_goats();
my $goatid;
if (!defined $beast) {
die "Invalid argument passed to find_goat\n";
}
if (ref $beast eq 'BCgoat') {
$goatid = $beast->id;
}
elsif ($beast =~ /^\d+$/o) { ## TODO: explicitly disallow numeric table names
exists $goats->{$beast} or die qq{Unknown goat id: $beast\n};
$goatid = $beast;
}
elsif (! defined $dbid) {
my @ids = map { $goats->{$_}{id} } grep { $goats->{$_}->{tablename} eq $beast } keys %$goats;
if ($#ids >= 1) {
die qq{More than one table named "$beast" found: please specify a database\n};
}
$goatid = $ids[0];
}
else {
($goatid) =
map { $goats->{$_}{id} }
grep { $goats->{$_}->{tablename} eq $beast and $goats->{$_}{db} eq $dbid }
keys %$goats;
}
if (!defined $goatid) {
die qq{Invalid goat given: "$beast"\n};
}
return $goatid;
} ## end of find_goat
sub reload_config {
my ($self) = @_;
my $masterdbh = $self->{masterdbh};
my $done = 'bucardo_reload_config_finished';
$masterdbh->do("LISTEN $done");
$masterdbh->commit();
$masterdbh->do("NOTIFY bucardo_reload_config") or warn 'NOTIFY failed';
$masterdbh->commit();
my $BAIL = 200;
CONFIG_WAIT: {
while (my $notify = $masterdbh->func('pg_notifies')) {
my ($name, $pid) = @$notify;
last CONFIG_WAIT if $name eq $done;
}
$masterdbh->commit();
sleep(0.1);
die "Waited too long for reload_config to return\n" if --$BAIL < 1;
redo;
}
return;
} ## end of reload_config
sub kick_sync {
my ($self, $arg) = @_;
my $msg;
if (ref $arg ne 'HASH') {
$msg = "Missing or invalid options given to method kick_sync!\n";
}
elsif (!defined $arg->{name} or !length $arg->{name}) {
$msg = qq{A name argument is required for method kick_sync.\n};
}
elsif ($arg->{name} !~ /^[[:alpha:]]\w*$/) {
$msg = qq{A valid name argument (1 letter followed by letters, numbers, or underscores) is required for method kick_sync.\n};
}
if ($msg) {
warn $msg;
$self->glog($msg);
return;
}
my $masterdbh = $self->{masterdbh};
for my $l
(
"bucardo_syncdone_$arg->{name}",
"bucardo_syncerror_$arg->{name}",
) {
if (! $masterdbh->do(qq{LISTEN "$l"})) {
$msg = "Error from kick_sync LISTEN $l\n";
warn $msg;
$self->glog($msg);
return;
}
}
unless ($masterdbh->do(qq{NOTIFY "bucardo_kick_sync_$arg->{name}"})) {
$msg = "Error sending kick_sync NOTIFY bucardo_sync_$arg->{name}\n";
warn $msg;
$self->glog($msg);
return;
}
$masterdbh->commit();
$self->glog("Called kick_sync with args: " . join ' | ' => map { "$_=$arg->{$_}" } keys %$arg);
return unless $arg->{wait};
my $timeout = $arg->{timeout};
my $timeout_error = 'timeout';
{
local $SIG{ALRM} = sub { die $timeout_error };
eval {
$timeout and alarm $timeout;
KICK_SYNC_WAIT: while (1) {
KICK_SYNC_NOTIFY: while (my $notify = $masterdbh->func('pg_notifies')) {
my ($name, $pid) = @$notify;
last KICK_SYNC_WAIT if $name =~ /syncdone/;
if ($name =~ /syncerror/o) {
$msg = "Received an error when trying to kick: perhaps it is not active?\n";
warn $msg;
$self->glog($msg);
return;
}
}
sleep $config{kick_sleep};
$masterdbh->commit();
}
alarm 0 if $timeout;
};
alarm 0 if $timeout;
if ($@) {
if ($@ =~ /\Q$timeout_error/o) {
$msg = qq{Timed out waiting $timeout seconds for sync "$arg->{name}" to complete\n};
}
else {
$msg = qq{Error waiting for sync "$arg->{name}" to complete\n};
}
warn $msg;
$self->glog($msg);
return;
}
}
return 1;
} ## end of kick_sync
sub glog {
return if ! $_[0]->{verbose};
my ($self,$msg,@extra) = @_;
chomp $msg;
if (@extra) {
$msg = sprintf $msg, @extra;
}
my $prefix = $self->{logprefix} || '';
$msg = "$prefix$msg";
my $header = sprintf '%s%s%s',
$config{log_showpid} ? "($$) " : '',
$config{log_showtime}==1 ? ('['.time.'] ')
: $config{log_showtime}==2 ? ('['.scalar gmtime(time).'] ')
: $config{log_showtime}==3 ? ('['.scalar localtime(time).'] ')
: '',
$config{log_showline} ? (sprintf '#%04d ', (caller)[2]) : '';
## Route/tee serious errors to another file
if ($msg =~ /Warning/o) {
## TODO
}
if ($self->{debugsyslog}) {
syslog "info", $msg;
}
if ($self->{debugfile}) {
my $file = "$DEBUGDIR/log.bucardo";
if ($self->{debugname}) {
$file .= ".$self->{debugname}";
}
if ($self->{debugfilesep}) {
$file .= ".$prefix.$$";
}
$file =~ s/ //g;
open my $log, '>>', $file or die qq{Could not create "$file": $!\n};
if (!$self->{debugfilesep}) {
print $log "($$) ";
}
printf $log "%s%s%s\n",
$config{log_showtime}==1 ? ('['.time.'] ')
: $config{log_showtime}==2 ? ('['.scalar gmtime(time).'] ')
: $config{log_showtime}==3 ? ('['.scalar localtime(time).'] ')
: '',
$config{log_showline} ? (sprintf '#%04d ', (caller)[2]) : '',
$msg;
close $log or warn qq{Could not close "$file": $!\n};
}
$self->{debugstderr} and print STDERR "$header $msg\n";
$self->{debugstdout} and print STDOUT "$header $msg\n";
return;
}
sub clog {
## Write something to the conflict log file at config{log_conflict_file}
my ($self,$msg,@extra) = @_;
chomp $msg;
if (@extra) {
$msg = sprintf $msg, @extra;
}
my $cfile = $config{log_conflict_file};
my $clog;
if (! open $clog, '>>', $cfile) {
warn qq{Could not append to file "$cfile": $!};
return;
}
print $clog "$msg\n";
close $clog or warn qq{Could not close "$cfile": $!\n};
return;
}
sub get_config {
## Return current value of a configuration setting
my ($self,$name) = @_;
$name = lc $name;
return $config{$name};
}
sub set_config {
## Set value of a configuration setting
## Returns old value
my ($self,$name,$value) = @_;
$name = lc $name;
my $oldval = $self->get_config($name);
$config{$name} = $value;
return $oldval;
}
sub get_config_about {
## Return current description of a configuration setting
my ($self,$name) = @_;
return $config_about{lc $name};
}
sub set_config_about {
## Set description of a configuration setting
## Returns old value
my ($self,$name,$about) = @_;
my $oldabout = $self->get_config(lc $name);
$config_about{lc $name} = $about;
return $oldabout;
}
sub store_config {
## Put a configuration setting's value and description into the database
my ($self,$name) = @_;
$name = lc $name;
my $maindbh = $self->{masterdbh};
my ($value,$about) = ($config{$name},$config_about{$name});
$SQL = "SELECT count(*) FROM bucardo_config WHERE type=NULL AND setting = ".$maindbh->quote($name);
$count = $maindbh->selectall_arrayref($SQL)->[0][0];
if ($count == 1) {
$SQL = "UPDATE bucardo_config SET value=?, about=? WHERE type=NULL AND setting = ?";
$sth = $maindbh->prepare($SQL);
$sth->execute($value,$about,$name);
}
else {
$SQL = "INSERT INTO bucardo_config(value,about,setting) VALUES (?,?,?)";
$sth = $maindbh->prepare($SQL);
$sth->execute($value,$about,$name);
}
$maindbh->commit();
return;
}
sub get_db {
## Return a BCdatabase object
my ($self,$dbname) = @_;
my $dbs = $self->get_dbs;
if (!exists $dbs->{$dbname}) {
die "No such database: $dbname\n";
}
my $db = BCdatabase->new($dbs->{$dbname});
return $db;
}
sub get_dbs {
my $self = shift;
## Return a hashref of everything in the db table
$SQL = "SELECT * FROM bucardo.db";
$sth = $self->{masterdbh}->prepare($SQL);
$sth->execute();
my $info = $sth->fetchall_hashref('name');
$self->{masterdbh}->commit();
return $info;
} # end of get_dbs
sub get_dbgroups {
my $self = shift;
## Return a hashref of dbgroups
$SQL = qq{
SELECT d.name, m.db, m.priority
FROM bucardo.dbgroup d
LEFT JOIN dbmap m ON (m.dbgroup=d.name)
ORDER BY m.priority ASC, random()
};
my $maindbh = $self->{masterdbh};
$sth = $maindbh->prepare($SQL);
$sth->execute();
my $groups;
for my $x (@{$sth->fetchall_arrayref({})}) {
if (!exists $groups->{$x->{name}}) {
$groups->{$x->{name}}{members} = [];
}
defined $x->{db} and push @{$groups->{$x->{name}}{members}}, $x->{db};
}
$maindbh->commit();
return $groups;
} # end of get_dbgroups
sub get_goats {
my $self = shift;
## Return a hashref of everything in the goat table
$SQL = "SELECT * FROM bucardo.goat";
$sth = $self->{masterdbh}->prepare($SQL);
$sth->execute();
my $info = $sth->fetchall_hashref('id');
$self->{masterdbh}->commit();
return $info;
} # end of get_goats
sub get_herds {
my $self = shift;
## Return a hashref of everything in the herd table
$SQL = "SELECT * FROM bucardo.herd";
$sth = $self->{masterdbh}->prepare($SQL);
$sth->execute();
my $info = $sth->fetchall_hashref('name');
$self->{masterdbh}->commit();
return $info;
} # end of get_herds
sub get_herd {
## Return a hashref for a single herd, with table information
my ($self,$herd) = @_;
$herd or die qq{Must provide a herd\n};
$SQL = qq{
SELECT h.name, g.db, g.tablename, g.schemaname, g.has_delta, g.ghost,
g.standard_conflict, g.pkey, g.qpkey, g.pkeytype
FROM bucardo.herd h
LEFT JOIN bucardo.herdmap m ON (m.herd=h.name)
LEFT JOIN bucardo.goat g ON (m.goat=g.id)
WHERE h.name = ?
};
my $maindbh = $self->{masterdbh};
$sth = $maindbh->prepare($SQL);
$sth->execute($herd);
my $tree;
for my $h (@{$sth->fetchall_arrayref({})}) {
if (! defined $tree) {
$tree = { name => $h->{name}, db => $h->{db} };
}
push @{$tree->{members}},
{
schema => $h->{schemaname},
table => $h->{tablename},
has_delta => $h->{has_delta},
ghost => $h->{ghost},
analyze_after_copy => $h->{analyze_after_copy},
strict_checking => $h->{strict_checking},
standard_conflict => $h->{standard_conflict},
};
}
$maindbh->commit();
return $tree
} # end of get_herd
sub get_syncs {
my $self = shift;
## Return an arrayref of everything in the sync table
$SQL = qq{
SELECT *,
COALESCE(EXTRACT(epoch FROM checktime),0) AS checksecs
FROM bucardo.sync
ORDER BY priority DESC, name DESC
};
$sth = $self->{masterdbh}->prepare($SQL);
$sth->execute();
my $info = $sth->fetchall_hashref("name");
$self->{masterdbh}->commit();
return $info;
} ## end of get_syncs
sub find_goats {
## Given a herd, return an arrayref of goats
my ($self,$herd) = @_;
my $goats = $self->get_goats();
my $maindbh = $self->{masterdbh};