agent-lock 3.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/.gitleaks.toml +23 -0
  3. data/AGENTS.md +11 -17
  4. data/CHANGELOG.md +124 -3
  5. data/README.md +496 -100
  6. data/Rakefile +13 -6
  7. data/docs/badges/coverage_badge.svg +21 -0
  8. data/docs/badges/yardoc.svg +1 -0
  9. data/docs/img/alock-sequence.avif +0 -0
  10. data/docs/img/alock-sequence.md +29 -0
  11. data/docs/img/alock-sequence.png +0 -0
  12. data/lefthook.yml +39 -0
  13. data/lib/agent/lock/cli/commands/acquire.rb +25 -19
  14. data/lib/agent/lock/cli/commands/base.rb +59 -23
  15. data/lib/agent/lock/cli/commands/break.rb +12 -7
  16. data/lib/agent/lock/cli/commands/check.rb +10 -9
  17. data/lib/agent/lock/cli/commands/completion.rb +15 -32
  18. data/lib/agent/lock/cli/commands/list.rb +46 -37
  19. data/lib/agent/lock/cli/commands/listing.rb +170 -0
  20. data/lib/agent/lock/cli/commands/mine.rb +7 -5
  21. data/lib/agent/lock/cli/commands/note.rb +13 -9
  22. data/lib/agent/lock/cli/commands/release.rb +10 -7
  23. data/lib/agent/lock/cli/commands/release_all.rb +7 -5
  24. data/lib/agent/lock/cli/commands/resume.rb +13 -7
  25. data/lib/agent/lock/cli/commands/show.rb +172 -0
  26. data/lib/agent/lock/cli/commands/skills.rb +28 -19
  27. data/lib/agent/lock/cli/commands/switch_backend.rb +205 -0
  28. data/lib/agent/lock/cli/commands/tree_command.rb +72 -0
  29. data/lib/agent/lock/cli/commands/version.rb +2 -1
  30. data/lib/agent/lock/cli/commands/whoami.rb +7 -3
  31. data/lib/agent/lock/cli.rb +63 -19
  32. data/lib/agent/lock/error.rb +52 -1
  33. data/lib/agent/lock/facade/async.rb +83 -0
  34. data/lib/agent/lock/facade/backend.rb +133 -0
  35. data/lib/agent/lock/facade/memo.rb +30 -0
  36. data/lib/agent/lock/facade/refusal.rb +78 -0
  37. data/lib/agent/lock/facade/session.rb +142 -0
  38. data/lib/agent/lock/facade/strategies.rb +36 -0
  39. data/lib/agent/lock/facade.rb +369 -0
  40. data/lib/agent/lock/freeze.rb +59 -5
  41. data/lib/agent/lock/identity.rb +63 -5
  42. data/lib/agent/lock/launcher.rb +17 -1
  43. data/lib/agent/lock/manager/enforcement.rb +98 -0
  44. data/lib/agent/lock/manager/switch.rb +91 -0
  45. data/lib/agent/lock/manager/thaw.rb +68 -0
  46. data/lib/agent/lock/manager.rb +176 -79
  47. data/lib/agent/lock/process_info/legacy_start.rb +60 -0
  48. data/lib/agent/lock/process_info.rb +42 -11
  49. data/lib/agent/lock/record.rb +124 -10
  50. data/lib/agent/lock/scope.rb +49 -4
  51. data/lib/agent/lock/skill.rb +14 -10
  52. data/lib/agent/lock/store/backend_name.rb +62 -0
  53. data/lib/agent/lock/store/file_system_store.rb +20 -1
  54. data/lib/agent/lock/store/redis_index.rb +179 -0
  55. data/lib/agent/lock/store/redis_store.rb +191 -33
  56. data/lib/agent/lock/store.rb +180 -19
  57. data/lib/agent/lock/text.rb +62 -0
  58. data/lib/agent/lock/tree.rb +143 -16
  59. data/lib/agent/lock/version.rb +2 -1
  60. data/lib/agent/lock.rb +3 -0
  61. data/skills/agent-lock/SKILL.md +75 -10
  62. metadata +41 -22
  63. data/justfile +0 -127
  64. data/sig/agent/lock.rbs +0 -6
