From 300bb52696036dce96ee360f4431837e6ee452a2 Mon Sep 17 00:00:00 2001 From: Jimmy Zelinskie Date: Wed, 28 Nov 2018 13:37:15 -0500 Subject: [PATCH] database: add FindLock dbutil --- database/dbutil.go | 22 ++++++++++++++++++++++ updater.go | 15 +++------------ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/database/dbutil.go b/database/dbutil.go index 31d48503..d02286a9 100644 --- a/database/dbutil.go +++ b/database/dbutil.go @@ -15,6 +15,7 @@ package database import ( + "errors" "time" "github.com/deckarep/golang-set" @@ -350,3 +351,24 @@ func ReleaseLock(datastore Datastore, name, owner string) { 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 +} diff --git a/updater.go b/updater.go index 1ab7700d..6bded33a 100644 --- a/updater.go +++ b/updater.go @@ -142,9 +142,9 @@ func RunUpdater(config *UpdaterConfig, datastore database.Datastore, st *stopper } continue } else { - lockOwner, lockExpiration, ok, err := findLock(datastore, updaterLockName) - if !ok || err != nil { - log.Debug("update lock is already taken") + lockOwner, lockExpiration, err := database.FindLock(datastore, updaterLockName) + if err != nil { + log.WithError(err).Warn("failed to find update lock") nextUpdate = hasLockUntil } else { 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 } -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 // is independent of each other. func updateUpdaterFlags(datastore database.Datastore, flags map[string]string) error {