Class: Textus::Infra::Locks::WatcherLock

Inherits:
Object
  • Object
show all
Defined in:
lib/textus/infra/locks.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root, file_system: Infra::FileSystem.new) ⇒ WatcherLock

Returns a new instance of WatcherLock.



9
10
11
12
13
14
15
# File 'lib/textus/infra/locks.rb', line 9

def initialize(root, file_system: Infra::FileSystem.new)
  @root = File.expand_path(root)
  @file_system = file_system
  @path = Textus::Protocol::Layout.new(@root).lock_path("watcher")
  @file = nil
  @file_system.mkdir_p(File.dirname(@path))
end

Class Method Details

.running?(root, file_system: Infra::FileSystem.new) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/textus/infra/locks.rb', line 17

def self.running?(root, file_system: Infra::FileSystem.new)
  path = Textus::Protocol::Layout.new(root).lock_path("watcher")
  return false unless file_system.exists?(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



30
31
32
33
34
35
36
37
# File 'lib/textus/infra/locks.rb', line 30

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



39
40
41
42
43
44
45
46
# File 'lib/textus/infra/locks.rb', line 39

def release
  return unless @file

  @file.flock(File::LOCK_UN)
  @file.close
  @file_system.delete(@path) if @file_system.exists?(@path)
  @file = nil
end