@@ -2,6 +2,9 @@
2
2
 
3
3
  require_relative "freeze"
4
4
  require_relative "identity"
5
+ require_relative "manager/enforcement"
6
+ require_relative "manager/switch"
7
+ require_relative "manager/thaw"
5
8
  require_relative "record"
6
9
  require_relative "scope"
7
10
  require_relative "store"
@@ -16,18 +19,39 @@ module Agent
16
19
  # decisions here and the wording in the commands is what lets the whole
17
20
  # lifecycle be tested without capturing output.
18
21
  class Manager
22
+ # What every Manager verb returns.
23
+ #
24
+ # @!attribute [r] status
25
+ # @return [Symbol] what happened, such as :acquired, :held or :not_found
26
+ # @!attribute [r] records
27
+ # @return [Array<Record>] the records involved, the subject first
28
+ # @!attribute [r] message
29
+ # @return [String, nil] a warning worth printing, such as a partial freeze
19
30
  Result = Data.define(:status, :records, :message) do
20
31
  # @return [Integer] what the process should exit with
21
- def code = %i[held refused not_found interrupted parent_scope].include?(status) ? 1 : 0
32
+ def code = %i[held refused not_found interrupted parent_scope occupied].include?(status) ? 1 : 0
22
33
 
23
34
  # @return [Record, nil] the one record most results are about
24
35
  def record = records.first
25
36
  end
26
37
 
38
+ # Minutes untouched before a lock is reported STALE, and before one
39
+ # whose holder cannot be checked expires. AGENT_LOCK_STALE_MINUTES
40
+ # overrides it.
27
41
  DEFAULT_STALE_MINUTES = 120
28
42
 
43
+ # @!attribute [r] tree
44
+ # @return [Tree] the checkout this manager works on
45
+ # @!attribute [r] store
46
+ # @return [Store::FileSystemStore, Store::RedisStore] where its locks are kept
47
+ # @!attribute [r] identity
48
+ # @return [Identity] who every lock it takes is signed by
29
49
  attr_reader :tree, :store, :identity
30
50
 
51
+ # @param tree [Tree] the checkout to work on
52
+ # @param identity [Identity] who the locks are signed by
53
+ # @param stale_minutes [Integer, nil] nil reads AGENT_LOCK_STALE_MINUTES
54
+ # @param store [FileSystemStore, RedisStore, nil] nil picks the tree's backend
31
55
  def initialize(tree: Tree.for, identity: Identity.current, stale_minutes: nil, store: nil)
32
56
  @tree = tree
33
57
  @store = store || Store.for(tree)
@@ -49,32 +73,37 @@ module Agent
49
73
  # ten sessions claiming `lib/**` and `lib/a.rb` at once each saw a clear
50
74
  # field and each wrote a lock, leaving overlapping claims that all
51
75
  # reported success. Freezing stays outside: it walks the tree and runs
52
- # `chflags`, and every other session would be waiting on it.
76
+ # `chflags`, and every other session would be waiting on it. What it
77
+ # writes afterwards goes back under the mutex: see {Enforcement}.
53
78
  #
54
79
  # @param path [String] a path or a glob
55
80
  # @param intent [String]
56
81
  # @param enforce [Boolean] also make the matched files unwritable
57
- # @param force [Boolean] freeze even a very wide scope
82
+ # @param wide [Boolean] freeze even a scope wider than Freeze::LIMIT files
58
83
  # @return [Result] :acquired, or :already_mine, :held, :parent_scope or
59
- # :interrupted with the records that explain why not
60
- def acquire(path, intent: "unspecified", enforce: false, force: false)
84
+ # :interrupted with the records that explain why not. With `enforce`,
85
+ # :held also answers a lock that was broken while its files were
86
+ # being frozen, with whoever holds the scope now
87
+ def acquire(path, intent: "unspecified", enforce: false, wide: false)
61
88
  scope = Scope.parse(path, tree: tree)
