Class: IncrementalBackup::Lock

Inherits:
Object
  • Object
show all
Defined in:
lib/incremental_backup/lock.rb

Constant Summary collapse

LOCK_FILENAME =
'lock_{task_id}'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(task) ⇒ Lock

Should not be called from other places than Lock.create



11
12
13
14
15
16
17
18
# File 'lib/incremental_backup/lock.rb', line 11

def initialize task
  @task = task

  @lock_file = File.open(path, File::RDWR|File::CREAT, 0644)
  unless @lock_file.flock(File::LOCK_EX|File::LOCK_NB)
    self.failed = true
  end
end

Instance Attribute Details

#failedObject

Returns the value of attribute failed.



8
9
10
# File 'lib/incremental_backup/lock.rb', line 8

def failed
  @failed
end

Class Method Details

.create(task, &block) ⇒ Object

Obtains lock, run block, release lock



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/incremental_backup/lock.rb', line 21

def self.create task, &block
  task.logger.info 'Obtaining lock...'

  lock = Lock.new task

  if lock.failed
    task.logger.info 'Lock can not be obtained. Exiting!'
    return
  end

  task.logger.info 'Obtained lock'

  begin
    yield
  ensure
    task.logger.info 'Releasing lock...'
    lock.release
    task.logger.info 'Released lock'
  end

  true
end

Instance Method Details

#releaseObject

Release lock



45
46
47
# File 'lib/incremental_backup/lock.rb', line 45

def release
  @lock_file.close if @lock_file
end