1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
13 "git.arvados.org/arvados.git/sdk/go/ctxlog"
14 "github.com/jmoiron/sqlx"
18 TrashSweep = &DBLocker{key: 10001}
19 retryDelay = 5 * time.Second
22 // DBLocker uses pg_advisory_lock to maintain a cluster-wide lock for
23 // a long-running task like "do X every N seconds".
24 type DBLocker struct {
28 getdb func(context.Context) (*sqlx.DB, error)
29 conn *sql.Conn // != nil if advisory lock has been acquired
32 // Lock acquires the advisory lock, waiting/reconnecting if needed.
33 func (dbl *DBLocker) Lock(ctx context.Context, getdb func(context.Context) (*sqlx.DB, error)) {
34 logger := ctxlog.FromContext(ctx)
35 for ; ; time.Sleep(retryDelay) {
38 // Another goroutine is already locked/waiting
39 // on this lock. Wait for them to release.
45 logger.WithError(err).Infof("error getting database pool")
49 conn, err := db.Conn(ctx)
51 logger.WithError(err).Info("error getting database connection")
56 err = conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock($1)`, dbl.key).Scan(&locked)
58 logger.WithError(err).Infof("error getting pg_try_advisory_lock %d", dbl.key)
68 logger.Debugf("acquired pg_advisory_lock %d", dbl.key)
69 dbl.ctx, dbl.getdb, dbl.conn = ctx, getdb, conn
75 // Check confirms that the lock is still active (i.e., the session is
76 // still alive), and re-acquires if needed. Panics if Lock is not
78 func (dbl *DBLocker) Check() {
80 err := dbl.conn.PingContext(dbl.ctx)
82 ctxlog.FromContext(dbl.ctx).Debugf("pg_advisory_lock %d connection still alive", dbl.key)
86 ctxlog.FromContext(dbl.ctx).WithError(err).Info("database connection ping failed")
89 ctx, getdb := dbl.ctx, dbl.getdb
94 func (dbl *DBLocker) Unlock() {
96 defer dbl.mtx.Unlock()
98 _, err := dbl.conn.ExecContext(context.Background(), `SELECT pg_advisory_unlock($1)`, dbl.key)
100 ctxlog.FromContext(dbl.ctx).WithError(err).Infof("error releasing pg_advisory_lock %d", dbl.key)
102 ctxlog.FromContext(dbl.ctx).Debugf("released pg_advisory_lock %d", dbl.key)