database: add FindLock dbutil

This commit is contained in:
Jimmy Zelinskie 2018-11-28 13:37:15 -05:00
parent 4fbeb9ced5
commit 300bb52696
2 changed files with 25 additions and 12 deletions

View File

@ -15,6 +15,7 @@
package database package database
import ( import (
"errors"
"time" "time"
"github.com/deckarep/golang-set" "github.com/deckarep/golang-set"
@ -350,3 +351,24 @@ func ReleaseLock(datastore Datastore, name, owner string) {
return return
} }
} }
// ErrLockNotFound is returned when FindLock succeeds, but cannot find a lock.
var ErrLockNotFound = errors.New("no lock was found")
// FindLock determines if a global lock with the provided name already exists.
func FindLock(datastore Datastore, updaterLockName string) (owner string, expiration time.Time, err error) {
var tx Session
tx, err = datastore.Begin()
if err != nil {
return
}
defer tx.Rollback()
var found bool
owner, expiration, found, err = tx.FindLock(updaterLockName)
if err != nil && !found {
err = ErrLockNotFound
}
return
}

View File

@ -142,9 +142,9 @@ func RunUpdater(config *UpdaterConfig, datastore database.Datastore, st *stopper
} }
continue continue
} else { } else {
lockOwner, lockExpiration, ok, err := findLock(datastore, updaterLockName) lockOwner, lockExpiration, err := database.FindLock(datastore, updaterLockName)
if !ok || err != nil { if err != nil {
log.Debug("update lock is already taken") log.WithError(err).Warn("failed to find update lock")
nextUpdate = hasLockUntil nextUpdate = hasLockUntil
} else { } else {
log.WithFields(log.Fields{"lock owner": lockOwner, "lock expiration": lockExpiration}).Debug("update lock is already taken") log.WithFields(log.Fields{"lock owner": lockOwner, "lock expiration": lockExpiration}).Debug("update lock is already taken")
@ -464,15 +464,6 @@ func doVulnerabilitiesNamespacing(vulnerabilities []database.VulnerabilityWithAf
return response return response
} }
func findLock(datastore database.Datastore, updaterLockName string) (string, time.Time, bool, error) {
tx, err := datastore.Begin()
if err != nil {
log.WithError(err).Error()
}
defer tx.Rollback()
return tx.FindLock(updaterLockName)
}
// updateUpdaterFlags updates the flags specified by updaters, every transaction // updateUpdaterFlags updates the flags specified by updaters, every transaction
// is independent of each other. // is independent of each other.
func updateUpdaterFlags(datastore database.Datastore, flags map[string]string) error { func updateUpdaterFlags(datastore database.Datastore, flags map[string]string) error {