FINALLY find and fix the elusive parallel test deadlock
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / BaseSchema.pm
1 package #hide from pause
2   DBICTest::BaseSchema;
3
4 use strict;
5 use warnings;
6 use base qw(DBICTest::Base DBIx::Class::Schema);
7
8 use Fcntl qw(:DEFAULT :seek :flock);
9 use Time::HiRes 'sleep';
10 use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry);
11 use DBICTest::Util qw( local_umask await_flock dbg DEBUG_TEST_CONCURRENCY_LOCKS );
12 use namespace::clean;
13
14 sub capture_executed_sql_bind {
15   my ($self, $cref) = @_;
16
17   $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
18
19   require DBICTest::SQLTracerObj;
20
21   # hack around stupid, stupid API
22   no warnings 'redefine';
23   local *DBIx::Class::Storage::DBI::_format_for_trace = sub { $_[1] };
24   Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
25
26
27   local $self->storage->{debugcb};
28   local $self->storage->{debugobj} = my $tracer_obj = DBICTest::SQLTracerObj->new;
29   local $self->storage->{debug} = 1;
30
31   local $Test::Builder::Level = $Test::Builder::Level + 2;
32   $cref->();
33
34   return $tracer_obj->{sqlbinds} || [];
35 }
36
37 sub is_executed_querycount {
38   my ($self, $cref, $exp_counts, $msg) = @_;
39
40   local $Test::Builder::Level = $Test::Builder::Level + 1;
41
42   $self->throw_exception("Expecting an hashref of counts or an integer representing total query count")
43     unless ref $exp_counts eq 'HASH' or (defined $exp_counts and ! ref $exp_counts);
44
45   my @got = map { $_->[0] } @{ $self->capture_executed_sql_bind($cref) };
46
47   return Test::More::is( @got, $exp_counts, $msg )
48     unless ref $exp_counts;
49
50   my $got_counts = { map { $_ => 0 } keys %$exp_counts };
51   $got_counts->{$_}++ for @got;
52
53   return Test::More::is_deeply(
54     $got_counts,
55     $exp_counts,
56     $msg,
57   );
58 }
59
60 sub is_executed_sql_bind {
61   my ($self, $cref, $sqlbinds, $msg) = @_;
62
63   local $Test::Builder::Level = $Test::Builder::Level + 1;
64
65   $self->throw_exception("Expecting an arrayref of SQL/Bind pairs") unless ref $sqlbinds eq 'ARRAY';
66
67   my @expected = @$sqlbinds;
68
69   my @got = map { $_->[1] } @{ $self->capture_executed_sql_bind($cref) };
70
71
72   return Test::Builder->new->ok(1, $msg || "No queries executed while running $cref")
73     if !@got and !@expected;
74
75   require SQL::Abstract::Test;
76   my $ret = 1;
77   while (@expected or @got) {
78     my $left = shift @got;
79     my $right = shift @expected;
80
81     # allow the right side to "simplify" the entire shebang
82     if ($left and $right) {
83       $left = [ @$left ];
84       for my $i (1..$#$right) {
85         if (
86           ! ref $right->[$i]
87             and
88           ref $left->[$i] eq 'ARRAY'
89             and
90           @{$left->[$i]} == 2
91         ) {
92           $left->[$i] = $left->[$i][1]
93         }
94       }
95     }
96
97     $ret &= SQL::Abstract::Test::is_same_sql_bind(
98       \( $left || [] ),
99       \( $right || [] ),
100       $msg,
101     );
102   }
103
104   return $ret;
105 }
106
107 our $locker;
108 END {
109   # we need the $locker to be referenced here for delayed destruction
110   if ($locker->{lock_name} and ($ENV{DBICTEST_LOCK_HOLDER}||0) == $$) {
111     DEBUG_TEST_CONCURRENCY_LOCKS
112       and dbg "$locker->{type} LOCK RELEASED (END): $locker->{lock_name}";
113   }
114 }
115
116 my $weak_registry = {};
117
118 sub connection {
119   my $self = shift->next::method(@_);
120
121 # MASSIVE FIXME
122 # we can't really lock based on DSN, as we do not yet have a way to tell that e.g.
123 # DBICTEST_MSSQL_DSN=dbi:Sybase:server=192.168.0.11:1433;database=dbtst
124 #  and
125 # DBICTEST_MSSQL_ODBC_DSN=dbi:ODBC:server=192.168.0.11;port=1433;database=dbtst;driver=FreeTDS;tds_version=8.0
126 # are the same server
127 # hence we lock everything based on sqlt_type or just globally if not available
128 # just pretend we are python you know? :)
129
130
131   # when we get a proper DSN resolution sanitize to produce a portable lockfile name
132   # this may look weird and unnecessary, but consider running tests from
133   # windows over a samba share >.>
134   #utf8::encode($dsn);
135   #$dsn =~ s/([^A-Za-z0-9_\-\.\=])/ sprintf '~%02X', ord($1) /ge;
136   #$dsn =~ s/^dbi/dbi/i;
137
138   # provide locking for physical (non-memory) DSNs, so that tests can
139   # safely run in parallel. While the harness (make -jN test) does set
140   # an envvar, we can not detect when a user invokes prove -jN. Hence
141   # perform the locking at all times, it shouldn't hurt.
142   # the lock fh *should* inherit across forks/subprocesses
143   if (
144     ! $DBICTest::global_exclusive_lock
145       and
146     ( ! $ENV{DBICTEST_LOCK_HOLDER} or $ENV{DBICTEST_LOCK_HOLDER} == $$ )
147       and
148     ref($_[0]) ne 'CODE'
149       and
150     ($_[0]||'') !~ /^ (?i:dbi) \: SQLite \: (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
151   ) {
152
153     my $locktype;
154
155     {
156       # guard against infinite recursion
157       local $ENV{DBICTEST_LOCK_HOLDER} = -1;
158
159       # we need to work with a forced fresh clone so that we do not upset any state
160       # of the main $schema (some tests examine it quite closely)
161       local $SIG{__WARN__} = sub {};
162       local $@;
163
164       # this will either give us an undef $locktype or will determine things
165       # properly with a default ( possibly connecting in the process )
166       eval {
167         my $s = ref($self)->connect(@{$self->storage->connect_info})->storage;
168
169         $locktype = $s->sqlt_type || 'generic';
170
171         # in case sqlt_type did connect, doesn't matter if it fails or something
172         $s->disconnect;
173       };
174     }
175
176     # Never hold more than one lock. This solves the "lock in order" issues
177     # unrelated tests may have
178     # Also if there is no connection - there is no lock to be had
179     if ($locktype and (!$locker or $locker->{type} ne $locktype)) {
180
181       # this will release whatever lock we may currently be holding
182       # which is fine since the type does not match as checked above
183       DEBUG_TEST_CONCURRENCY_LOCKS
184         and $locker
185         and dbg "$locker->{type} LOCK RELEASED (UNDEF): $locker->{lock_name}";
186
187       undef $locker;
188
189       my $lockpath = DBICTest::RunMode->tmpdir->file("_dbictest_$locktype.lock");
190
191       DEBUG_TEST_CONCURRENCY_LOCKS
192         and dbg "Waiting for $locktype LOCK: $lockpath...";
193
194       my $lock_fh;
195       {
196         my $u = local_umask(0); # so that the file opens as 666, and any user can lock
197         sysopen ($lock_fh, $lockpath, O_RDWR|O_CREAT) or die "Unable to open $lockpath: $!";
198       }
199
200       await_flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
201
202       DEBUG_TEST_CONCURRENCY_LOCKS
203         and dbg "Got $locktype LOCK: $lockpath";
204
205       # see if anyone was holding a lock before us, and wait up to 5 seconds for them to terminate
206       # if we do not do this we may end up trampling over some long-running END or somesuch
207       seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
208       my $old_pid;
209       if (
210         read ($lock_fh, $old_pid, 100)
211           and
212         ($old_pid) = $old_pid =~ /^(\d+)$/
213       ) {
214         DEBUG_TEST_CONCURRENCY_LOCKS
215           and dbg "Post-grab WAIT for $old_pid START: $lockpath";
216
217         for (1..50) {
218           kill (0, $old_pid) or last;
219           sleep 0.1;
220         }
221
222         DEBUG_TEST_CONCURRENCY_LOCKS
223           and dbg "Post-grab WAIT for $old_pid FINISHED: $lockpath";
224       }
225
226       truncate $lock_fh, 0;
227       seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
228       $lock_fh->autoflush(1);
229       print $lock_fh $$;
230
231       $ENV{DBICTEST_LOCK_HOLDER} ||= $$;
232
233       $locker = {
234         type => $locktype,
235         fh => $lock_fh,
236         lock_name => "$lockpath",
237       };
238     }
239   }
240
241   if ($INC{'Test/Builder.pm'}) {
242     populate_weakregistry ( $weak_registry, $self->storage );
243
244     my $cur_connect_call = $self->storage->on_connect_call;
245
246     $self->storage->on_connect_call([
247       (ref $cur_connect_call eq 'ARRAY'
248         ? @$cur_connect_call
249         : ($cur_connect_call || ())
250       ),
251       [sub {
252         populate_weakregistry( $weak_registry, shift->_dbh )
253       }],
254     ]);
255   }
256
257   return $self;
258 }
259
260 sub clone {
261   my $self = shift->next::method(@_);
262   populate_weakregistry ( $weak_registry, $self )
263     if $INC{'Test/Builder.pm'};
264   $self;
265 }
266
267 END {
268   assert_empty_weakregistry($weak_registry, 'quiet');
269 }
270
271 1;