Skip to contentSkip to conversation

Database locking: Perl: Retry all deadlocks in PostgreSQL

PATCH In review Ian Jackson 3 participants 13 messages Dec 15, 2015 – Dec 16, 2015

lore
Share & tools
lore
#0 lore raw

PATCH 1/4 Database locking: Perl: Retry all deadlocks in PostgreSQL

Previously we would retry all COMMITs but nothing else. This is correct for SQLite3 but not for PostgreSQL.

We got away with it before because of the heavyweight locking of even long-running read-only transactions, but now the LOCK TABLEs can fail (at least in a mixed-version system, and perhaps even in a system with only new code).

So: cover all of the database work in db_retry with the eval, and explicitly ask the JobDB adaptation layer (via a new need_retry method) whether to go around again. We tell the JobDB layer whether the problem was during commit, so that we can avoid making any overall semantic change to the interaction with SQLite3.

In the PostgreSQL case, the db handle can be asked whether there was an error and what the error code was. Deadlock has its own error code.

I have tested this with the following rune:

OSSTEST_CONFIG=/u/iwj/.xen-osstest/config:local-config.test-database_iwj perl -w -MData::Dumper -e 'use strict; use Osstest::Executive; use Osstest; csreadconfig(); print Dumper($dbh_tests->{AutoCommit}); eval { $dbh_tests->do("BOGUS"); }; db_begin_work($dbh_tests, [qw(flights resources)])'

adding a sleep(2) to the loop Osstest::JobDB::Executive::begin_work, and running a second copy of the rune with the tables to lock in the other order.

---
 Osstest.pm                  |   34 +++++++++++++++++++++-------------
 Osstest/JobDB/Executive.pm  |    7 +++++++
 Osstest/JobDB/Standalone.pm |    5 +++++
 3 files changed, 33 insertions(+), 13 deletions(-)
Osstest.pm +21 -13
index d4ddda7..a39ae42 100644
@@ -288,20 +288,28 @@ sub db_retry ($$$;$$) {
     for (;;) {
         $pre->();
 
-        db_begin_work($dbh, $tables);
-        if (defined $fl) {
-            die unless $dbh eq $dbh_tests;
-            $mjobdb->dbfl_check($fl,$flok);
-        }
-        $db_retry_stop= 0;
-        $r= &$body;
-        if ($db_retry_stop) {
-            $dbh->rollback();
-            last if $db_retry_stop eq 'abort';
-        } else {
-            last if eval { $dbh->commit(); 1; };
-        }
+	my $committing = 0;
+	eval {
+	    db_begin_work($dbh, $tables);
+	    if (defined $fl) {
+		die unless $dbh eq $dbh_tests;
+		$mjobdb->dbfl_check($fl,$flok);
+	    }
+	    $db_retry_stop= 0;
+	    $r= &$body;
+	    if ($db_retry_stop) {
+		$dbh->rollback();
+		last if $db_retry_stop eq 'abort';
+		next;
+	    }
+	    $committing = 1;
+	    $dbh->commit();
+	};
+	last if !length $@;
+	die $@ unless $mjobdb->need_retry($dbh, $committing);
         die "$dbh $body $@ ?" unless $retries-- > 0;
+	eval { $dbh->rollback(); };
+	print STDERR "DB conflict (messages above may refer); retrying...\n";
         sleep(1);
     }
     return $r;
Osstest/JobDB/Executive.pm +7 -0
index 124e7c0..6fb77a4 100644
@@ -47,6 +47,13 @@ sub begin_work ($$$) { #method
     }
 }
 
+sub need_retry ($$$) {
+    my ($jd, $dbh,$committing) = @_;
+    return
+	$dbh_tests->err()==7 &&
+	($dbh_tests->state =~ m/^40P01/); # DEADLOCK DETECTED
+}
+
 sub current_flight ($) { #method
     return $ENV{'OSSTEST_FLIGHT'};
 }