62
- outcome = store.synchronize { take(scope, intent) }
89
+ outcome = exclusively { take(scope, intent) }
63
90
  return outcome unless enforce && outcome.status == :acquired
64
91
 
65
- enforce_on(outcome.record, scope, force: force)
92
+ enforce_on(outcome.record, scope, wide: wide)
66
93
  end
67
94
 
68
95
  # @param path [String]
69
96
  # @return [Result]
70
97
  def release(path)
71
98
  scope = Scope.parse(path, tree: tree)
72
- record = locate(scope, prefer: ->(found) { found.held_by?(identity) })
73
- return result(:not_found, []) if record.nil?
74
- return result(:refused, [record]) unless record.held_by?(identity)
99
+ exclusively do
100
+ record = locate(scope, prefer: ->(found) { found.held_by?(identity) })
101
+ next result(:not_found, []) if record.nil?
102
+ next result(:refused, [record]) unless record.held_by?(identity)
75
103
 
76
- drop(record)
77
- result(:released, [record])
104
+ drop(record)
105
+ result(:released, [record])
106
+ end
78
107
  end
79
108
 
80
109
  # Whether this session may write in a scope. A parent's lock alone does
@@ -82,46 +111,51 @@ module Agent
82
111
  # before its siblings can see it there; to the child, that scope is
83
112
  # :free to claim.
84
113
  #
114
+ # Nor does a narrower lock of this session's own, which is the line
115
+ # `acquire` draws: holding `lib/a.rb` and asking about `lib/**` answered
116
+ # :mine while `acquire 'lib/**'` wrote a new lock, so the asker wrote
117
+ # to files nobody had claimed. Only a lock that contains the whole
118
+ # scope is :mine; anything less is :free, still to be claimed.
119
+ #
85
120
  # @param path [String]
86
- # @return [Result] :held, :mine or :free
121
+ # @return [Result] :held, :mine with this session's locks that contain
122
+ # the scope, or :free
87
123
  def check(path)
88
124
  scope = Scope.parse(path, tree: tree)
89
- reap
90
- blocking, family = conflicts(scope).partition { |record| record.blocks?(identity) }
125
+ blocking, family = after_reap { conflicts(scope).partition { |record| record.blocks?(identity) } }
91
126
  return result(:held, blocking) if blocking.any?
92
127
 
93
- own = family.select { |record| record.held_by?(identity) }
128
+ own = covering(scope, family.select { |record| record.held_by?(identity) })
94
129
  own.any? ? result(:mine, own) : result(:free, [])
95
130
  end
96
131
 
97
132
  # @return [Result] every lock in the store, this tree's siblings included
98
133
  def list
99
- reap
100
- result(:listed, store.all)
134
+ result(:listed, after_reap { store.all })
101
135
  end
102
136
 
103
137
  # @return [Result]
104
138
  def mine
105
- reap
106
- result(:listed, store.all.select { |record| record.held_by?(identity) })
139
+ result(:listed, after_reap { store.all.select { |record| record.held_by?(identity) } })
107
140
  end
108
141
 
109
142
  # @return [Result]
110
143
  def release_all
111
- held = store.all.select { |record| record.held_by?(identity) }
112
- held.each { |record| drop(record) }
113
- result(:released, held)
144
+ mine = ->(record) { record.held_by?(identity) }
145
+ result(:released, exclusively { store.all.select(&mine).each { |record| drop(record) } })
114
146
  end
115
147
 
116
148
  # @param path [String]
117
149
  # @return [Result]
118
150
  def break_lock(path)
119
151
  scope = Scope.parse(path, tree: tree)
120
- record = locate(scope)
121
- return result(:not_found, []) if record.nil?
152
+ exclusively do
153
+ record = locate(scope)
154
+ next result(:not_found, []) if record.nil?
122
155
 
