Class: Puppet::Util::Lockfile

Inherits:
Object
  • Object
show all
Defined in:
lib/puppet/util/lockfile.rb

Overview

This class provides a simple API for managing a lock file whose contents are an (optional) String. In addition to querying the basic state (#locked?) of the lock, managing the lock (#lock, #unlock), the contents can be retrieved at any time while the lock is held (#lock_data). This can be used to store pids, messages, etc.

See Also:

Direct Known Subclasses

JsonLockfile

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Lockfile

Returns a new instance of Lockfile.



12
13
14
# File 'lib/puppet/util/lockfile.rb', line 12

def initialize(file_path)
  @file_path = file_path
end

Instance Attribute Details

#file_pathObject (readonly)



10
11
12
# File 'lib/puppet/util/lockfile.rb', line 10

def file_path
  @file_path
end

Instance Method Details

#lock(lock_data = nil) ⇒ boolean

Returns true if lock is successfully acquired, false otherwise.

Returns:

  • (boolean)

    true if lock is successfully acquired, false otherwise.



25
26
27
28
29
30
# File 'lib/puppet/util/lockfile.rb', line 25

def lock(lock_data = nil)
  return false if locked?

  File.open(@file_path, 'w') { |fd| fd.print(lock_data) }
  true
end

#lock_dataString

Retrieve the (optional) lock data that was specified at the time the file

was locked.

Returns:

  • (String)

    the data object.



49
50
51
# File 'lib/puppet/util/lockfile.rb', line 49

def lock_data
  return File.read(@file_path) if file_locked?
end

#locked?Boolean

Returns:

  • (Boolean)


41
42
43
44
# File 'lib/puppet/util/lockfile.rb', line 41

def locked?
  # delegate logic to a more explicit private method
  file_locked?
end

#unlockObject



32
33
34
35
36
37
38
39
# File 'lib/puppet/util/lockfile.rb', line 32

def unlock
  if locked?
    Puppet::FileSystem::File.unlink(@file_path)
    true
  else
    false
  end
end