Class: Textus::Ports::WatcherLock

Inherits:
Object
  • Object
show all
Defined in:
lib/textus/ports/watcher_lock.rb

Overview

Flock-based watcher presence lock. Held for the watcher’s lifetime. Process death releases the flock automatically.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ WatcherLock

Returns a new instance of WatcherLock.



10
11
12
13
14
# File 'lib/textus/ports/watcher_lock.rb', line 10

def initialize(root)
  @path = Textus::Layout.watcher_lock(root)
  @file = nil
  FileUtils.mkdir_p(File.dirname(@path))
end

Class Method Details

.running?(root) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/textus/ports/watcher_lock.rb', line 16

def self.running?(root)
  path = Textus::Layout.watcher_lock(root)
  return false unless File.exist?(path)

  File.open(path, "r+") do |file|
    got = file.flock(File::LOCK_EX | File::LOCK_NB)
    file.flock(File::LOCK_UN) if got
    return !got
  end
rescue Errno::ENOENT
  false
end

Instance Method Details

#acquireObject



29
30
31
32
33
34
35
36
# File 'lib/textus/ports/watcher_lock.rb', line 29

def acquire
  @file = File.open(@path, File::RDWR | File::CREAT, 0o644)
  raise "watcher already running" unless @file.flock(File::LOCK_EX | File::LOCK_NB)

  @file.write("pid=#{Process.pid} host=#{Socket.gethostname}\n")
  @file.flush
  self
end

#releaseObject



38
39
40
41
42
43
44
45
# File 'lib/textus/ports/watcher_lock.rb', line 38

def release
  return unless @file

  @file.flock(File::LOCK_UN)
  @file.close
  FileUtils.rm_f(@path)
  @file = nil
end