Class: Imap::Backup::Lockfile

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

Defined Under Namespace

Classes: LockfileExistsError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path:) ⇒ Lockfile

Initializes a new Lockfile instance.

Parameters:

  • path (String)

    the path to the lockfile



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

def initialize(path:)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



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

def path
  @path
end

Instance Method Details

#exists?Boolean

Checks if the lockfile exists.

Returns:

  • (Boolean)

    true if the lockfile exists, false otherwise



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

def exists?
  File.exist?(path)
end

#removeObject

Removes the lockfile.



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

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).

Returns:

  • (Boolean)

    true if the lockfile is stale, false otherwise



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

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?

  proc_table_entry.starttime != starttime
end

#with_lock(&block) ⇒ Object

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



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

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

  begin
    create
    block.call
  ensure
    remove
  end
end