123
- drop(record)
124
- result(:broken, [record])
156
+ drop(record)
157
+ result(:broken, [record])
158
+ end
125
159
  end
126
160
 
127
161
  # Locks whose holder is provably gone, or, for a holder on another host
@@ -136,13 +170,11 @@ module Agent
136
170
  # halfway, and a reboot is the most likely reason there are any. Whoever
137
171
  # comes next sees them, and `resume` takes the lock and the notes back.
138
172
  #
173
+ # Takes the store's mutex, so it is not for use inside another
174
+ # `synchronize`: the verbs here call {#sweep} there instead.
175
+ #
139
176
  # @return [Array<Record>] what it cleared out of the way
140
- def reap
141
- store.all.select { |record| record.active? && record.expired?(stale_minutes) }.map do |record|
142
- record.notes? ? orphan(record) : drop(record)
143
- record
144
- end
145
- end
177
+ def reap = exclusively { sweep }
146
178
 
147
179
  # Write a line into a lock this session holds, so that a machine coming
148
180
  # back up has something better than the diff to work out where it was.
@@ -152,13 +184,15 @@ module Agent
152
184
  # @return [Result]
153
185
  def note(path, text)
154
186
  scope = Scope.parse(path, tree: tree)
155
- record = locate(scope, prefer: ->(found) { found.held_by?(identity) })
156
- return result(:not_found, []) if record.nil?
157
- return result(:refused, [record]) unless record.held_by?(identity)
158
-
159
- updated = record.note(text)
160
- store.update(updated)
161
- result(:noted, [updated])
187
+ exclusively do
188
+ record = locate(scope, prefer: ->(found) { found.held_by?(identity) })
189
+ next result(:not_found, []) if record.nil?
190
+ next result(:refused, [record]) unless record.held_by?(identity)
191
+
192
+ updated = record.note(text)
193
+ store.update(updated)
194
+ result(:noted, [updated])
195
+ end
162
196
  end
163
197
 
164
198
  # Take an interrupted lock back, notes and all.
@@ -177,27 +211,77 @@ module Agent
177
211
  # @return [Result] :resumed, :not_found, or :held with what overlaps
178
212
  def resume(path)
179
213
  scope = Scope.parse(path, tree: tree)
180
- store.synchronize do
181
- reap
214
+ exclusively do
215
+ sweep
182
216
  record = locate(scope, prefer: :orphaned?.to_proc)
183
217
  next result(:not_found, []) if record.nil? || record.active?
184
218
 
185
219
  blocking = conflicts(scope).select { |other| other.blocks?(identity) }
186
220
  next result(:held, blocking) if blocking.any?
187
221
 
188
- rebind(record, scope)
222
+ # Under the orphan's own spelling, which may differ in case from the
223
+ # one typed here: the id is made from the scope the record states.
224
+ rebind(record, record.scope_object)
189
225
  end
190
226
  end
191
227
 
228
+ # Bind this tree to another backend: see {Switch}. Reaped first, so a
229
+ # holder that is gone does not stand in the way.
230
+ #
231
+ # @param target [Store::FileSystemStore, Store::RedisStore] the store to move to, connected
232
+ # @param discard [Boolean] delete the old store's locks instead of refusing
233
+ # @return [Result] :switched with the locks it discarded, :unchanged, or
234
+ # :occupied with the locks standing in the way
235
+ def switch_backend(target, discard: false) = result(*switcher.call(target, discard:))
236
+
192
237
  private
193
238
 
