From 532f55d640ec0ab2cb3f352c8e449e9351522344 Mon Sep 17 00:00:00 2001 From: Gibheer Date: Tue, 9 Apr 2019 09:51:52 +0200 Subject: fix idle in transaction It happend all the time, that connections were hanging in idle in transaction state. This was caused by a rollback stuck behind a sleep loop to wait for the next bunch of checks to run. This also replaces a Query() call with QueryRow, as we only expect a single row and this cleans up the code a bit. --- cmd/moncheck/main.go | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) (limited to 'cmd/moncheck/main.go') diff --git a/cmd/moncheck/main.go b/cmd/moncheck/main.go index 3080309..7253c07 100644 --- a/cmd/moncheck/main.go +++ b/cmd/moncheck/main.go @@ -87,7 +87,7 @@ func check(thread int, db *sql.DB, waitDuration, timeout time.Duration, hostname log.Printf("[%d] could not start transaction: %s", thread, err) continue } - rows, err := tx.Query(`select check_id, cmdLine, states, mapping_id + row := tx.QueryRow(`select check_id, cmdLine, states, mapping_id from active_checks where next_time < now() and enabled @@ -106,25 +106,15 @@ func check(thread int, db *sql.DB, waitDuration, timeout time.Duration, hostname mapId int state int ) - found := false - for rows.Next() { - if err := rows.Err(); err != nil { - log.Printf("could not fetch row: %s", err) - tx.Rollback() - break - } - err := rows.Scan(&id, pq.Array(&cmdLine), &states, &mapId) - if err != nil { - log.Printf("could not scan values: %s", err) - tx.Rollback() - break - } - found = true - } - if !found { - time.Sleep(waitDuration) + err = row.Scan(&id, pq.Array(&cmdLine), &states, &mapId) + if err != nil && err == sql.ErrNoRows { tx.Rollback() + time.Sleep(waitDuration) continue + } else if err != nil { + log.Printf("could not scan values: %s", err) + tx.Rollback() + break } ctx, cancel := context.WithTimeout(context.Background(), timeout) cmd := exec.CommandContext(ctx, cmdLine[0], cmdLine[1:]...) -- cgit v1.2.3-70-g09d2