Class: Imap::Backup::Lockfile

Inherits:
Object
  • Object
show all
Defined in:
lib/imap/backup/lockfile.rb

Defined Under Namespace

Classes: LockfileExistsError, ProcessStartTimeUnavailableError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path:) ⇒ Lockfile

Initializes a new Lockfile instance.



16
17
18
# File 'lib/imap/backup/lockfile.rb', line 16

def initialize(path:)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



12
13
14
# File 'lib/imap/backup/lockfile.rb', line 12

def path
  @path
end

Instance Method Details

#exists?Boolean

Checks if the lockfile exists.



35
36
37
# File 'lib/imap/backup/lockfile.rb', line 35

def exists?
  File.exist?(path)
end

#removeObject

Removes the lockfile.



40
41
42
# File 'lib/imap/backup/lockfile.rb', line 40

def remove
  FileUtils.rm_f(path)
end

#stale?Boolean

Checks if the lockfile is stale (i.e., the process that created it is no longer running).



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/imap/backup/lockfile.rb', line 46

def stale?
  return false if !exists?

  file_content = File.read(path)
  data = JSON.parse(file_content, symbolize_names: true)
  pid = data[:pid]
  starttime = data[:starttime]
  proc_table_entry = Sys::ProcTable.ps(pid: pid)

  return true if proc_table_entry.nil?

  other_starttime = starttime(proc_table_entry)

  other_starttime != starttime
end

#with_lock(&block) ⇒ Object

Creates the lockfile, yields to the given block and ensures the lockfile is removed afterwards.



22
23
24
25
26
27
28
29
30
31
# File 'lib/imap/backup/lockfile.rb', line 22

def with_lock(&block)
  raise LockfileExistsError, "Lockfile already exists at #{path}" if exists?

  begin
    create
    block.call
  ensure
    remove
  end
end