Files

43 lines
1.3 KiB
Nim

## Data-dir lock (DESIGN 3.2 / 11.1, #17): the running server holds an exclusive advisory lock on
## `<stateDir>/instance.lock`; `fff-vtt gm-key --new` must not rotate under a live server.
## POSIX fcntl(F_SETLK) write lock: process-scoped, released when the fd is closed or the process exits.
import std/[os, posix]
const InstanceLockName* = "instance.lock"
type
InstanceLock* = object
path*: string
fd*: cint
held*: bool
proc tryAcquire*(stateDir: string): InstanceLock =
result.path = stateDir / InstanceLockName
let fd = open(result.path.cstring, O_RDWR or O_CREAT, Mode(0o600))
if fd < 0: return
var fl: Tflock
fl.l_type = cshort(F_WRLCK)
fl.l_whence = cshort(SEEK_SET)
fl.l_start = 0
fl.l_len = 0
if fcntl(fd, F_SETLK, addr fl) == 0:
result.fd = fd
result.held = true
# Record the holder for humans; the lock, not the content, is the protocol.
discard ftruncate(fd, 0)
let pid = $getCurrentProcessId() & "\n"
discard posix.write(fd, pid.cstring, pid.len)
else:
discard posix.close(fd)
proc release*(l: var InstanceLock) =
if l.held:
var fl: Tflock
fl.l_type = cshort(F_UNLCK)
fl.l_whence = cshort(SEEK_SET)
fl.l_start = 0
fl.l_len = 0
discard fcntl(l.fd, F_SETLK, addr fl)
discard posix.close(l.fd)
l.held = false