Class: VagrantPlugins::SshConfigManager::FileLocker

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant_ssh_config_manager/file_locker.rb

Overview

Handles file locking for SSH config files to prevent concurrent conflicts

Constant Summary collapse

DEFAULT_TIMEOUT =

Default timeout for acquiring locks (in seconds)

30
LOCK_SHARED =

Lock types

File::LOCK_SH
LOCK_EXCLUSIVE =
File::LOCK_EX
LOCK_NON_BLOCKING =
File::LOCK_NB

Instance Method Summary collapse

Constructor Details

#initialize(file_path, logger = nil) ⇒ FileLocker

Returns a new instance of FileLocker.



18
19
20
21
22
23
# File 'lib/vagrant_ssh_config_manager/file_locker.rb', line 18

def initialize(file_path, logger = nil)
  @file_path = file_path
  @logger = logger || Log4r::Logger.new('vagrant::plugins::ssh_config_manager::file_locker')
  @lock_file = nil
  @locked = false
end

Instance Method Details

#locked?Boolean

Check if file is currently locked by another process

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/vagrant_ssh_config_manager/file_locker.rb', line 36

def locked?
  return false unless File.exist?(@file_path)

  begin
    File.open(@file_path, 'r') do |file|
      # Try to acquire a non-blocking exclusive lock
      file.flock(LOCK_EXCLUSIVE | LOCK_NON_BLOCKING)
      false # Not locked if we could acquire the lock
    end
  rescue Errno::EAGAIN, Errno::EACCES
    true # File is locked
  rescue StandardError => e
    @logger.debug("Error checking lock status: #{e.message}")
    false
  end
end

#with_exclusive_lock(timeout: DEFAULT_TIMEOUT, &block) ⇒ Object

Acquire an exclusive lock on the file



26
27
28
# File 'lib/vagrant_ssh_config_manager/file_locker.rb', line 26

def with_exclusive_lock(timeout: DEFAULT_TIMEOUT, &block)
  with_lock(LOCK_EXCLUSIVE, timeout: timeout, &block)
end

#with_shared_lock(timeout: DEFAULT_TIMEOUT, &block) ⇒ Object

Acquire a shared lock on the file



31
32
33
# File 'lib/vagrant_ssh_config_manager/file_locker.rb', line 31

def with_shared_lock(timeout: DEFAULT_TIMEOUT, &block)
  with_lock(LOCK_SHARED, timeout: timeout, &block)
end