File size: 11,934 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | /**
* PID-Based Version Locking
*
* This module provides PID-based locking for running Claude Code versions.
* Unlike mtime-based locking (which can hold locks for 30 days after a crash),
* PID-based locking can immediately detect when a process is no longer running.
*
* Lock files contain JSON with the PID and metadata, and staleness is determined
* by checking if the process is still alive.
*/
import { basename, join } from 'path'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
import { logForDebugging } from '../debug.js'
import { isEnvDefinedFalsy, isEnvTruthy } from '../envUtils.js'
import { isENOENT, toError } from '../errors.js'
import { getFsImplementation } from '../fsOperations.js'
import { getProcessCommand } from '../genericProcessUtils.js'
import { logError } from '../log.js'
import {
jsonParse,
jsonStringify,
writeFileSync_DEPRECATED,
} from '../slowOperations.js'
/**
* Check if PID-based version locking is enabled.
* When disabled, falls back to mtime-based locking (30-day timeout).
*
* Controlled by GrowthBook gate with local override:
* - Set ENABLE_PID_BASED_VERSION_LOCKING=true to force-enable
* - Set ENABLE_PID_BASED_VERSION_LOCKING=false to force-disable
* - If unset, GrowthBook gate (tengu_pid_based_version_locking) controls rollout
*/
export function isPidBasedLockingEnabled(): boolean {
const envVar = process.env.ENABLE_PID_BASED_VERSION_LOCKING
// If env var is explicitly set, respect it
if (isEnvTruthy(envVar)) {
return true
}
if (isEnvDefinedFalsy(envVar)) {
return false
}
// GrowthBook controls gradual rollout (returns false for external users)
return getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_pid_based_version_locking',
false,
)
}
/**
* Content stored in a version lock file
*/
export type VersionLockContent = {
pid: number
version: string
execPath: string
acquiredAt: number // timestamp when lock was acquired
}
/**
* Information about a lock for diagnostic purposes
*/
export type LockInfo = {
version: string
pid: number
isProcessRunning: boolean
execPath: string
acquiredAt: Date
lockFilePath: string
}
// Fallback stale timeout (2 hours) - used when PID check is inconclusive
// This is much shorter than the previous 30-day timeout but still allows
// for edge cases like network filesystems where PID check might fail
const FALLBACK_STALE_MS = 2 * 60 * 60 * 1000
/**
* Check if a process with the given PID is currently running
* Uses signal 0 which doesn't actually send a signal but checks if we can
*/
export function isProcessRunning(pid: number): boolean {
// PID 0 is special - it refers to the current process group, not a real process
// PID 1 is init/systemd and is always running but shouldn't be considered for locks
if (pid <= 1) {
return false
}
try {
process.kill(pid, 0)
return true
} catch {
return false
}
}
/**
* Validate that a running process is actually a Claude process
* This helps mitigate PID reuse issues
*/
function isClaudeProcess(pid: number, expectedExecPath: string): boolean {
if (!isProcessRunning(pid)) {
return false
}
// If the PID matches our current process, we know it's valid
// This handles test environments where the command might not contain 'claude'
if (pid === process.pid) {
return true
}
try {
const command = getProcessCommand(pid)
if (!command) {
// If we can't get the command, trust the PID check
// This is conservative - we'd rather not delete a running version
return true
}
// Check if the command contains 'claude' or the expected exec path
const normalizedCommand = command.toLowerCase()
const normalizedExecPath = expectedExecPath.toLowerCase()
return (
normalizedCommand.includes('claude') ||
normalizedCommand.includes(normalizedExecPath)
)
} catch {
// If command check fails, trust the PID check
return true
}
}
/**
* Read and parse a lock file's content
*/
export function readLockContent(
lockFilePath: string,
): VersionLockContent | null {
const fs = getFsImplementation()
try {
const content = fs.readFileSync(lockFilePath, { encoding: 'utf8' })
if (!content || content.trim() === '') {
return null
}
const parsed = jsonParse(content) as VersionLockContent
// Validate required fields
if (typeof parsed.pid !== 'number' || !parsed.version || !parsed.execPath) {
return null
}
return parsed
} catch {
return null
}
}
/**
* Check if a lock file represents an active lock (process still running)
*/
export function isLockActive(lockFilePath: string): boolean {
const content = readLockContent(lockFilePath)
if (!content) {
return false
}
const { pid, execPath } = content
// Primary check: is the process running?
if (!isProcessRunning(pid)) {
return false
}
// Secondary validation: is it actually a Claude process?
// This helps with PID reuse scenarios
if (!isClaudeProcess(pid, execPath)) {
logForDebugging(
`Lock PID ${pid} is running but does not appear to be Claude - treating as stale`,
)
return false
}
// Fallback: if the lock is very old (> 2 hours) and we can't validate
// the command, be conservative and consider it potentially stale
// This handles edge cases like network filesystems
const fs = getFsImplementation()
try {
const stats = fs.statSync(lockFilePath)
const age = Date.now() - stats.mtimeMs
if (age > FALLBACK_STALE_MS) {
// Double-check that we can still see the process
if (!isProcessRunning(pid)) {
return false
}
}
} catch {
// If we can't stat the file, trust the PID check
}
return true
}
/**
* Write lock content to a file atomically
*/
function writeLockFile(
lockFilePath: string,
content: VersionLockContent,
): void {
const fs = getFsImplementation()
const tempPath = `${lockFilePath}.tmp.${process.pid}.${Date.now()}`
try {
writeFileSync_DEPRECATED(tempPath, jsonStringify(content, null, 2), {
encoding: 'utf8',
flush: true,
})
fs.renameSync(tempPath, lockFilePath)
} catch (error) {
// Clean up temp file on failure (best-effort)
try {
fs.unlinkSync(tempPath)
} catch {
// Ignore cleanup errors (ENOENT expected if write failed before file creation)
}
throw error
}
}
/**
* Try to acquire a lock on a version file
* Returns a release function if successful, null if the lock is already held
*/
export async function tryAcquireLock(
versionPath: string,
lockFilePath: string,
): Promise<(() => void) | null> {
const fs = getFsImplementation()
const versionName = basename(versionPath)
// Check if there's an existing active lock (including by our own process)
// Use isLockActive for consistency with cleanup - it checks both PID running AND
// validates it's actually a Claude process (to handle PID reuse scenarios)
if (isLockActive(lockFilePath)) {
const existingContent = readLockContent(lockFilePath)
logForDebugging(
`Cannot acquire lock for ${versionName} - held by PID ${existingContent?.pid}`,
)
return null
}
// Try to acquire the lock
const lockContent: VersionLockContent = {
pid: process.pid,
version: versionName,
execPath: process.execPath,
acquiredAt: Date.now(),
}
try {
writeLockFile(lockFilePath, lockContent)
// Verify we actually got the lock (race condition check)
const verifyContent = readLockContent(lockFilePath)
if (verifyContent?.pid !== process.pid) {
// Another process won the race
return null
}
logForDebugging(`Acquired PID lock for ${versionName} (PID ${process.pid})`)
// Return release function
return () => {
try {
// Only release if we still own the lock
const currentContent = readLockContent(lockFilePath)
if (currentContent?.pid === process.pid) {
fs.unlinkSync(lockFilePath)
logForDebugging(`Released PID lock for ${versionName}`)
}
} catch (error) {
logForDebugging(`Failed to release lock for ${versionName}: ${error}`)
}
}
} catch (error) {
logForDebugging(`Failed to acquire lock for ${versionName}: ${error}`)
return null
}
}
/**
* Acquire a lock and hold it for the lifetime of the process
* This is used for locking the currently running version
*/
export async function acquireProcessLifetimeLock(
versionPath: string,
lockFilePath: string,
): Promise<boolean> {
const release = await tryAcquireLock(versionPath, lockFilePath)
if (!release) {
return false
}
// Register cleanup on process exit
const cleanup = () => {
try {
release()
} catch {
// Ignore errors during process exit
}
}
process.on('exit', cleanup)
process.on('SIGINT', cleanup)
process.on('SIGTERM', cleanup)
// Don't call release() - we want to hold the lock until process exits
return true
}
/**
* Execute a callback while holding a lock
* Returns true if the callback executed, false if lock couldn't be acquired
*/
export async function withLock(
versionPath: string,
lockFilePath: string,
callback: () => void | Promise<void>,
): Promise<boolean> {
const release = await tryAcquireLock(versionPath, lockFilePath)
if (!release) {
return false
}
try {
await callback()
return true
} finally {
release()
}
}
/**
* Get information about all version locks for diagnostics
*/
export function getAllLockInfo(locksDir: string): LockInfo[] {
const fs = getFsImplementation()
const lockInfos: LockInfo[] = []
try {
const lockFiles = fs
.readdirStringSync(locksDir)
.filter((f: string) => f.endsWith('.lock'))
for (const lockFile of lockFiles) {
const lockFilePath = join(locksDir, lockFile)
const content = readLockContent(lockFilePath)
if (content) {
lockInfos.push({
version: content.version,
pid: content.pid,
isProcessRunning: isProcessRunning(content.pid),
execPath: content.execPath,
acquiredAt: new Date(content.acquiredAt),
lockFilePath,
})
}
}
} catch (error) {
if (isENOENT(error)) {
return lockInfos
}
logError(toError(error))
}
return lockInfos
}
/**
* Clean up stale locks (locks where the process is no longer running)
* Returns the number of locks cleaned up
*
* Handles both:
* - PID-based locks (files containing JSON with PID)
* - Legacy proper-lockfile locks (directories created by mtime-based locking)
*/
export function cleanupStaleLocks(locksDir: string): number {
const fs = getFsImplementation()
let cleanedCount = 0
try {
const lockEntries = fs
.readdirStringSync(locksDir)
.filter((f: string) => f.endsWith('.lock'))
for (const lockEntry of lockEntries) {
const lockFilePath = join(locksDir, lockEntry)
try {
const stats = fs.lstatSync(lockFilePath)
if (stats.isDirectory()) {
// Legacy proper-lockfile directory lock - always remove when PID-based
// locking is enabled since these are from a different locking mechanism
fs.rmSync(lockFilePath, { recursive: true, force: true })
cleanedCount++
logForDebugging(`Cleaned up legacy directory lock: ${lockEntry}`)
} else if (!isLockActive(lockFilePath)) {
// PID-based file lock with no running process
fs.unlinkSync(lockFilePath)
cleanedCount++
logForDebugging(`Cleaned up stale lock: ${lockEntry}`)
}
} catch {
// Ignore individual cleanup errors
}
}
} catch (error) {
if (isENOENT(error)) {
return 0
}
logError(toError(error))
}
return cleanedCount
}
|