mirror of https://github.com/k3s-io/k3s
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
commit
70b3848bce
|
@ -11,7 +11,6 @@ go_library(
|
|||
name = "go_default_library",
|
||||
srcs = ["flock_unix.go"],
|
||||
tags = ["automanaged"],
|
||||
deps = ["//vendor:golang.org/x/sys/unix"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue