lock_plan9.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package fileutil
  15. import (
  16. "errors"
  17. "os"
  18. "syscall"
  19. "time"
  20. )
  21. var (
  22. ErrLocked = errors.New("file already locked")
  23. )
  24. type Lock interface {
  25. Name() string
  26. TryLock() error
  27. Lock() error
  28. Unlock() error
  29. Destroy() error
  30. }
  31. type lock struct {
  32. fname string
  33. file *os.File
  34. }
  35. func (l *lock) Name() string {
  36. return l.fname
  37. }
  38. // TryLock acquires exclusivity on the lock without blocking
  39. func (l *lock) TryLock() error {
  40. err := os.Chmod(l.fname, syscall.DMEXCL|0600)
  41. if err != nil {
  42. return err
  43. }
  44. f, err := os.Open(l.fname)
  45. if err != nil {
  46. return ErrLocked
  47. }
  48. l.file = f
  49. return nil
  50. }
  51. // Lock acquires exclusivity on the lock with blocking
  52. func (l *lock) Lock() error {
  53. err := os.Chmod(l.fname, syscall.DMEXCL|0600)
  54. if err != nil {
  55. return err
  56. }
  57. for {
  58. f, err := os.Open(l.fname)
  59. if err == nil {
  60. l.file = f
  61. return nil
  62. }
  63. time.Sleep(10 * time.Millisecond)
  64. }
  65. }
  66. // Unlock unlocks the lock
  67. func (l *lock) Unlock() error {
  68. return l.file.Close()
  69. }
  70. func (l *lock) Destroy() error {
  71. return nil
  72. }
  73. func NewLock(file string) (Lock, error) {
  74. l := &lock{fname: file}
  75. return l, nil
  76. }