mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-07-23 03:41:45 +00:00
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.
This commit is contained in:
commit
70b3848bce
@ -11,7 +11,6 @@ go_library(
|
|||||||
name = "go_default_library",
|
name = "go_default_library",
|
||||||
srcs = ["flock_unix.go"],
|
srcs = ["flock_unix.go"],
|
||||||
tags = ["automanaged"],
|
tags = ["automanaged"],
|
||||||
deps = ["//vendor:golang.org/x/sys/unix"],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
filegroup(
|
filegroup(
|
||||||
|
@ -18,34 +18,18 @@ limitations under the License.
|
|||||||
|
|
||||||
package flock
|
package flock
|
||||||
|
|
||||||
import (
|
import "syscall"
|
||||||
"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
|
|
||||||
)
|
|
||||||
|
|
||||||
// Acquire acquires a lock on a file for the duration of the process. This method
|
// Acquire acquires a lock on a file for the duration of the process. This method
|
||||||
// is reentrant.
|
// is reentrant.
|
||||||
func Acquire(path string) error {
|
func Acquire(path string) error {
|
||||||
lock.Lock()
|
fd, err := syscall.Open(path, syscall.O_CREAT|syscall.O_RDWR, 0600)
|
||||||
defer lock.Unlock()
|
if err != nil {
|
||||||
var err error
|
|
||||||
if lockfile, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer lockfile.Close()
|
|
||||||
opts := unix.Flock_t{Type: unix.F_WRLCK}
|
// We don't need to close the fd since we should hold
|
||||||
if err := unix.FcntlFlock(lockfile.Fd(), unix.F_SETLKW, &opts); err != nil {
|
// it until the process exits.
|
||||||
return err
|
|
||||||
}
|
return syscall.Flock(fd, syscall.LOCK_EX)
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user