1 package DBIx::Class::Storage::DBI::Replicated::Pool;
4 use MooseX::AttributeHelpers;
5 use DBIx::Class::Storage::DBI::Replicated::Replicant;
7 use Scalar::Util 'reftype';
9 use Carp::Clan qw/^DBIx::Class/;
10 use MooseX::Types::Moose qw/Num Int ClassName HashRef/;
12 use namespace::clean -except => 'meta';
16 DBIx::Class::Storage::DBI::Replicated::Pool - Manage a pool of replicants
20 This class is used internally by L<DBIx::Class::Storage::DBI::Replicated>. You
21 shouldn't need to create instances of this class.
25 In a replicated storage type, there is at least one replicant to handle the
26 read only traffic. The Pool class manages this replicant, or list of
27 replicants, and gives some methods for querying information about their status.
31 This class defines the following attributes.
33 =head2 maximum_lag ($num)
35 This is a number which defines the maximum allowed lag returned by the
36 L<DBIx::Class::Storage::DBI/lag_behind_master> method. The default is 0. In
37 general, this should return a larger number when the replicant is lagging
38 behind its master, however the implementation of this is database specific, so
39 don't count on this number having a fixed meaning. For example, MySQL will
40 return a number of seconds that the replicating database is lagging.
44 has 'maximum_lag' => (
54 This is an integer representing a time since the last time the replicants were
55 validated. It's nothing fancy, just an integer provided via the perl L<time|perlfunc/time>
60 has 'last_validated' => (
63 reader=>'last_validated',
64 writer=>'_last_validated',
69 =head2 replicant_type ($classname)
71 Base class used to instantiate replicants that are in the pool. Unless you
72 need to subclass L<DBIx::Class::Storage::DBI::Replicated::Replicant> you should
73 just leave this alone.
77 has 'replicant_type' => (
81 default=>'DBIx::Class::Storage::DBI',
83 'create_replicant' => 'new',
89 A hashref of replicant, with the key being the dsn and the value returning the
90 actual replicant storage. For example if the $dsn element is something like:
92 "dbi:SQLite:dbname=dbfile"
94 You could access the specific replicant via:
96 $schema->storage->replicants->{'dbname=dbfile'}
98 This attributes also supports the following helper methods:
102 =item set_replicant($key=>$storage)
104 Pushes a replicant onto the HashRef under $key
106 =item get_replicant($key)
108 Retrieves the named replicant
112 Returns true if the Pool defines replicants.
116 The number of replicants in the pool
118 =item delete_replicant ($key)
120 removes the replicant under $key from the pool
126 has 'replicants' => (
128 metaclass => 'Collection::Hash',
129 isa=>HashRef['Object'],
132 'set' => 'set_replicant',
133 'get' => 'get_replicant',
134 'empty' => 'has_replicants',
135 'count' => 'num_replicants',
136 'delete' => 'delete_replicant',
137 'values' => 'all_replicant_storages',
141 has next_unknown_replicant_id => (
143 metaclass => 'Counter',
147 inc => 'inc_unknown_replicant_id'
153 This class defines the following methods.
155 =head2 connect_replicants ($schema, Array[$connect_info])
157 Given an array of $dsn or connect_info structures suitable for connected to a
158 database, create an L<DBIx::Class::Storage::DBI::Replicated::Replicant> object
159 and store it in the L</replicants> attribute.
163 sub connect_replicants {
165 my $schema = shift @_;
167 my @newly_created = ();
168 foreach my $connect_info (@_) {
169 $connect_info = [ $connect_info ]
170 if reftype $connect_info ne 'ARRAY';
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};
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
181 no warnings 'redefine';
182 my $connect = \&DBI::connect;
183 local *DBI::connect = sub {
187 $self->connect_replicant($schema, $connect_info);
193 if (!$connect_coderef) {
194 $dsn = $connect_info->[0];
195 $dsn = $dsn->{dsn} if (reftype($dsn)||'') eq 'HASH';
198 # all attempts to get the DSN failed
199 $key = "UNKNOWN_" . $self->next_unknown_replicant_id;
200 $self->inc_unknown_replicant_id;
204 $replicant->dsn($dsn);
205 ($key) = ($dsn =~ m/^dbi\:.+\:(.+)$/i);
208 $replicant->id($key);
209 $self->set_replicant($key => $replicant);
211 push @newly_created, $replicant;
214 return @newly_created;
217 =head2 connect_replicant ($schema, $connect_info)
219 Given a schema object and a hashref of $connect_info, connect the replicant
224 sub connect_replicant {
225 my ($self, $schema, $connect_info) = @_;
226 my $replicant = $self->create_replicant($schema);
227 $replicant->connect_info($connect_info);
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
235 ## Why this is necessary at all, is that we need to have the final storage
236 ## class to apply the Replicant role.
238 $self->_safely($replicant, '->_determine_driver', sub {
239 $replicant->_determine_driver
242 DBIx::Class::Storage::DBI::Replicated::Replicant->meta->apply($replicant);
246 =head2 _safely_ensure_connected ($replicant)
248 The standard ensure_connected method with throw an exception should it fail to
249 connect. For the master database this is desirable, but since replicants are
250 allowed to fail, this behavior is not desirable. This method wraps the call
251 to ensure_connected in an eval in order to catch any generated errors. That
252 way a slave can go completely offline (ie, the box itself can die) without
253 bringing down your entire pool of databases.
257 sub _safely_ensure_connected {
258 my ($self, $replicant, @args) = @_;
260 return $self->_safely($replicant, '->ensure_connected', sub {
261 $replicant->ensure_connected(@args)
265 =head2 _safely ($replicant, $name, $code)
267 Execute C<$code> for operation C<$name> catching any exceptions and printing an
268 error message to the C<<$replicant->debugobj>>.
270 Returns 1 on success and undef on failure.
275 my ($self, $replicant, $name, $code) = @_;
284 sprintf( "Exception trying to $name for replicant %s, error is %s",
285 $replicant->_dbi_connect_info->[0], $@)
292 =head2 connected_replicants
294 Returns true if there are connected replicants. Actually is overloaded to
295 return the number of replicants. So you can do stuff like:
297 if( my $num_connected = $storage->has_connected_replicants ) {
298 print "I have $num_connected connected replicants";
300 print "Sorry, no replicants.";
303 This method will actually test that each replicant in the L</replicants> hashref
304 is actually connected, try not to hit this 10 times a second.
308 sub connected_replicants {
312 } $self->all_replicants );
315 =head2 active_replicants
317 This is an array of replicants that are considered to be active in the pool.
318 This does not check to see if they are connected, but if they are not, DBIC
319 should automatically reconnect them for us when we hit them with a query.
323 sub active_replicants {
325 return ( grep {$_} map {
327 } $self->all_replicants );
330 =head2 all_replicants
332 Just a simple array of all the replicant storages. No particular order to the
333 array is given, nor should any meaning be derived.
339 return values %{$self->replicants};
342 =head2 validate_replicants
344 This does a check to see if 1) each replicate is connected (or reconnectable),
345 2) that is ->is_replicating, and 3) that it is not exceeding the lag amount
346 defined by L</maximum_lag>. Replicants that fail any of these tests are set to
347 inactive, and thus removed from the replication pool.
349 This tests L<all_replicants>, since a replicant that has been previous marked
350 as inactive can be reactived should it start to pass the validation tests again.
352 See L<DBIx::Class::Storage::DBI> for more about checking if a replicating
353 connection is not following a master or is lagging.
355 Calling this method will generate queries on the replicant databases so it is
356 not recommended that you run them very often.
358 This method requires that your underlying storage engine supports some sort of
359 native replication mechanism. Currently only MySQL native replication is
360 supported. Your patches to make other replication types work are welcomed.
364 sub validate_replicants {
366 foreach my $replicant($self->all_replicants) {
367 if($self->_safely_ensure_connected($replicant)) {
368 my $is_replicating = $replicant->is_replicating;
369 unless(defined $is_replicating) {
370 $replicant->debugobj->print("Storage Driver ".ref($self)." Does not support the 'is_replicating' method. Assuming you are manually managing.\n");
373 if($is_replicating) {
374 my $lag_behind_master = $replicant->lag_behind_master;
375 unless(defined $lag_behind_master) {
376 $replicant->debugobj->print("Storage Driver ".ref($self)." Does not support the 'lag_behind_master' method. Assuming you are manually managing.\n");
379 if($lag_behind_master <= $self->maximum_lag) {
380 $replicant->active(1);
382 $replicant->active(0);
386 $replicant->active(0);
390 $replicant->active(0);
393 ## Mark that we completed this validation.
394 $self->_last_validated(time);
399 John Napiorkowski <john.napiorkowski@takkle.com>
403 You may distribute this code under the same terms as Perl itself.
407 __PACKAGE__->meta->make_immutable;