Class: Henitai::ReportsDirectoryLock
- Inherits:
-
Object
- Object
- Henitai::ReportsDirectoryLock
- Defined in:
- lib/henitai/reports_directory_lock.rb,
sig/henitai.rbs
Overview
Coordinates exclusive access to a reports directory across processes.
Constant Summary collapse
- LOCK_FILENAME =
".henitai-run.lock"
Instance Method Summary collapse
- #acquire(file) ⇒ void
- #contention_message(pid) ⇒ String
-
#initialize(reports_dir:) ⇒ ReportsDirectoryLock
constructor
A new instance of ReportsDirectoryLock.
- #lock_path ⇒ String
- #owner_pid(file) ⇒ Integer, String
- #synchronize { ... } ⇒ Object
- #write_owner(file) ⇒ Object
Constructor Details
#initialize(reports_dir:) ⇒ ReportsDirectoryLock
Returns a new instance of ReportsDirectoryLock.
12 13 14 |
# File 'lib/henitai/reports_directory_lock.rb', line 12 def initialize(reports_dir:) @reports_dir = File.(reports_dir) end |
Instance Method Details
#acquire(file) ⇒ void
This method returns an undefined value.
31 32 33 34 35 |
# File 'lib/henitai/reports_directory_lock.rb', line 31 def acquire(file) return if file.flock(File::LOCK_EX | File::LOCK_NB) raise ConcurrentRunError, (owner_pid(file)) end |
#contention_message(pid) ⇒ String
46 47 48 49 50 51 52 53 54 |
# File 'lib/henitai/reports_directory_lock.rb', line 46 def (pid) = "another henitai run is active in #{@reports_dir} " \ "(pid #{pid}); use a separate reports_dir or wait" return unless dead_owner?(pid) "#{}. The recorded owner pid #{pid} is not running — an " \ "orphaned child may still hold the lock " \ "(check: lsof #{lock_path})" end |
#lock_path ⇒ String
27 28 29 |
# File 'lib/henitai/reports_directory_lock.rb', line 27 def lock_path File.join(@reports_dir, LOCK_FILENAME) end |
#owner_pid(file) ⇒ Integer, String
37 38 39 40 41 42 43 44 |
# File 'lib/henitai/reports_directory_lock.rb', line 37 def owner_pid(file) file.rewind = JSON.parse(file.read) pid = ["pid"] if .is_a?(Hash) pid.is_a?(Integer) ? pid : "unknown" rescue JSON::ParserError, IOError, SystemCallError "unknown" end |
#synchronize { ... } ⇒ Object
16 17 18 19 20 21 22 23 |
# File 'lib/henitai/reports_directory_lock.rb', line 16 def synchronize FileUtils.mkdir_p(@reports_dir) File.open(lock_path, File::RDWR | File::CREAT, 0o644) do |file| acquire(file) write_owner(file) yield end end |
#write_owner(file) ⇒ Object
69 70 71 72 73 74 |
# File 'lib/henitai/reports_directory_lock.rb', line 69 def write_owner(file) file.rewind file.truncate(0) file.write(JSON.generate(pid: Process.pid, started_at: Time.now.iso8601)) file.flush end |