Skip to content

Commit

Permalink
Refactor tryLock
Browse files Browse the repository at this point in the history
simplify `locked` at the expenso of adding a boolean arg to tryLock.

Signed-off-by: Natanael Copa <ncopa@mirantis.com>
  • Loading branch information
ncopa committed Jan 20, 2025
1 parent 1c3f2a7 commit 3511d3f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
33 changes: 18 additions & 15 deletions pkg/config/flock_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,35 @@ limitations under the License.
package config

import (
"errors"
"golang.org/x/sys/unix"
"os"
"path/filepath"
)

// tryLock attempts to acquire the lock. Returns *os.File if successful, nil otherwise.
func tryLock(path string) (*os.File, error) {
func tryLock(path string, exclusive bool) (*os.File, error) {
fullPath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
file, err := os.OpenFile(fullPath, os.O_CREATE|os.O_RDWR, 0600)
mode := os.O_RDWR
if exclusive {
mode |= os.O_CREATE
}
file, err := os.OpenFile(fullPath, mode, 0600)
if err != nil {
return nil, err
}

if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
flockMode := unix.LOCK_NB
if exclusive {
flockMode |= unix.LOCK_EX
} else {
flockMode |= unix.LOCK_SH
}

if err := unix.Flock(int(file.Fd()), flockMode); err != nil {
_ = file.Close()
if err == unix.EWOULDBLOCK {
return nil, ErrK0sAlreadyRunning // Lock is already held by another process
Expand All @@ -47,19 +59,10 @@ func tryLock(path string) (*os.File, error) {

// locked checks if the lock is currently held by another process.
func locked(path string) bool {
file, err := os.OpenFile(path, os.O_RDWR, 0600)
f, err := tryLock(path, false)
if err != nil {
return false
}
defer file.Close()

// Attempt a non-blocking shared lock to test the lock state
if err := unix.Flock(int(file.Fd()), unix.LOCK_SH|unix.LOCK_NB); err != nil {
if err == unix.EWOULDBLOCK {
return true
}
return false
return errors.Is(err, ErrK0sAlreadyRunning)
}

f.Close()
return false
}
2 changes: 1 addition & 1 deletion pkg/config/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func NewRuntimeConfig(k0sVars *CfgVars) (*RuntimeConfig, error) {
//
// It works similar on Windows, but with LockFileEx

lockFile, err := tryLock(k0sVars.RuntimeConfigPath + ".lock")
lockFile, err := tryLock(k0sVars.RuntimeConfigPath+".lock", true)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 3511d3f

Please sign in to comment.