locks.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. Copyright The containerd Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package local
  14. import (
  15. "sync"
  16. "time"
  17. "github.com/containerd/containerd/errdefs"
  18. "github.com/pkg/errors"
  19. )
  20. // Handles locking references
  21. type lock struct {
  22. since time.Time
  23. }
  24. var (
  25. // locks lets us lock in process
  26. locks = make(map[string]*lock)
  27. locksMu sync.Mutex
  28. )
  29. func tryLock(ref string) error {
  30. locksMu.Lock()
  31. defer locksMu.Unlock()
  32. if v, ok := locks[ref]; ok {
  33. return errors.Wrapf(errdefs.ErrUnavailable, "ref %s locked since %s", ref, v.since)
  34. }
  35. locks[ref] = &lock{time.Now()}
  36. return nil
  37. }
  38. func unlock(ref string) {
  39. locksMu.Lock()
  40. defer locksMu.Unlock()
  41. delete(locks, ref)
  42. }