MCPcopy Create free account
hub / github.com/Thunder-Compute/thunder-cli / AcquireInstanceLock

Function AcquireInstanceLock

utils/lockfile.go:28–63  ·  view source on GitHub ↗

AcquireInstanceLock attempts to acquire an exclusive lock for the given instance. Returns an InstanceLock if successful, or an error if the lock cannot be acquired. Uses O_EXCL for atomicity; stale locks (>30 min or dead process) are automatically cleaned up.

(instanceID string)

Source from the content-addressed store, hash-verified

26// Returns an InstanceLock if successful, or an error if the lock cannot be acquired.
27// Uses O_EXCL for atomicity; stale locks (>30 min or dead process) are automatically cleaned up.
28func AcquireInstanceLock(instanceID string) (*InstanceLock, error) {
29 lockDir := GetLockDir()
30 if err := os.MkdirAll(lockDir, 0700); err != nil {
31 return nil, fmt.Errorf("failed to create locks directory: %w", err)
32 }
33
34 lockPath := GetInstanceLockPath(instanceID)
35
36 if data, err := os.ReadFile(lockPath); err == nil {
37 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
38 if len(lines) >= 2 {
39 if pid, err := strconv.Atoi(lines[0]); err == nil {
40 if timestamp, err := strconv.ParseInt(lines[1], 10, 64); err == nil {
41 lockAge := time.Since(time.Unix(timestamp, 0))
42 if isProcessAlive(pid) && lockAge < 30*time.Minute {
43 return nil, fmt.Errorf("another 'tnr connect' session is already in progress for this instance")
44 }
45 }
46 }
47 }
48 _ = os.Remove(lockPath) // Stale lock
49 }
50
51 file, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
52 if err != nil {
53 if os.IsExist(err) {
54 return nil, fmt.Errorf("another 'tnr connect' session is already in progress for this instance")
55 }
56 return nil, fmt.Errorf("failed to create lock file: %w", err)
57 }
58
59 _, _ = file.WriteString(fmt.Sprintf("%d\n%d\n", os.Getpid(), time.Now().Unix()))
60 file.Close()
61
62 return &InstanceLock{lockPath: lockPath}, nil
63}
64
65// Release releases the instance lock and removes the lock file.
66func (l *InstanceLock) Release() error {

Callers

nothing calls this directly

Calls 6

GetLockDirFunction · 0.85
GetInstanceLockPathFunction · 0.85
isProcessAliveFunction · 0.85
MkdirAllMethod · 0.65
ReadFileMethod · 0.65
CloseMethod · 0.65

Tested by

no test coverage detected