2016-11-16 03:46:24 +00:00
|
|
|
package content
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/nightlyone/lockfile"
|
2017-02-17 08:07:02 +00:00
|
|
|
"github.com/pkg/errors"
|
2016-11-16 03:46:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// In addition to providing inter-process locks for content ingest, we also
|
|
|
|
// define a global in process lock to prevent two goroutines writing to the
|
|
|
|
// same file.
|
|
|
|
//
|
2017-01-19 04:27:51 +00:00
|
|
|
// This is pretty unsophisticated for now. In the future, we'd probably like to
|
2016-11-16 03:46:24 +00:00
|
|
|
// have more information about who is holding which locks, as well as better
|
|
|
|
// error reporting.
|
|
|
|
|
|
|
|
var (
|
2017-02-17 08:07:02 +00:00
|
|
|
errLocked = errors.New("key is locked")
|
|
|
|
|
2016-11-16 03:46:24 +00:00
|
|
|
// locks lets us lock in process, as well as output of process.
|
|
|
|
locks = map[lockfile.Lockfile]struct{}{}
|
|
|
|
locksMu sync.Mutex
|
|
|
|
)
|
|
|
|
|
|
|
|
func tryLock(lock lockfile.Lockfile) error {
|
|
|
|
locksMu.Lock()
|
|
|
|
defer locksMu.Unlock()
|
|
|
|
|
|
|
|
if _, ok := locks[lock]; ok {
|
2017-02-17 08:07:02 +00:00
|
|
|
return errLocked
|
2016-11-16 03:46:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := lock.TryLock(); err != nil {
|
2017-02-17 08:07:02 +00:00
|
|
|
if errors.Cause(err) == lockfile.ErrBusy {
|
|
|
|
return errLocked
|
|
|
|
}
|
|
|
|
|
|
|
|
return errors.Wrapf(err, "lock.TryLock() encountered an error")
|
2016-11-16 03:46:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
locks[lock] = struct{}{}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func unlock(lock lockfile.Lockfile) error {
|
|
|
|
locksMu.Lock()
|
|
|
|
defer locksMu.Unlock()
|
|
|
|
|
|
|
|
if _, ok := locks[lock]; !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
delete(locks, lock)
|
|
|
|
return lock.Unlock()
|
|
|
|
}
|