Osstest/JobDB/Standalone.pm +5 -0
index 431ba5a..98d0173 100644
@@ -41,6 +41,11 @@ augmentconfigdefaults(
 sub new { return bless {}, $_[0]; };
 
 sub begin_work { }
+sub need_retry ($$$) {
+    my ($jd, $dbh,$committing) = @_;
+    return $committing;
+}
+
 sub dbfl_check { }
 
 sub open ($) {
Signature · 1 line
1.7.10.4
#1 lore raw

PATCH 2/4 Database locking: Perl: Increase retry count

It seems to me that this deadlock might actually become fairly common in some setups. There is little harm in trying it for 100s rather than 20s, and there maybe some benefit.

---
 Osstest.pm |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Osstest.pm +1 -1
index a39ae42..c77d960 100644
@@ -282,7 +282,7 @@ sub db_retry ($$$;$$) {
     my ($pre,$body) =
         (ref $code eq 'ARRAY') ? @$code : (sub { }, $code);
 
-    my $retries= 20;
+    my $retries= 100;
     my $r;
     local $db_retry_stop;
     for (;;) {
Signature · 1 line
1.7.10.4
Acked-by on v1 2/4
#2 lore raw

Re: [OSSTEST PATCH 2/4] Database locking: Perl: Increase retry count

Quoted 5 lines · Ian Jackson

It seems to me that this deadlock might actually become fairly common in some setups.  There is little harm in trying it for 100s rather than 20s, and there maybe some benefit.

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

#3 lore raw

PATCH 3/4 Database locking: Tcl: Cover LOCK TABLEs with catch

In reply to Ian Jackson

Previously we would retry only the body, but not LOCK TABLEs.

We got away with it before because of the heavyweight locking of even long-running read-only transactions, but now the LOCK TABLEs can fail (at least in a mixed-version system, and perhaps even in a system with only new code).

Additionally, if one of the LOCK TABLEs fails, the code's use of the db handle becomes stuck because of the failed transaction: the error is caught by the daemon's main loop error handler, but the db handle is not subjected to ROLLBACK and all future attempts to use it will fail.

So: move the LOCK TABLEs (and the SET TRANSACTION) into the catch, so that deadlocks in LOCK TABLEs are retried (after ROLLBACK).

The COMMIT remains outside the eval but this should be unaffected by DB deadlocks if the LOCK TABLEs are right.

Note that this code does not attempt to distinguish DB deadlock errors from other errors. Arguably this is quite wrong. Fixing it to distinguish deadlocks is awkward because pg_execute does not leave the error information anywhere it can be found. Contrary to what the documentation seems to imply, it does not set errorCode (!)

---
 tcl/JobDB-Executive.tcl |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
tcl/JobDB-Executive.tcl +5 -3
index a3dbb9e..8e45ea7 100644
@@ -228,9 +228,11 @@ proc transaction {tables script} {
     while 1 {
         set ol {}
         db-execute BEGIN
-        db-execute "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"
-        lock-tables $tables
-	set rc [catch { uplevel 1 $script } result]
+	set rc [catch {
+	    db-execute "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"
+	    lock-tables $tables
+	    uplevel 1 $script
+	} result]
 	if {!$rc} {
 	    if {[catch {
 		db-execute COMMIT
Signature · 1 line
1.7.10.4
Acked-by on v1 3/4
#4 lore raw

Re: [OSSTEST PATCH 3/4] Database locking: Tcl: Cover LOCK TABLEs with catch

Quoted 19 lines · Ian Jackson

Previously we would retry only the body, but not LOCK TABLEs.

We got away with it before because of the heavyweight locking of even long-running read-only transactions, but now the LOCK TABLEs can fail (at least in a mixed-version system, and perhaps even in a system with only new code).

Additionally, if one of the LOCK TABLEs fails, the code's use of the db handle becomes stuck because of the failed transaction: the error is caught by the daemon's main loop error handler, but the db handle is not subjected to ROLLBACK and all future attempts to use it will fail.

So: move the LOCK TABLEs (and the SET TRANSACTION) into the catch, so that deadlocks in LOCK TABLEs are retried (after ROLLBACK).

The COMMIT remains outside the eval but this should be unaffected by DB deadlocks if the LOCK TABLEs are right.

Quoted 7 lines

Note that this code does not attempt to distinguish DB deadlock errors from other errors.  Arguably this is quite wrong.  Fixing it to distinguish deadlocks is awkward because pg_execute does not leave the error information anywhere it can be found.  Contrary to what the documentation seems to imply, it does not set errorCode (!)

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

#5 lore raw

PATCH 4/4 Database locking: Tcl: Limit number of retries

In reply to Ian Jackson

If there is something fundamentally wrong, don't just sit looping around every 500ms.

---
 tcl/JobDB-Executive.tcl |    6 ++++++
 1 file changed, 6 insertions(+)
tcl/JobDB-Executive.tcl +6 -0
index 8e45ea7..7dba497 100644
@@ -224,6 +224,8 @@ proc step-set-status {flight job stepno st} {
 }
 
 proc transaction {tables script} {
+    global errorInfo errorCode
+    set retries 100
     db-open
     while 1 {
         set ol {}
@@ -239,6 +241,10 @@ proc transaction {tables script} {
 	    } emsg]} {
 		puts "commit failed: $emsg; retrying ..."
 		db-execute ROLLBACK
+		if {[incr retries -1] <= 0} {
+		    error \
+ "commit failed, too many retries: $emsg\n$errorInfo\n$errorCode\n"
+		}
 		after 500
 		continue
 	    }
Signature · 1 line
1.7.10.4
#7 lore raw
In reply to Ian Jackson

Osstest/JobDB/Executive.pm sub begin_work ($$$) { #method · line 54

Quoted 6 lines · Ian Jackson

Osstest/JobDB/Executive.pm +5 -0
+sub need_retry ($$$) {
+    my ($jd, $dbh,$committing) = @_;
+    return
+	$dbh_tests->err()==7 &&
+	($dbh_tests->state =~ m/^40P01/); # DEADLOCK DETECTED

How come this return value doesn't need to include $committing in some way?

Also, "DEADLOCK DETECTED" presumably only occurs when fighting with some other client, as opposed to this client being broken and doing "LOCK A; ....; LOCK A"? Or if not we have a retry limit so such code won't just spin forever.

Ian.

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

#8 lore raw

Ian Campbell writes ("Re: [OSSTEST PATCH 1/4] Database locking: Perl: Retry all deadlocks in PostgreSQL"):

Quoted 8 lines · Ian Jackson

Osstest/JobDB/Executive.pm sub begin_work ($$$) { #method · line 54

Quoted 5 lines
Osstest/JobDB/Executive.pm +5 -0
+sub need_retry ($$$) {
+    my ($jd, $dbh,$committing) = @_;
+    return
+	$dbh_tests->err()==7 &&
+	($dbh_tests->state =~ m/^40P01/); # DEADLOCK DETECTED

How come this return value doesn't need to include $committing in some way?

$committing is just there as a fudge for the benefit of SQLite3, which only fails during COMMIT. In PostgreSQL we can always tell by the error code.

Quoted 4 lines

Also, "DEADLOCK DETECTED" presumably only occurs when fighting with some other client, as opposed to this client being broken and doing "LOCK A; ....; LOCK A"? Or if not we have a retry limit so such code won't just spin forever.

Databases (at least PostgreSQL) take care of all that kind of thing:
they will detect the deadlock. IDK what happens if you try to lock the same table twice in the same transaction but it will either work or fail with a deadlock error. If it fails with a deadlock error then as you say the retry limit will catch it.

(Deadlocks involving perhaps multiple processes, doing IPC outside the DB, and with multiple db connections, are not necessarily detectable by the DB. But this change does not make that possibility any worse.)

Ian.

#9 lore raw
Quoted 12 lines · Ian Jackson

Ian Campbell writes ("Re: [OSSTEST PATCH 1/4] Database locking: Perl:
Retry all deadlocks in PostgreSQL"):

Quoted 9 lines · Ian Jackson

Osstest/JobDB/Executive.pm sub begin_work ($$$) { #method · line 54

Quoted 5 lines
Osstest/JobDB/Executive.pm +5 -0
+sub need_retry ($$$) {
+    my ($jd, $dbh,$committing) = @_;
+    return
+	$dbh_tests->err()==7 &&
+	($dbh_tests->state =~ m/^40P01/); # DEADLOCK DETECTED

How come this return value doesn't need to include $committing in some way?

Quoted 3 lines

$committing is just there as a fudge for the benefit of SQLite3, which only fails during COMMIT.  In PostgreSQL we can always tell by the error code.

But the above doesn't check for the commit failed/conflict code either.

Ian.

_______________________________________________
Xen-devel mailing list
[email protected]
http://lists.xen.org/xen-devel

#10 lore raw
In reply to Ian Jackson

Ian Jackson writes ("Re: [OSSTEST PATCH 1/4] Database locking: Perl: Retry all deadlocks in PostgreSQL"):

Quoted 1 line

[stuff]

Thanks, we discussed this in person, and I have added your ack and force pushed it to osstest production.

The Massachusetts instance is currently broken because the ownerdaemon is broken. So I am going to update the owner and queue daemons, and restart everything, and then remove the Mass stop file.

The Cambridge instance doesn't have the SQL locking changes yet, but it would start testing the new osstest which might start to cause trouble. So I have dropped a stop file there now. When Cambridge has drained, probably tomorrow, I will update the daemons there (but not push anything to the main in-use trees).

Any other instances (eg, Intel?) running in Executive mode need to get the updates to the owner and queue daemons before starting to use the new osstest.git for actual test flights.

Ian.

#11 lore raw

Ian Jackson writes ("Re: [OSSTEST PATCH 1/4] Database locking: Perl: Retry all deadlocks in PostgreSQL"):

Quoted 3 lines

The Massachusetts instance is currently broken because the ownerdaemon is broken. So I am going to update the owner and queue daemons, and restart everything, and then remove the Mass stop file.

The Mass owner daemon did not start because it runs on the DB VM which:
* Did not have /home/osstest/.xen-osstest/settings
* Did not have libhtml-parser-perl installed
I have sorted this out.

Quoted 9 lines

The Cambridge instance doesn't have the SQL locking changes yet, but it would start testing the new osstest which might start to cause trouble. So I have dropped a stop file there now. When Cambridge has drained, probably tomorrow, I will update the daemons there (but not push anything to the main in-use trees).

Any other instances (eg, Intel?) running in Executive mode need to get the updates to the owner and queue daemons before starting to use the new osstest.git for actual test flights.

Ian.

#12 lore raw
Quoted 19 lines · Ian Jackson

Ian Jackson writes ("Re: [OSSTEST PATCH 1/4] Database locking: Perl: Retry all deadlocks in PostgreSQL"):

Quoted 3 lines

The Massachusetts instance is currently broken because the ownerdaemon is broken. So I am going to update the owner and queue daemons, and restart everything, and then remove the Mass stop file.

The Mass owner daemon did not start because it runs on the DB VM which:
* Did not have /home/osstest/.xen-osstest/settings
* Did not have libhtml-parser-perl installed
I have sorted this out.

Quoted 9 lines

The Cambridge instance doesn't have the SQL locking changes yet, but it would start testing the new osstest which might start to cause trouble. So I have dropped a stop file there now. When Cambridge has drained, probably tomorrow, I will update the daemons there (but not push anything to the main in-use trees).

Any other instances (eg, Intel?) running in Executive mode need to get the updates to the owner and queue daemons before starting to use the new osstest.git for actual test flights.

Thanks for your care, Ian. My side instances only run in Standalone mode.

Quoted 2 lines

Ian.