239
+ # Reads the store with the reaping that precedes it under one hold of
240
+ # the mutex, so no other writer lands between the two. Not for use
241
+ # inside another `synchronize`: the file store's flock is not
242
+ # re-entrant.
243
+ #
244
+ # @yield the read
245
+ # @return [Object] whatever the block returns
246
+ def after_reap
247
+ exclusively do
248
+ sweep
249
+ yield
250
+ end
251
+ end
252
+
253
+ # The store's mutex, and then a look at the tree's marker. A manager picks
254
+ # its store when it is built, and `switch-backend` moves the marker under
255
+ # this same mutex. A verb that was waiting on the mutex while the tree
256
+ # moved would otherwise claim, or read "free", in a store nobody reads
257
+ # any more, and report success. Not re-entrant: see {#after_reap}.
258
+ #
259
+ # @yield the critical section
260
+ # @return [Object] whatever the block returns
261
+ # @raise [Store::Mismatch] when the tree moved to another backend after
262
+ # this manager was built
263
+ def exclusively(&) = Switch.holding(tree, store, &)
264
+
265
+ # @return [Switch] over this store, reaping and dropping as this manager does
266
+ def switcher = Switch.new(tree, store, sweep: method(:sweep), drop: method(:drop))
267
+
268
+ # {#reap} without the mutex, for a caller already holding it.
269
+ #
270
+ # @return [Array<Record>] what it cleared out of the way
271
+ def sweep
272
+ store.all.select { |record| record.active? && record.expired?(stale_minutes) }.map do |record|
273
+ record.notes? ? orphan(record) : drop(record)
274
+ record
275
+ end
276
+ end
277
+
194
278
  # The critical section of #acquire: the scan, and the write it justifies.
195
279
  #
196
280
  # @param scope [Scope]
197
281
  # @param intent [String]
198
282
  # @return [Result]
199
283
  def take(scope, intent)
200
- reap
284
+ sweep
201
285
  refusal = why_not(scope)
202
286
  return refusal if refusal
203
287
 
@@ -255,39 +339,25 @@ module Agent
255
339
  result(:interrupted, [record]) if record&.orphaned?
256
340
  end
257
341
 
258
- # Freezing happens after the claim is won, never before. Flagging files
259
- # first and then losing the race would leave a tree full of unwritable
260
- # files that no lock admits to having frozen, which is the one failure
261
- # this whole feature is supposed to prevent.
342
+ # See {Enforcement}.
262
343
  #
263
344
  # @param record [Record] the lock, already created
345
+ # @param scope [Scope]
346
+ # @param wide [Boolean] freeze even a scope wider than Freeze::LIMIT files
264
347
  # @return [Result]
265
- def enforce_on(record, scope, force:)
266
- wanted = Freeze.matches(scope, tree)
267
- frozen = Freeze.apply(wanted, tree: tree, force: force)
268
- updated = record.with(frozen_paths: frozen)
269
- store.update(updated)
270
-
271
- result(:acquired, [updated], freeze_shortfall(wanted, frozen))
272
- rescue Freeze::TooBroad
273
- # The lock stands; the freeze does not. Undoing the claim here would
274
- # be a second surprise on top of the first.
275
- drop(record)
276
- raise
277
- end
348
+ def enforce_on(record, scope, wide:)
349
+ updated, shortfall = Enforcement.new(tree, store).apply(record, scope, wide:)
350
+ return result(:acquired, [updated], shortfall) if updated
278
351
 
279
- # @return [String, nil] said only when the filesystem refused some of it
280
- def freeze_shortfall(wanted, frozen)
281
- missed = wanted.size - frozen.size
282
- return nil if missed.zero?
283
-
284
- "could not freeze #{missed} of #{wanted.size} file(s); the lock still stands"
352
+ result(:held, exclusively { conflicts(scope) },
353
+ "#{scope} was broken while its files were being frozen; nothing is frozen")
285
354
  end
286
355
 
287
356
  # Orphaned locks are left out: they carry the notes of a session that
288
357
  # died, which is information rather than a claim, and a machine that
289
358
  # rebooted should not lock its owner out of their own checkout.
290
359
  #
360
+ # @param scope [Scope]
291
361
  # @return [Array<Record>]
292
362
  def conflicts(scope)
293
363
  store.all.select do |record|
@@ -295,23 +365,28 @@ module Agent
295
365
  end
296
366
  end
297
367
 
