minor changes
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Replicated / Pool.pm
CommitLineData
26ab719a 1package DBIx::Class::Storage::DBI::Replicated::Pool;
2
3use Moose;
4use MooseX::AttributeHelpers;
5use DBIx::Class::Storage::DBI::Replicated::Replicant;
9901aad7 6use List::Util 'sum';
7use Scalar::Util 'reftype';
0bd8e058 8use DBI ();
9901aad7 9use Carp::Clan qw/^DBIx::Class/;
41916570 10use MooseX::Types::Moose qw/Num Int ClassName HashRef/;
9901aad7 11
12use namespace::clean -except => 'meta';
26ab719a 13
14=head1 NAME
15
21fc4719 16DBIx::Class::Storage::DBI::Replicated::Pool - Manage a pool of replicants
26ab719a 17
18=head1 SYNOPSIS
19
20This class is used internally by L<DBIx::Class::Storage::DBI::Replicated>. You
21shouldn't need to create instances of this class.
d4daee7b 22
26ab719a 23=head1 DESCRIPTION
24
25In a replicated storage type, there is at least one replicant to handle the
26read only traffic. The Pool class manages this replicant, or list of
27replicants, and gives some methods for querying information about their status.
28
29=head1 ATTRIBUTES
30
31This class defines the following attributes.
32
4a607d7a 33=head2 maximum_lag ($num)
34
35This is a number which defines the maximum allowed lag returned by the
36L<DBIx::Class::Storage::DBI/lag_behind_master> method. The default is 0. In
37general, this should return a larger number when the replicant is lagging
faaba25f 38behind its master, however the implementation of this is database specific, so
4a607d7a 39don't count on this number having a fixed meaning. For example, MySQL will
40return a number of seconds that the replicating database is lagging.
41
42=cut
43
44has 'maximum_lag' => (
64cdad22 45 is=>'rw',
41916570 46 isa=>Num,
64cdad22 47 required=>1,
48 lazy=>1,
49 default=>0,
4a607d7a 50);
51
17b05c13 52=head2 last_validated
53
54This is an integer representing a time since the last time the replicants were
faaba25f 55validated. It's nothing fancy, just an integer provided via the perl L<time|perlfunc/time>
17b05c13 56builtin.
57
58=cut
59
60has 'last_validated' => (
64cdad22 61 is=>'rw',
41916570 62 isa=>Int,
64cdad22 63 reader=>'last_validated',
64 writer=>'_last_validated',
65 lazy=>1,
66 default=>0,
17b05c13 67);
68
4a607d7a 69=head2 replicant_type ($classname)
26ab719a 70
71Base class used to instantiate replicants that are in the pool. Unless you
72need to subclass L<DBIx::Class::Storage::DBI::Replicated::Replicant> you should
73just leave this alone.
74
75=cut
76
77has 'replicant_type' => (
64cdad22 78 is=>'ro',
41916570 79 isa=>ClassName,
64cdad22 80 required=>1,
81 default=>'DBIx::Class::Storage::DBI',
82 handles=>{
83 'create_replicant' => 'new',
84 },
26ab719a 85);
86
26ab719a 87=head2 replicants
88
89A hashref of replicant, with the key being the dsn and the value returning the
90actual replicant storage. For example if the $dsn element is something like:
91
64cdad22 92 "dbi:SQLite:dbname=dbfile"
d4daee7b 93
26ab719a 94You could access the specific replicant via:
95
64cdad22 96 $schema->storage->replicants->{'dbname=dbfile'}
d4daee7b 97
64cdad22 98This attributes also supports the following helper methods:
26ab719a 99
100=over 4
101
102=item set_replicant($key=>$storage)
103
104Pushes a replicant onto the HashRef under $key
105
106=item get_replicant($key)
107
108Retrieves the named replicant
109
110=item has_replicants
111
112Returns true if the Pool defines replicants.
113
114=item num_replicants
115
116The number of replicants in the pool
117
118=item delete_replicant ($key)
119
120removes the replicant under $key from the pool
121
122=back
123
124=cut
125
126has 'replicants' => (
64cdad22 127 is=>'rw',
128 metaclass => 'Collection::Hash',
071bbccb 129 isa=>HashRef['Object'],
64cdad22 130 default=>sub {{}},
131 provides => {
132 'set' => 'set_replicant',
d4daee7b 133 'get' => 'get_replicant',
64cdad22 134 'empty' => 'has_replicants',
135 'count' => 'num_replicants',
136 'delete' => 'delete_replicant',
d4daee7b 137 'values' => 'all_replicant_storages',
64cdad22 138 },
26ab719a 139);
140
ede99b9f 141has next_unknown_replicant_id => (
142 is => 'rw',
143 metaclass => 'Counter',
144 isa => Int,
145 default => 1,
146 provides => {
147 inc => 'inc_unknown_replicant_id'
148 },
149);
150
26ab719a 151=head1 METHODS
152
153This class defines the following methods.
154
955a6df6 155=head2 connect_replicants ($schema, Array[$connect_info])
26ab719a 156
d40080c3 157Given an array of $dsn or connect_info structures suitable for connected to a
158database, create an L<DBIx::Class::Storage::DBI::Replicated::Replicant> object
159and store it in the L</replicants> attribute.
26ab719a 160
161=cut
162
955a6df6 163sub connect_replicants {
64cdad22 164 my $self = shift @_;
165 my $schema = shift @_;
d4daee7b 166
64cdad22 167 my @newly_created = ();
168 foreach my $connect_info (@_) {
2cd3ccc4 169 $connect_info = [ $connect_info ]
9901aad7 170 if reftype $connect_info ne 'ARRAY';
171
0bd8e058 172 my $connect_coderef =
173 (reftype($connect_info->[0])||'') eq 'CODE' ? $connect_info->[0]
174 : (reftype($connect_info->[0])||'') eq 'HASH' &&
175 $connect_info->[0]->{dbh_maker};
176
177 my $dsn;
4c91f824 178 my $replicant = do {
ede99b9f 179# yes this is evil, but it only usually happens once (for coderefs)
180# this will fail if the coderef does not actually DBI::connect
0bd8e058 181 no warnings 'redefine';
182 my $connect = \&DBI::connect;
183 local *DBI::connect = sub {
184 $dsn = $_[1];
185 goto $connect;
186 };
4c91f824 187 $self->connect_replicant($schema, $connect_info);
188 };
189
ede99b9f 190 my $key;
191
192 if (!$dsn) {
193 if (!$connect_coderef) {
194 $dsn = $connect_info->[0];
195 $dsn = $dsn->{dsn} if (reftype($dsn)||'') eq 'HASH';
196 }
197 else {
198 # all attempts to get the DSN failed
199 $key = "UNKNOWN_" . $self->next_unknown_replicant_id;
200 $self->inc_unknown_replicant_id;
201 }
202 }
203 if ($dsn) {
204 $replicant->dsn($dsn);
205 ($key) = ($dsn =~ m/^dbi\:.+\:(.+)$/i);
0bd8e058 206 }
0bd8e058 207
ede99b9f 208 $replicant->id($key);
0bd8e058 209 $self->set_replicant($key => $replicant);
ede99b9f 210
64cdad22 211 push @newly_created, $replicant;
212 }
d4daee7b 213
64cdad22 214 return @newly_created;
26ab719a 215}
216
bbafcf26 217=head2 connect_replicant ($schema, $connect_info)
218
219Given a schema object and a hashref of $connect_info, connect the replicant
220and return it.
221
222=cut
223
224sub connect_replicant {
225 my ($self, $schema, $connect_info) = @_;
226 my $replicant = $self->create_replicant($schema);
f15afa13 227 $replicant->connect_info($connect_info);
d40080c3 228
229## It is undesirable for catalyst to connect at ->conect_replicants time, as
230## connections should only happen on the first request that uses the database.
231## So we try to set the driver without connecting, however this doesn't always
232## work, as a driver may need to connect to determine the DB version, and this
233## may fail.
d6e80959 234##
235## Why this is necessary at all, is that we need to have the final storage
236## class to apply the Replicant role.
d40080c3 237
238 $self->_safely($replicant, '->_determine_driver', sub {
239 $replicant->_determine_driver
240 });
241
f15afa13 242 DBIx::Class::Storage::DBI::Replicated::Replicant->meta->apply($replicant);
bbafcf26 243 return $replicant;
244}
245
f15afa13 246=head2 _safely_ensure_connected ($replicant)
247
248The standard ensure_connected method with throw an exception should it fail to
249connect. For the master database this is desirable, but since replicants are
250allowed to fail, this behavior is not desirable. This method wraps the call
251to ensure_connected in an eval in order to catch any generated errors. That
d40080c3 252way a slave can go completely offline (ie, the box itself can die) without
f15afa13 253bringing down your entire pool of databases.
254
255=cut
256
257sub _safely_ensure_connected {
258 my ($self, $replicant, @args) = @_;
d40080c3 259
260 return $self->_safely($replicant, '->ensure_connected', sub {
261 $replicant->ensure_connected(@args)
262 });
263}
264
265=head2 _safely ($replicant, $name, $code)
266
267Execute C<$code> for operation C<$name> catching any exceptions and printing an
268error message to the C<<$replicant->debugobj>>.
269
270Returns 1 on success and undef on failure.
271
272=cut
273
274sub _safely {
275 my ($self, $replicant, $name, $code) = @_;
276
6ffb5be5 277 eval {
d40080c3 278 $code->()
6ffb5be5 279 };
280 if ($@) {
13b9e828 281 $replicant
6ffb5be5 282 ->debugobj
283 ->print(
d40080c3 284 sprintf( "Exception trying to $name for replicant %s, error is %s",
6ffb5be5 285 $replicant->_dbi_connect_info->[0], $@)
13b9e828 286 );
6ffb5be5 287 return;
13b9e828 288 }
6ffb5be5 289 return 1;
f15afa13 290}
291
26ab719a 292=head2 connected_replicants
293
294Returns true if there are connected replicants. Actually is overloaded to
295return the number of replicants. So you can do stuff like:
296
64cdad22 297 if( my $num_connected = $storage->has_connected_replicants ) {
298 print "I have $num_connected connected replicants";
299 } else {
300 print "Sorry, no replicants.";
301 }
26ab719a 302
303This method will actually test that each replicant in the L</replicants> hashref
304is actually connected, try not to hit this 10 times a second.
305
306=cut
307
308sub connected_replicants {
64cdad22 309 my $self = shift @_;
310 return sum( map {
311 $_->connected ? 1:0
312 } $self->all_replicants );
26ab719a 313}
314
50336325 315=head2 active_replicants
316
317This is an array of replicants that are considered to be active in the pool.
318This does not check to see if they are connected, but if they are not, DBIC
319should automatically reconnect them for us when we hit them with a query.
320
321=cut
322
323sub active_replicants {
64cdad22 324 my $self = shift @_;
325 return ( grep {$_} map {
326 $_->active ? $_:0
327 } $self->all_replicants );
50336325 328}
329
26ab719a 330=head2 all_replicants
331
332Just a simple array of all the replicant storages. No particular order to the
333array is given, nor should any meaning be derived.
334
335=cut
336
337sub all_replicants {
64cdad22 338 my $self = shift @_;
339 return values %{$self->replicants};
26ab719a 340}
341
4a607d7a 342=head2 validate_replicants
343
344This does a check to see if 1) each replicate is connected (or reconnectable),
3452) that is ->is_replicating, and 3) that it is not exceeding the lag amount
346defined by L</maximum_lag>. Replicants that fail any of these tests are set to
347inactive, and thus removed from the replication pool.
348
349This tests L<all_replicants>, since a replicant that has been previous marked
350as inactive can be reactived should it start to pass the validation tests again.
351
352See L<DBIx::Class::Storage::DBI> for more about checking if a replicating
353connection is not following a master or is lagging.
354
355Calling this method will generate queries on the replicant databases so it is
356not recommended that you run them very often.
357
13b9e828 358This method requires that your underlying storage engine supports some sort of
359native replication mechanism. Currently only MySQL native replication is
360supported. Your patches to make other replication types work are welcomed.
361
4a607d7a 362=cut
363
364sub validate_replicants {
64cdad22 365 my $self = shift @_;
366 foreach my $replicant($self->all_replicants) {
13b9e828 367 if($self->_safely_ensure_connected($replicant)) {
368 my $is_replicating = $replicant->is_replicating;
369 unless(defined $is_replicating) {
9901aad7 370 $replicant->debugobj->print("Storage Driver ".ref($self)." Does not support the 'is_replicating' method. Assuming you are manually managing.\n");
13b9e828 371 next;
372 } else {
373 if($is_replicating) {
374 my $lag_behind_master = $replicant->lag_behind_master;
375 unless(defined $lag_behind_master) {
9901aad7 376 $replicant->debugobj->print("Storage Driver ".ref($self)." Does not support the 'lag_behind_master' method. Assuming you are manually managing.\n");
13b9e828 377 next;
378 } else {
379 if($lag_behind_master <= $self->maximum_lag) {
380 $replicant->active(1);
381 } else {
382 $replicant->active(0);
383 }
384 }
385 } else {
386 $replicant->active(0);
387 }
388 }
64cdad22 389 } else {
64cdad22 390 $replicant->active(0);
7edf5f1c 391 }
64cdad22 392 }
393 ## Mark that we completed this validation.
13b9e828 394 $self->_last_validated(time);
4a607d7a 395}
396
26ab719a 397=head1 AUTHOR
398
399John Napiorkowski <john.napiorkowski@takkle.com>
400
401=head1 LICENSE
402
403You may distribute this code under the same terms as Perl itself.
404
405=cut
406
c354902c 407__PACKAGE__->meta->make_immutable;
408
cb6ec758 4091;