::DBI:Replicated - merge connect_info from master to replicants
[dbsrgits/DBIx-Class.git] / t / 93storage_replication.t
1 use strict;
2 use warnings;
3 use lib qw(t/lib);
4 use Test::More;
5 use Test::Exception;
6 use DBICTest;
7 use List::Util 'first';
8 use Scalar::Util 'reftype';
9
10 BEGIN {
11     eval "use DBIx::Class::Storage::DBI::Replicated; use Test::Moose";
12     plan $@
13         ? ( skip_all => "Deps not installed: $@" )
14         : ( tests => 83 );
15 }
16
17 use_ok 'DBIx::Class::Storage::DBI::Replicated::Pool';
18 use_ok 'DBIx::Class::Storage::DBI::Replicated::Balancer';
19 use_ok 'DBIx::Class::Storage::DBI::Replicated::Replicant';
20 use_ok 'DBIx::Class::Storage::DBI::Replicated';
21
22 =head1 HOW TO USE
23
24     This is a test of the replicated storage system.  This will work in one of
25     two ways, either it was try to fake replication with a couple of SQLite DBs
26     and creative use of copy, or if you define a couple of %ENV vars correctly
27     will try to test those.  If you do that, it will assume the setup is properly
28     replicating.  Your results may vary, but I have demonstrated this to work with
29     mysql native replication.
30     
31 =cut
32
33
34 ## ----------------------------------------------------------------------------
35 ## Build a class to hold all our required testing data and methods.
36 ## ----------------------------------------------------------------------------
37
38 TESTSCHEMACLASSES: {
39
40     ## --------------------------------------------------------------------- ##
41     ## Create an object to contain your replicated stuff.
42     ## --------------------------------------------------------------------- ##
43     
44     package DBIx::Class::DBI::Replicated::TestReplication;
45    
46     use DBICTest;
47     use base qw/Class::Accessor::Fast/;
48     
49     __PACKAGE__->mk_accessors( qw/schema/ );
50
51     ## Initialize the object
52     
53         sub new {
54             my $class = shift @_;
55             my $self = $class->SUPER::new(@_);
56         
57             $self->schema( $self->init_schema );
58             return $self;
59         }
60     
61     ## Get the Schema and set the replication storage type
62     
63     sub init_schema {
64         # current SQLT SQLite producer does not handle DROP TABLE IF EXISTS, trap warnings here
65         local $SIG{__WARN__} = sub { warn @_ unless $_[0] =~ /no such table.+DROP TABLE/ };
66
67         my $class = shift @_;
68
69         my $schema = DBICTest->init_schema(
70             sqlite_use_file => 1,
71             storage_type=>{
72                 '::DBI::Replicated' => {
73                         balancer_type=>'::Random',
74                     balancer_args=>{
75                         auto_validate_every=>100,
76                     },
77                 }
78             },
79             deploy_args=>{
80                    add_drop_table => 1,
81             },
82         );
83
84         return $schema;
85     }
86     
87     sub generate_replicant_connect_info {}
88     sub replicate {}
89     sub cleanup {}
90
91     ## --------------------------------------------------------------------- ##
92     ## Add a connect_info option to test option merging.
93     ## --------------------------------------------------------------------- ##
94     {
95     package DBIx::Class::Storage::DBI::Replicated;
96
97     use Moose;
98
99     __PACKAGE__->meta->make_mutable;
100
101     around connect_info => sub {
102       my ($next, $self, $info) = @_;
103       $info->[3]{master_option} = 1;
104       $self->$next($info);
105     };
106
107     __PACKAGE__->meta->make_immutable;
108
109     no Moose;
110     }
111   
112     ## --------------------------------------------------------------------- ##
113     ## Subclass for when you are using SQLite for testing, this provides a fake
114     ## replication support.
115     ## --------------------------------------------------------------------- ##
116         
117     package DBIx::Class::DBI::Replicated::TestReplication::SQLite;
118
119     use DBICTest;
120     use File::Copy;    
121     use base 'DBIx::Class::DBI::Replicated::TestReplication';
122     
123     __PACKAGE__->mk_accessors( qw/master_path slave_paths/ );
124     
125     ## Set the mastep path from DBICTest
126     
127         sub new {
128             my $class = shift @_;
129             my $self = $class->SUPER::new(@_);
130         
131             $self->master_path( DBICTest->_sqlite_dbfilename );
132             $self->slave_paths([
133             "t/var/DBIxClass_slave1.db",
134             "t/var/DBIxClass_slave2.db",    
135         ]);
136         
137             return $self;
138         }    
139         
140     ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
141     ## $storage->connect_info to be used for connecting replicants.
142     
143     sub generate_replicant_connect_info {
144         my $self = shift @_;
145         my @dsn = map {
146             "dbi:SQLite:${_}";
147         } @{$self->slave_paths};
148         
149         my @connect_infos = map { [$_,'','',{AutoCommit=>1}] } @dsn;
150
151     # try a hashref too
152         my $c = $connect_infos[0];
153         $connect_infos[0] = {
154           dsn => $c->[0],
155           user => $c->[1],
156           password => $c->[2],
157           %{ $c->[3] }
158         };
159
160         @connect_infos
161     }
162
163     ## Do a 'good enough' replication by copying the master dbfile over each of
164     ## the slave dbfiles.  If the master is SQLite we do this, otherwise we
165     ## just do a one second pause to let the slaves catch up.
166     
167     sub replicate {
168         my $self = shift @_;
169         foreach my $slave (@{$self->slave_paths}) {
170             copy($self->master_path, $slave);
171         }
172     }
173     
174     ## Cleanup after ourselves.  Unlink all gthe slave paths.
175     
176     sub cleanup {
177         my $self = shift @_;
178         foreach my $slave (@{$self->slave_paths}) {
179             unlink $slave;
180         }     
181     }
182     
183     ## --------------------------------------------------------------------- ##
184     ## Subclass for when you are setting the databases via custom export vars
185     ## This is for when you have a replicating database setup that you are
186     ## going to test against.  You'll need to define the correct $ENV and have
187     ## two slave databases to test against, as well as a replication system
188     ## that will replicate in less than 1 second.
189     ## --------------------------------------------------------------------- ##
190         
191     package DBIx::Class::DBI::Replicated::TestReplication::Custom; 
192     use base 'DBIx::Class::DBI::Replicated::TestReplication';
193     
194     ## Return an Array of ArrayRefs where each ArrayRef is suitable to use for
195     ## $storage->connect_info to be used for connecting replicants.
196     
197     sub generate_replicant_connect_info { 
198         return (
199             [$ENV{"DBICTEST_SLAVE0_DSN"}, $ENV{"DBICTEST_SLAVE0_DBUSER"}, $ENV{"DBICTEST_SLAVE0_DBPASS"}, {AutoCommit => 1}],
200             [$ENV{"DBICTEST_SLAVE1_DSN"}, $ENV{"DBICTEST_SLAVE1_DBUSER"}, $ENV{"DBICTEST_SLAVE1_DBPASS"}, {AutoCommit => 1}],           
201         );
202     }
203     
204     ## pause a bit to let the replication catch up 
205     
206     sub replicate {
207         sleep 1;
208     } 
209 }
210
211 ## ----------------------------------------------------------------------------
212 ## Create an object and run some tests
213 ## ----------------------------------------------------------------------------
214
215 ## Thi first bunch of tests are basic, just make sure all the bits are behaving
216
217 my $replicated_class = DBICTest->has_custom_dsn ?
218     'DBIx::Class::DBI::Replicated::TestReplication::Custom' :
219     'DBIx::Class::DBI::Replicated::TestReplication::SQLite';
220
221 ok my $replicated = $replicated_class->new
222     => 'Created a replication object';
223     
224 isa_ok $replicated->schema
225     => 'DBIx::Class::Schema';
226     
227 isa_ok $replicated->schema->storage
228     => 'DBIx::Class::Storage::DBI::Replicated';
229
230 ok $replicated->schema->storage->meta
231     => 'has a meta object';
232     
233 isa_ok $replicated->schema->storage->master
234     => 'DBIx::Class::Storage::DBI';
235     
236 isa_ok $replicated->schema->storage->pool
237     => 'DBIx::Class::Storage::DBI::Replicated::Pool';
238     
239 does_ok $replicated->schema->storage->balancer
240     => 'DBIx::Class::Storage::DBI::Replicated::Balancer'; 
241
242 ok my @replicant_connects = $replicated->generate_replicant_connect_info
243     => 'got replication connect information';
244
245 ok my @replicated_storages = $replicated->schema->storage->connect_replicants(@replicant_connects)
246     => 'Created some storages suitable for replicants';
247
248 ok my @all_storages = $replicated->schema->storage->all_storages
249     => '->all_storages';
250
251 is scalar @all_storages
252     ,3
253     => 'correct number of ->all_storages';
254
255 is ((grep $_->isa('DBIx::Class::Storage::DBI'), @all_storages)
256     ,3
257     => '->all_storages are correct type');
258
259 is ((grep $_->{master_option},
260       grep { (reftype($_)||'') eq 'HASH' }
261         map @{ $_->_connect_info }, @all_storages)
262     ,3
263     => 'connect_info was merged from master to replicants');
264  
265 my @replicant_names = keys %{ $replicated->schema->storage->replicants };
266
267 ## Silence warning about not supporting the is_replicating method if using the
268 ## sqlite dbs.
269 $replicated->schema->storage->debugobj->silence(1)
270   if first { m{^t/} } @replicant_names;
271    
272 isa_ok $replicated->schema->storage->balancer->current_replicant
273     => 'DBIx::Class::Storage::DBI'; 
274
275 $replicated->schema->storage->debugobj->silence(0);
276
277 ok $replicated->schema->storage->pool->has_replicants
278     => 'does have replicants';     
279
280 is $replicated->schema->storage->pool->num_replicants => 2
281     => 'has two replicants';
282        
283 does_ok $replicated_storages[0]
284     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
285
286 does_ok $replicated_storages[1]
287     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
288     
289 does_ok $replicated->schema->storage->replicants->{$replicant_names[0]}
290     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';
291
292 does_ok $replicated->schema->storage->replicants->{$replicant_names[1]}
293     => 'DBIx::Class::Storage::DBI::Replicated::Replicant';  
294
295 ## Add some info to the database
296
297 $replicated
298     ->schema
299     ->populate('Artist', [
300         [ qw/artistid name/ ],
301         [ 4, "Ozric Tentacles"],
302     ]);
303                 
304 ## Make sure all the slaves have the table definitions
305
306 $replicated->replicate;
307 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
308 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
309
310 ## Silence warning about not supporting the is_replicating method if using the
311 ## sqlite dbs.
312 $replicated->schema->storage->debugobj->silence(1)
313   if first { m{^t/} } @replicant_names;
314  
315 $replicated->schema->storage->pool->validate_replicants;
316
317 $replicated->schema->storage->debugobj->silence(0);
318
319 ## Make sure we can read the data.
320
321 ok my $artist1 = $replicated->schema->resultset('Artist')->find(4)
322     => 'Created Result';
323
324 isa_ok $artist1
325     => 'DBICTest::Artist';
326     
327 is $artist1->name, 'Ozric Tentacles'
328     => 'Found expected name for first result';
329
330 ## Add some new rows that only the master will have  This is because
331 ## we overload any type of write operation so that is must hit the master
332 ## database.
333
334 $replicated
335     ->schema
336     ->populate('Artist', [
337         [ qw/artistid name/ ],
338         [ 5, "Doom's Children"],
339         [ 6, "Dead On Arrival"],
340         [ 7, "Watergate"],
341     ]);
342
343 ## Make sure all the slaves have the table definitions
344 $replicated->replicate;
345
346 ## Should find some data now
347
348 ok my $artist2 = $replicated->schema->resultset('Artist')->find(5)
349     => 'Sync succeed';
350     
351 isa_ok $artist2
352     => 'DBICTest::Artist';
353     
354 is $artist2->name, "Doom's Children"
355     => 'Found expected name for first result';
356
357 ## What happens when we disconnect all the replicants?
358
359 is $replicated->schema->storage->pool->connected_replicants => 2
360     => "both replicants are connected";
361     
362 $replicated->schema->storage->replicants->{$replicant_names[0]}->disconnect;
363 $replicated->schema->storage->replicants->{$replicant_names[1]}->disconnect;
364
365 is $replicated->schema->storage->pool->connected_replicants => 0
366     => "both replicants are now disconnected";
367
368 ## All these should pass, since the database should automatically reconnect
369
370 ok my $artist3 = $replicated->schema->resultset('Artist')->find(6)
371     => 'Still finding stuff.';
372     
373 isa_ok $artist3
374     => 'DBICTest::Artist';
375     
376 is $artist3->name, "Dead On Arrival"
377     => 'Found expected name for first result';
378
379 is $replicated->schema->storage->pool->connected_replicants => 1
380     => "At Least One replicant reconnected to handle the job";
381     
382 ## What happens when we try to select something that doesn't exist?
383
384 ok ! $replicated->schema->resultset('Artist')->find(666)
385     => 'Correctly failed to find something.';
386     
387 ## test the reliable option
388
389 TESTRELIABLE: {
390         
391         $replicated->schema->storage->set_reliable_storage;
392         
393         ok $replicated->schema->resultset('Artist')->find(2)
394             => 'Read from master 1';
395         
396         ok $replicated->schema->resultset('Artist')->find(5)
397             => 'Read from master 2';
398             
399     $replicated->schema->storage->set_balanced_storage;     
400             
401         ok $replicated->schema->resultset('Artist')->find(3)
402         => 'Read from replicant';
403 }
404
405 ## Make sure when reliable goes out of scope, we are using replicants again
406
407 ok $replicated->schema->resultset('Artist')->find(1)
408     => 'back to replicant 1.';
409     
410 ok $replicated->schema->resultset('Artist')->find(2)
411     => 'back to replicant 2.';
412
413 ## set all the replicants to inactive, and make sure the balancer falls back to
414 ## the master.
415
416 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
417 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
418
419 ## Silence warning about falling back to master.
420 $replicated->schema->storage->debugobj->silence(1);
421  
422 ok $replicated->schema->resultset('Artist')->find(2)
423     => 'Fallback to master';
424
425 $replicated->schema->storage->debugobj->silence(0);
426
427 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(1);
428 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(1);
429
430 ## Silence warning about not supporting the is_replicating method if using the
431 ## sqlite dbs.
432 $replicated->schema->storage->debugobj->silence(1)
433   if first { m{^t/} } @replicant_names;
434  
435 $replicated->schema->storage->pool->validate_replicants;
436
437 $replicated->schema->storage->debugobj->silence(0);
438
439 ok $replicated->schema->resultset('Artist')->find(2)
440     => 'Returned to replicates';
441     
442 ## Getting slave status tests
443
444 SKIP: {
445     ## We skip this tests unless you have a custom replicants, since the default
446     ## sqlite based replication tests don't support these functions.
447     
448     skip 'Cannot Test Replicant Status on Non Replicating Database', 9
449      unless DBICTest->has_custom_dsn && $ENV{"DBICTEST_SLAVE0_DSN"};
450
451     $replicated->replicate; ## Give the slaves a chance to catchup.
452
453         ok $replicated->schema->storage->replicants->{$replicant_names[0]}->is_replicating
454             => 'Replicants are replicating';
455             
456         is $replicated->schema->storage->replicants->{$replicant_names[0]}->lag_behind_master, 0
457             => 'Replicant is zero seconds behind master';
458             
459         ## Test the validate replicants
460         
461         $replicated->schema->storage->pool->validate_replicants;
462         
463         is $replicated->schema->storage->pool->active_replicants, 2
464             => 'Still have 2 replicants after validation';
465             
466         ## Force the replicants to fail the validate test by required their lag to
467         ## be negative (ie ahead of the master!)
468         
469     $replicated->schema->storage->pool->maximum_lag(-10);
470     $replicated->schema->storage->pool->validate_replicants;
471     
472     is $replicated->schema->storage->pool->active_replicants, 0
473         => 'No way a replicant be be ahead of the master';
474         
475     ## Let's be fair to the replicants again.  Let them lag up to 5
476         
477     $replicated->schema->storage->pool->maximum_lag(5);
478     $replicated->schema->storage->pool->validate_replicants;
479     
480     is $replicated->schema->storage->pool->active_replicants, 2
481         => 'Both replicants in good standing again';    
482         
483         ## Check auto validate
484         
485         is $replicated->schema->storage->balancer->auto_validate_every, 100
486             => "Got the expected value for auto validate";
487             
488                 ## This will make sure we auto validatge everytime
489                 $replicated->schema->storage->balancer->auto_validate_every(0);
490                 
491                 ## set all the replicants to inactive, and make sure the balancer falls back to
492                 ## the master.
493                 
494                 $replicated->schema->storage->replicants->{$replicant_names[0]}->active(0);
495                 $replicated->schema->storage->replicants->{$replicant_names[1]}->active(0);
496                 
497                 ## Ok, now when we go to run a query, autovalidate SHOULD reconnect
498         
499         is $replicated->schema->storage->pool->active_replicants => 0
500             => "both replicants turned off";
501                 
502         ok $replicated->schema->resultset('Artist')->find(5)
503             => 'replicant reactivated';
504             
505         is $replicated->schema->storage->pool->active_replicants => 2
506             => "both replicants reactivated";        
507 }
508
509 ## Test the reliably callback
510
511 ok my $reliably = sub {
512         
513     ok $replicated->schema->resultset('Artist')->find(5)
514         => 'replicant reactivated';     
515         
516 } => 'created coderef properly';
517
518 $replicated->schema->storage->execute_reliably($reliably);
519
520 ## Try something with an error
521
522 ok my $unreliably = sub {
523     
524     ok $replicated->schema->resultset('ArtistXX')->find(5)
525         => 'replicant reactivated'; 
526     
527 } => 'created coderef properly';
528
529 throws_ok {$replicated->schema->storage->execute_reliably($unreliably)} 
530     qr/Can't find source for ArtistXX/
531     => 'Bad coderef throws proper error';
532     
533 ## Make sure replication came back
534
535 ok $replicated->schema->resultset('Artist')->find(3)
536     => 'replicant reactivated';
537     
538 ## make sure transactions are set to execute_reliably
539
540 ok my $transaction = sub {
541         
542         my $id = shift @_;
543         
544         $replicated
545             ->schema
546             ->populate('Artist', [
547                 [ qw/artistid name/ ],
548                 [ $id, "Children of the Grave"],
549             ]);
550             
551     ok my $result = $replicated->schema->resultset('Artist')->find($id)
552         => 'Found expected artist';
553         
554     ok my $more = $replicated->schema->resultset('Artist')->find(1)
555         => 'Found expected artist again';
556         
557    return ($result, $more);
558    
559 } => 'Created a coderef properly';
560
561 ## Test the transaction with multi return
562 {
563         ok my @return = $replicated->schema->txn_do($transaction, 666)
564             => 'did transaction';
565             
566             is $return[0]->id, 666
567                 => 'first returned value is correct';
568                 
569             is $return[1]->id, 1
570                 => 'second returned value is correct';
571 }
572
573 ## Test that asking for single return works
574 {
575         ok my $return = $replicated->schema->txn_do($transaction, 777)
576             => 'did transaction';
577             
578             is $return->id, 777
579                 => 'first returned value is correct';
580 }
581
582 ## Test transaction returning a single value
583
584 {
585         ok my $result = $replicated->schema->txn_do(sub {
586                 ok my $more = $replicated->schema->resultset('Artist')->find(1)
587                 => 'found inside a transaction';
588                 return $more;
589         }) => 'successfully processed transaction';
590         
591         is $result->id, 1
592            => 'Got expected single result from transaction';
593 }
594
595 ## Make sure replication came back
596
597 ok $replicated->schema->resultset('Artist')->find(1)
598     => 'replicant reactivated';
599     
600 ## Test Discard changes
601
602 {
603         ok my $artist = $replicated->schema->resultset('Artist')->find(2)
604             => 'got an artist to test discard changes';
605             
606         ok $artist->discard_changes
607            => 'properly discard changes';
608 }
609
610 ## Test some edge cases, like trying to do a transaction inside a transaction, etc
611
612 {
613     ok my $result = $replicated->schema->txn_do(sub {
614         return $replicated->schema->txn_do(sub {
615                 ok my $more = $replicated->schema->resultset('Artist')->find(1)
616                 => 'found inside a transaction inside a transaction';
617                 return $more;                   
618         });
619     }) => 'successfully processed transaction';
620     
621     is $result->id, 1
622        => 'Got expected single result from transaction';          
623 }
624
625 {
626     ok my $result = $replicated->schema->txn_do(sub {
627         return $replicated->schema->storage->execute_reliably(sub {
628                 return $replicated->schema->txn_do(sub {
629                         return $replicated->schema->storage->execute_reliably(sub {
630                                 ok my $more = $replicated->schema->resultset('Artist')->find(1)
631                                 => 'found inside crazy deep transactions and execute_reliably';
632                                 return $more;                           
633                         });
634                 });     
635         });
636     }) => 'successfully processed transaction';
637     
638     is $result->id, 1
639        => 'Got expected single result from transaction';          
640 }     
641
642 ## Test the force_pool resultset attribute.
643
644 {
645         ok my $artist_rs = $replicated->schema->resultset('Artist')
646         => 'got artist resultset';
647            
648         ## Turn on Forced Pool Storage
649         ok my $reliable_artist_rs = $artist_rs->search(undef, {force_pool=>'master'})
650         => 'Created a resultset using force_pool storage';
651            
652     ok my $artist = $reliable_artist_rs->find(2) 
653         => 'got an artist result via force_pool storage';
654 }
655
656 ## Delete the old database files
657 $replicated->cleanup;