298
- # The frozen paths of a lock taken in another checkout, or on another
299
- # machine, name files that are not here. Clearing them would unfreeze
368
+ # The holder is gone, so what it froze is thawed, in the checkout that
369
+ # froze it: see {Thaw}. The frozen paths of a lock taken on another
370
+ # machine name files that are not here. Clearing them would unfreeze
300
371
  # this checkout's files of the same name, which may be frozen under a
301
- # lock of its own, so they are left alone. An orphan keeps the list, so
302
- # the checkout that froze them can still see what to thaw.
372
+ # lock of its own, so they are left alone, and the orphan keeps the
373
+ # list, so the machine that froze them can still see what to thaw.
303
374
  #
304
375
  # @param record [Record]
376
+ # @return [void]
305
377
  def orphan(record)
306
- local = record.local_to?(tree)
307
- Freeze.clear(record.frozen_paths, tree: tree) if local
308
- store.update(record.with(status: Record::ORPHANED, frozen_paths: local ? [] : record.frozen_paths,
309
- updated_at: Time.now.utc.iso8601))
378
+ unreachable = Thaw.call(record)
379
+ store.update(record.with(status: Record::ORPHANED, frozen_paths: unreachable, updated_at: Time.now.utc.iso8601))
310
380
  end
311
381
 
382
+ # Thawed where the lock was taken, not where this command runs: a lock
383
+ # from another worktree used to be deleted here with its files still
384
+ # frozen there, and the list of them went with the record.
385
+ #
312
386
  # @param record [Record]
387
+ # @return [void]
313
388
  def drop(record)
314
- Freeze.clear(record.frozen_paths, tree: tree) if record.local_to?(tree)
389
+ Thaw.call(record)
315
390
  store.delete(record)
316
391
  end
317
392
 
@@ -326,32 +401,54 @@ module Agent
326
401
  # switched to. `prefer` picks which one a command is after, so `release`
327
402
  # finds the lock it owns rather than refusing on somebody else's.
328
403
  #
404
+ # The scan also takes a lock on this scope spelled in another case,
405
+ # which the id, made from the spelling, cannot find. `acquire` and
406
+ # `check` answer for `readme.md` with the lock on `README.md`, so
407
+ # `release` and `note` have to reach that lock by the same name.
408
+ #
329
409
  # @param scope [Scope]
330
410
  # @param prefer [Proc, nil] the record wanted when there is a choice
331
411
  # @return [Record, nil]
332
412
  def locate(scope, prefer: nil)
333
- found = [store.find(scope), *store.all.select { |record| record.scope == scope.to_s && record.local_to?(tree) }]
334
- .compact.uniq(&:id)
413
+ found = [store.find(scope), *store.all.select { |record| spelling_of?(scope, record) }].compact.uniq(&:id)
335
414
  (prefer && found.find(&prefer)) || found.first
336
415
  end
337
416
 
417
+ # @param scope [Scope]
418
+ # @param record [Record]
419
+ # @return [Boolean] whether the lock is on this scope, in any case, and
420
+ # about this tree: its branch from anywhere, or this very checkout
421
+ def spelling_of?(scope, record) = record.about?(tree) && record.scope_object.same_as?(scope)
422
+
338
423
  # An orphan made a live claim again, by this session, on this tree's
339
424
  # current branch. When the branch moved, the id moves with it: the new
340
425
  # record is created first, so a lost race leaves the orphan where it
341
426
  # was, and the old one is deleted only once the new one stands.
342
427
  #
428
+ # The freeze does not come back with the claim. An orphan's frozen
429
+ # paths are relative to the checkout that froze them, and carried into
430
+ # this one they made the next `release` clear this checkout's flags on
431
+ # files of the same name while the real ones stayed frozen. So the
432
+ # resumed lock lists none, and what the orphan still lists is thawed
433
+ # where this machine can reach it.
434
+ #
343
435
  # @param record [Record] the orphan
344
436
  # @param scope [Scope]
345
437
  # @return [Result]
346
438
  def rebind(record, scope)
