-
Notifications
You must be signed in to change notification settings - Fork 55
/
zdba.pl
106 lines (78 loc) · 2.31 KB
/
zdba.pl
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
package main;
use strict;
use warnings;
use forks 'exit' => 'threads_only';
use sigtrap 'handler', \&stop, 'normal-signals';
use FindBin '$Bin';
use File::Spec;
use Log::Log4perl ':easy';
use Log::Any::Adapter;
use lib File::Spec->catfile( $Bin, 'lib' );
use ZDBA;
$ENV{ZDBA_SPLIT_LOGS} = 0;
Log::Any::Adapter->set('Log4perl');
Log::Log4perl::init( File::Spec->catfile( $Bin, 'conf', 'log4perl.conf' ) );
my $running = 1;
my $counter = {};
my $pool = {};
my $zdba = ZDBA->new( config => { file => shift @ARGV } );
$zdba->log->info( q{starting %s (version %s)}, $zdba->PROJECT_NAME, $zdba->VERSION );
while ($running) {
$zdba->config->load;
$ENV{ZDBA_SPLIT_LOGS} = $zdba->{config}{daemon}{split_logs};
for my $db ( keys %{$pool} ) {
unless ( grep { m/$db/ms } @{ $zdba->{config}{db}{list} } ) {
$zdba->log->info( q{database '%s' has gone from configuration}, $db );
$pool->{$db}->kill('USR1')->join;
delete $pool->{$db};
delete $counter->{$db};
}
}
for my $db ( @{ $zdba->{config}{db}{list} } ) {
if ( $pool->{$db} ) {
if ( $pool->{$db}->is_running ) {
next;
} else {
count($db) or next;
}
}
$zdba->log->info( q{starting thread for database '%s'}, $db );
$pool->{$db} = threads->create( sub {
$ENV{ZDBA_DBNAME} = $db;
Log::Log4perl::init( File::Spec->catfile( $Bin, 'conf', 'log4perl.conf' ) );
$zdba->monitor($db);
} );
}
for ( threads->list(threads::all) ) {
$_->kill('USR1')->join unless $_->is_running;
}
sleep( $zdba->{config}{daemon}{sleep} // $zdba->SLEEP_DAEMON );
}
sub stop {
$zdba->log->info( q{stopping %s}, $zdba->PROJECT_NAME );
$running = 0;
while ( threads->list(threads::all) ) {
$_->kill('USR1')->join for threads->list(threads::all);
}
return 1;
}
sub count {
my ($db) = @_;
my $rc = 1;
if ( defined $counter->{$db} ) {
--$counter->{$db} > 0 ? --$rc : delete $counter->{$db};
} else {
$counter->{$db} = $zdba->{config}{db}{$db}{retry_step}
// $zdba->{config}{db}{default}{retry_step}
// $zdba->RETRY_STEP;
--$rc;
}
return $rc;
}
sub logfile_name {
my $prefix = shift // 'zdba';
my $name = $ENV{ZDBA_SPLIT_LOGS} ? ( $ENV{ZDBA_DBNAME} // $prefix ) : $prefix;
return File::Spec->catfile( $Bin, 'log', "${name}.log" );
}
1;
__END__