flock.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Copyright 2016 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package fileutil
  14. import (
  15. "os"
  16. "path/filepath"
  17. )
  18. // Releaser provides the Release method to release a file lock.
  19. type Releaser interface {
  20. Release() error
  21. }
  22. // Flock locks the file with the provided name. If the file does not exist, it is
  23. // created. The returned Releaser is used to release the lock. existed is true
  24. // if the file to lock already existed. A non-nil error is returned if the
  25. // locking has failed. Neither this function nor the returned Releaser is
  26. // goroutine-safe.
  27. func Flock(fileName string) (r Releaser, existed bool, err error) {
  28. if err = os.MkdirAll(filepath.Dir(fileName), 0755); err != nil {
  29. return nil, false, err
  30. }
  31. _, err = os.Stat(fileName)
  32. existed = err == nil
  33. r, err = newLock(fileName)
  34. return r, existed, err
  35. }