Class: Prometheus::Client::Helper::FileLocker

Inherits:
Object
  • Object
show all
Defined in:
lib/prometheus/client/helper/file_locker.rb

Constant Summary collapse

LOCK_FILE_MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.lock_to_process(filepath) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/prometheus/client/helper/file_locker.rb', line 8

def lock_to_process(filepath)
  LOCK_FILE_MUTEX.synchronize do
    @file_locks ||= {}
    return false if @file_locks[filepath]

    file = File.open(filepath, 'ab')
    if file.flock(File::LOCK_NB | File::LOCK_EX)
      @file_locks[filepath] = file
      return true
    else
      return false
    end
  end
end

.unlock(filepath) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/prometheus/client/helper/file_locker.rb', line 23

def unlock(filepath)
  LOCK_FILE_MUTEX.synchronize do
    @file_locks ||= {}
    return false unless @file_locks[filepath]

    file = @file_locks[filepath]
    file.flock(File::LOCK_UN)
    file.close
    @file_locks.delete(filepath)
  end
end

.unlock_allObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/prometheus/client/helper/file_locker.rb', line 35

def unlock_all
  LOCK_FILE_MUTEX.synchronize do
    @file_locks ||= {}
    @file_locks.values.each do |file|
      file.flock(File::LOCK_UN)
      file.close
    end

    @file_locks = {}
  end
end