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 // Already locked by another caller in this
39 // process. 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")
55 _, err = conn.ExecContext(ctx, `SELECT pg_advisory_lock($1)`, dbl.key)
57 logger.WithError(err).Infof("error getting pg_advisory_lock %d", dbl.key)
62 logger.Debugf("acquired pg_advisory_lock %d", dbl.key)
63 dbl.ctx, dbl.getdb, dbl.conn = ctx, getdb, conn
69 // Check confirms that the lock is still active (i.e., the session is
70 // still alive), and re-acquires if needed. Panics if Lock is not
72 func (dbl *DBLocker) Check() {
74 err := dbl.conn.PingContext(dbl.ctx)
76 ctxlog.FromContext(dbl.ctx).Debugf("pg_advisory_lock %d connection still alive", dbl.key)
80 ctxlog.FromContext(dbl.ctx).WithError(err).Info("database connection ping failed")
83 ctx, getdb := dbl.ctx, dbl.getdb
88 func (dbl *DBLocker) Unlock() {
90 defer dbl.mtx.Unlock()
92 _, err := dbl.conn.ExecContext(context.Background(), `SELECT pg_advisory_unlock($1)`, dbl.key)
94 ctxlog.FromContext(dbl.ctx).WithError(err).Infof("error releasing pg_advisory_lock %d", dbl.key)
96 ctxlog.FromContext(dbl.ctx).Debugf("released pg_advisory_lock %d", dbl.key)