347
- adopted = record.resumed(tree: tree, scope: scope, identity: identity)
439
+ adopted = record.resumed(tree: tree, scope: scope, identity: identity).with(frozen_paths: [])
348
440
  moved = adopted.id != record.id
349
441
  return result(:interrupted, [store.find(scope)].compact) if moved && !store.create(adopted)
350
442
 
351
443
  moved ? store.delete(record) : store.update(adopted)
444
+ Thaw.call(record)
352
445
  result(:resumed, [adopted])
353
446
  end
354
447
 
448
+ # @param status [Symbol]
449
+ # @param records [Array<Record>]
450
+ # @param message [String, nil]
451
+ # @return [Result]
355
452
  def result(status, records, message = nil) = Result.new(status:, records:, message:)
356
453
  end
357
454
  end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Agent
4
+ module Lock
5
+ module ProcessInfo
6
+ # Reads the start time a 4.0.0 gem recorded for a lock's holder.
7
+ #
8
+ # That gem stored `ps -o lstart=` as printed, so the text is a wall
9
+ # clock in a time zone, and in a language, the record does not name:
10
+ #
11
+ # Sat Nov 28 13:57:53 2026 TZ=America/Los_Angeles
12
+ # Sa. 28 Nov. 13:57:53 2026 LC_ALL=de_DE.UTF-8
13
+ # 2026년 11월 28일 토요일 13시 57분 53초
14
+ #
15
+ # It cannot be turned back into an instant, so the question is asked
16
+ # the other way round: could the process now at that pid, whose start
17
+ # instant is known, have been printed as this text on some zone's
18
+ # clock? Only the numbers are compared, because they are the one part
19
+ # every locale `ps` knows prints in ASCII digits on a 24-hour clock.
20
+ #
21
+ # A recycled pid passes only when its process started a whole number
22
+ # of quarter hours from the old one, on a matching date: one start
23
+ # second in 900. Passing keeps a dead holder's lock until somebody
24
+ # breaks it. Failing would reap a live holder's lock, which is the
25
+ # failure this exists to prevent.
26
+ module LegacyStart
27
+ # Every UTC offset a zone may have, in seconds: whole quarter hours
28
+ # from UTC-12:00 to UTC+14:00.
29
+ OFFSETS = (-48..56).map { |quarters| quarters * 900 }.freeze
30
+
31
+ module_function
32
+
33
+ # @param text [String] the `started` a 4.0.0 gem recorded
34
+ # @param instant [Time] when the process now at that pid started
35
+ # @return [Boolean] whether some zone's clock showed `text` at `instant`
36
+ def shows?(text, instant)
37
+ # As bytes: a locale that is not UTF-8 leaves text no regexp will
38
+ # scan as characters, and the digits are ASCII either way.
39
+ numbers = text.to_s.b.scan(/\d+/).map(&:to_i)
40
+ OFFSETS.any? { |offset| on_clock?(numbers, instant.getutc + offset) }
41
+ end
42
+
43
+ # Hour, minute and second sit side by side in every locale; the day
44
+ # and the year sit around them in an order that varies, and the year
45
+ # may be printed as two digits.
46
+ #
47
+ # @param numbers [Array<Integer>] every number in the recorded text
48
+ # @param wall [Time] the instant, shifted onto one zone's wall clock
49
+ # @return [Boolean]
50
+ def on_clock?(numbers, wall)
51
+ at = numbers.each_cons(3).find_index([wall.hour, wall.min, wall.sec])
52
+ return false if at.nil?
53
+
54
+ date = numbers[0...at] + numbers[(at + 3)..]
55
+ date.include?(wall.day) && date.intersect?([wall.year, wall.year % 100])
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -1,5 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "time"
4
+
5
+ require_relative "process_info/legacy_start"
6
+
3
7
  module Agent
4
8
  module Lock
5
9
  # The three questions this gem asks the operating system about a process:
@@ -9,6 +13,15 @@ module Agent
9
13
  # Linux, and because none of it is on a hot path. Every answer is nil when
