From a489bd26740136aed04b2a67bc14562c74dc06d3 Mon Sep 17 00:00:00 2001 From: Yifan Gu Date: Fri, 10 Mar 2017 16:52:00 -0800 Subject: [PATCH] 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. --- pkg/util/flock/BUILD | 1 - pkg/util/flock/flock_unix.go | 32 ++++++++------------------------ 2 files changed, 8 insertions(+), 25 deletions(-) diff --git a/pkg/util/flock/BUILD b/pkg/util/flock/BUILD index b9c41288847..640563db950 100644 --- a/pkg/util/flock/BUILD +++ b/pkg/util/flock/BUILD @@ -11,7 +11,6 @@ go_library( name = "go_default_library", srcs = ["flock_unix.go"], tags = ["automanaged"], - deps = ["//vendor:golang.org/x/sys/unix"], ) filegroup( diff --git a/pkg/util/flock/flock_unix.go b/pkg/util/flock/flock_unix.go index 73a608020e7..d59afd4becb 100644 --- a/pkg/util/flock/flock_unix.go +++ b/pkg/util/flock/flock_unix.go @@ -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) }