FINALLY find and fix the elusive parallel test deadlock
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest.pm
index 670e180..47b62a9 100644 (file)
@@ -4,7 +4,7 @@ package # hide from PAUSE
 use strict;
 use warnings;
 
-use DBICTest::Util 'local_umask';
+use DBICTest::Util qw( local_umask await_flock dbg DEBUG_TEST_CONCURRENCY_LOCKS );
 use DBICTest::Schema;
 use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
 use DBIx::Class::_Util 'detected_reinvoked_destructor';
@@ -90,7 +90,14 @@ sub import {
 
     for my $exp (@_) {
         if ($exp eq ':GlobalLock') {
-            flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
+            DEBUG_TEST_CONCURRENCY_LOCKS > 1
+              and dbg "Waiting for EXCLUSIVE global lock...";
+
+            await_flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
+
+            DEBUG_TEST_CONCURRENCY_LOCKS > 1
+              and dbg "Got EXCLUSIVE global lock";
+
             $global_exclusive_lock = 1;
         }
         elsif ($exp eq ':DiffSQL') {
@@ -107,13 +114,22 @@ sub import {
     }
 
     unless ($global_exclusive_lock) {
-        flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
+        DEBUG_TEST_CONCURRENCY_LOCKS > 1
+          and dbg "Waiting for SHARED global lock...";
+
+        await_flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
+
+        DEBUG_TEST_CONCURRENCY_LOCKS > 1
+          and dbg "Got SHARED global lock";
     }
 }
 
 END {
+    # referencing here delays destruction even more
     if ($global_lock_fh) {
-        # delay destruction even more
+      DEBUG_TEST_CONCURRENCY_LOCKS > 1
+        and dbg "Release @{[ $global_exclusive_lock ? 'EXCLUSIVE' : 'SHARED' ]} global lock (END)";
+      1;
     }
 }
 
@@ -143,6 +159,7 @@ END {
 
 $SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
 
+my $need_global_cleanup;
 sub _cleanup_dbfile {
     # cleanup if this is us
     if (
@@ -152,6 +169,10 @@ sub _cleanup_dbfile {
         or
       $ENV{DBICTEST_LOCK_HOLDER} == $$
     ) {
+        if ($need_global_cleanup and my $dbh = DBICTest->schema->storage->_dbh) {
+          $dbh->disconnect;
+        }
+
         my $db_file = _sqlite_dbfilename();
         unlink $_ for ($db_file, "${db_file}-journal");
     }
@@ -316,6 +337,7 @@ sub init_schema {
     my $schema;
 
     if ($args{compose_connection}) {
+      $need_global_cleanup = 1;
       $schema = DBICTest::Schema->compose_connection(
                   'DBICTest', $self->_database(%args)
                 );