Merge pull request #42935 from yifan-gu/fix_flock

Automatic merge from submit-queue (batch tested with PRs 42942, 42935)

pkg/util/flock: Fix the flock so it actually locks.

With this PR, the second call to `Acquire()` will block unless the lock is released (process exits).
Also removed the memory mutex in the previous code since we don't need `Release()` here so no need to save and protect the local fd.

Fix #42929.
pull/6/head
Kubernetes Submit Queue 2017-03-14 10:19:18 -07:00 committed by GitHub
commit 70b3848bce
2 changed files with 8 additions and 25 deletions

View File

@ -11,7 +11,6 @@ go_library(
name = "go_default_library",
srcs = ["flock_unix.go"],
tags = ["automanaged"],
deps = ["//vendor:golang.org/x/sys/unix"],
)
filegroup(

View File

@ -18,34 +18,18 @@ limitations under the License.
package flock
import (
"os"
"sync"
"golang.org/x/sys/unix"
)
var (
// lock guards lockfile. Assignment is not atomic.
lock sync.Mutex
// os.File has a runtime.Finalizer so the fd will be closed if the struct
// is garbage collected. Let's hold onto a reference so that doesn't happen.
lockfile *os.File
)
import "syscall"
// Acquire acquires a lock on a file for the duration of the process. This method
// is reentrant.
func Acquire(path string) error {
lock.Lock()
defer lock.Unlock()
var err error
if lockfile, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600); err != nil {
fd, err := syscall.Open(path, syscall.O_CREAT|syscall.O_RDWR, 0600)
if err != nil {
return err
}
defer lockfile.Close()
opts := unix.Flock_t{Type: unix.F_WRLCK}
if err := unix.FcntlFlock(lockfile.Fd(), unix.F_SETLKW, &opts); err != nil {
return err
}
return nil
// We don't need to close the fd since we should hold
// it until the process exits.
return syscall.Flock(fd, syscall.LOCK_EX)
}