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