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)
| 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. |
| 28 | func 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. |
| 66 | func (l *InstanceLock) Release() error { |
nothing calls this directly
no test coverage detected