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 ContainerLogSweep = &DBLocker{key: 10002}
20 retryDelay = 5 * time.Second
23 // DBLocker uses pg_advisory_lock to maintain a cluster-wide lock for
24 // a long-running task like "do X every N seconds".
25 type DBLocker struct {
29 getdb func(context.Context) (*sqlx.DB, error)
30 conn *sql.Conn // != nil if advisory lock has been acquired
33 // Lock acquires the advisory lock, waiting/reconnecting if needed.
34 func (dbl *DBLocker) Lock(ctx context.Context, getdb func(context.Context) (*sqlx.DB, error)) {
35 logger := ctxlog.FromContext(ctx)
36 for ; ; time.Sleep(retryDelay) {
39 // Another goroutine is already locked/waiting
40 // on this lock. Wait for them to release.
46 logger.WithError(err).Infof("error getting database pool")
50 conn, err := db.Conn(ctx)
52 logger.WithError(err).Info("error getting database connection")
57 err = conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock($1)`, dbl.key).Scan(&locked)
59 logger.WithError(err).Infof("error getting pg_try_advisory_lock %d", dbl.key)
69 logger.Debugf("acquired pg_advisory_lock %d", dbl.key)
70 dbl.ctx, dbl.getdb, dbl.conn = ctx, getdb, conn
76 // Check confirms that the lock is still active (i.e., the session is
77 // still alive), and re-acquires if needed. Panics if Lock is not
79 func (dbl *DBLocker) Check() {
81 err := dbl.conn.PingContext(dbl.ctx)
83 ctxlog.FromContext(dbl.ctx).Debugf("pg_advisory_lock %d connection still alive", dbl.key)
87 ctxlog.FromContext(dbl.ctx).WithError(err).Info("database connection ping failed")
90 ctx, getdb := dbl.ctx, dbl.getdb
95 func (dbl *DBLocker) Unlock() {
97 defer dbl.mtx.Unlock()
99 _, err := dbl.conn.ExecContext(context.Background(), `SELECT pg_advisory_unlock($1)`, dbl.key)
101 ctxlog.FromContext(dbl.ctx).WithError(err).Infof("error releasing pg_advisory_lock %d", dbl.key)
103 ctxlog.FromContext(dbl.ctx).Debugf("released pg_advisory_lock %d", dbl.key)