10
14
  # the process is gone, which callers read as "no longer running".
11
15
  module ProcessInfo
16
+ # The environment `ps` reads a start time under. Left to the caller's
17
+ # own, `ps` prints it in that time zone and locale, so a command run
18
+ # under another TZ or LC_TIME read a different start time for the same
19
+ # process, took a live holder for dead, and reaped its lock.
20
+ FIXED_CLOCK = { "LC_ALL" => "C", "TZ" => "UTC" }.freeze
21
+
22
+ # `ps -o lstart=` under {FIXED_CLOCK}, e.g. "Sat Nov 28 21:57:53 2026".
23
+ LSTART = /\A[A-Z][a-z]{2} (?<month>[A-Z][a-z]{2}) +(?<day>\d+) (?<clock>\d\d:\d\d:\d\d) (?<year>\d{4})\z/
24
+
12
25
  module_function
13
26
 
14
27
  # @param pid [Integer]
@@ -25,31 +38,49 @@ module Agent
25
38
  value && Integer(value, exception: false)
26
39
  end
27
40
 
28
- # The wall-clock start time, which is what tells a live process from a
29
- # different one that inherited its recycled pid.
41
+ # When the process started, which is what tells a live process from a
42
+ # different one that inherited its recycled pid. The same string for
43
+ # one process whatever the caller's time zone and locale.
30
44
  #
31
45
  # @param pid [Integer]
32
- # @return [String, nil]
33
- def started_at(pid) = ps(pid, "lstart")
46
+ # @return [String, nil] ISO 8601, UTC. What `ps` printed, when that is
47
+ # not a date this reads: nil would say the process is gone
48
+ def started_at(pid)
49
+ text = ps(pid, "lstart", env: FIXED_CLOCK)
50
+ date = LSTART.match(text.to_s)
51
+ return text if date.nil?
52
+
53
+ Time.utc(date[:year], date[:month], date[:day], *date[:clock].split(":")).iso8601
54
+ end
34
55
 
35
56
  # @param pid [Integer, nil]
36
- # @param started [String, nil] as recorded when the lock was taken
57
+ # @param started_at [String, nil] {.started_at}, as recorded when the lock was taken
58
+ # @param started [String, nil] what a 4.0.0 gem recorded in its place,
59
+ # see {LegacyStart}. Read only when `started_at` is missing
37
60
  # @return [Boolean] whether that exact process is still running
38
- def alive?(pid, started: nil)
61
+ def alive?(pid, started_at: nil, started: nil)
39
62
  return false if pid.nil?
40
63
 
41
- now = started_at(pid)
64
+ now = ProcessInfo.started_at(pid)
42
65
  return false if now.nil?
43
- return true if started.nil? || started.empty?
66
+ return now == started_at unless started_at.to_s.empty?
67
+ return true if started.to_s.empty?
44
68
 
45
- now == started
69
+ LegacyStart.shows?(started, Time.iso8601(now))
70
+ rescue ArgumentError
71
+ # `ps` printed no date to compare with, so the pid is all there is,
72
+ # as it is for a record that names no start time.
73
+ true
46
74
  end
47
75
 
76
+ # @param pid [Integer, nil]
77
+ # @param field [String] a `ps -o` keyword, e.g. "comm"
78
+ # @param env [Hash{String => String}] set for `ps` on top of the caller's own
48
79
  # @return [String, nil] the field, or nil for a process that is gone
49
- def ps(pid, field)
80
+ def ps(pid, field, env: {})
50
81
  return nil if pid.nil?
51
82
 
52
- out = IO.popen(["ps", "-p", pid.to_s, "-o", "#{field}="], err: File::NULL, &:read)
83
+ out = IO.popen(env, ["ps", "-p", pid.to_s, "-o", "#{field}="], err: File::NULL, &:read)
53
84
  out = out.to_s.strip
54
85
  out.empty? ? nil : out
55
86
  rescue SystemCallError