Use per-user lock file when unlocking

This commit is contained in:
Daniel 2022-10-11 14:49:27 +02:00
parent 1144ac589b
commit 694dfb5b46
2 changed files with 22 additions and 19 deletions

View file

@ -3,6 +3,7 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/fs"
"log" "log"
"os" "os"
"os/user" "os/user"
@ -14,21 +15,7 @@ import (
) )
func checkAndCreateInstanceLock(path, name string, perUser bool) (pid int32, err error) { func checkAndCreateInstanceLock(path, name string, perUser bool) (pid int32, err error) {
var lockFilePath string lockFilePath := getLockFilePath(path, name, perUser)
if perUser {
// Get user ID for per-user lock file.
var userID string
usr, err := user.Current()
if err != nil {
log.Printf("failed to get current user: %s\n", err)
userID = "no-user"
} else {
userID = usr.Uid
}
lockFilePath = filepath.Join(dataRoot.Path, path, fmt.Sprintf("%s-%s-lock.pid", name, userID))
} else {
lockFilePath = filepath.Join(dataRoot.Path, path, fmt.Sprintf("%s-lock.pid", name))
}
// read current pid file // read current pid file
data, err := os.ReadFile(lockFilePath) data, err := os.ReadFile(lockFilePath)
@ -100,7 +87,23 @@ func createInstanceLock(lockFilePath string) error {
return nil return nil
} }
func deleteInstanceLock(path, name string) error { func deleteInstanceLock(path, name string, perUser bool) error {
lockFilePath := filepath.Join(dataRoot.Path, path, fmt.Sprintf("%s-lock.pid", name)) return os.Remove(getLockFilePath(path, name, perUser))
return os.Remove(lockFilePath) }
func getLockFilePath(path, name string, perUser bool) string {
if !perUser {
return filepath.Join(dataRoot.Path, path, fmt.Sprintf("%s-lock.pid", name))
}
// Get user ID for per-user lock file.
var userID string
usr, err := user.Current()
if err != nil {
log.Printf("failed to get current user: %s\n", err)
userID = "no-user"
} else {
userID = usr.Uid
}
return filepath.Join(dataRoot.Path, path, fmt.Sprintf("%s-%s-lock.pid", name, userID))
} }

View file

@ -172,7 +172,7 @@ func run(opts *Options, cmdArgs []string) (err error) {
return fmt.Errorf("another instance of %s is already running: PID %d", opts.Name, pid) return fmt.Errorf("another instance of %s is already running: PID %d", opts.Name, pid)
} }
defer func() { defer func() {
err := deleteInstanceLock(opts.LockPathPrefix, opts.ShortIdentifier) err := deleteInstanceLock(opts.LockPathPrefix, opts.ShortIdentifier, opts.LockPerUser)
if err != nil { if err != nil {
log.Printf("failed to delete instance lock: %s\n", err) log.Printf("failed to delete instance lock: %s\n", err)
} }