Class: WithLock::Client

Inherits:
Object
  • Object
show all
Extended by:
Common
Defined in:
lib/with_lock/client.rb

Constant Summary collapse

@@locker =
nil

Class Method Summary collapse

Methods included from Common

default_settings, load_settings, local_settings_filename, logger, pid, pidfile, running?, settings, settings_filename, url

Class Method Details

.decrement(name) ⇒ Object



48
49
50
# File 'lib/with_lock/client.rb', line 48

def self.decrement(name)
  locker.decrement(identity,scoped_name(name))
end

.get(name, timeout = 5) ⇒ Object



13
14
15
# File 'lib/with_lock/client.rb', line 13

def self.get(name,timeout=5)
  locker.get(identity,scoped_name(name),timeout)
end

.identityObject



9
10
11
# File 'lib/with_lock/client.rb', line 9

def self.identity
  "#{`hostname`.strip}|#{$$}"
end

.increment(name) ⇒ Object



44
45
46
# File 'lib/with_lock/client.rb', line 44

def self.increment(name)
  locker.increment(identity,scoped_name(name))
end

.lockerObject



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/with_lock/client.rb', line 63

def self.locker
  return @@locker if (@@locker.url rescue false)
  @@locker = nil
  tries = 3
  while @@locker.nil? && tries > 0 do
    sleep 0.2 if tries < 3
    tries -= 1
    reconnect!
    @@locker = nil unless (@@locker.url rescue false)
  end
  raise WithLock::LockException.new("Couldn't connect to locker.") if @@locker.nil?
  @@locker
end

.locker_available?Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
# File 'lib/with_lock/client.rb', line 37

def self.locker_available?
  locker.url
  true
rescue DRb::DRbConnError => e
  false
end

.mine?(name) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/with_lock/client.rb', line 21

def self.mine?(name)
  locker.mine?(identity,scoped_name(name))
end

.reconnect!Object



57
58
59
60
61
# File 'lib/with_lock/client.rb', line 57

def self.reconnect!
  DRb.stop_service
  @@uri = DRb.start_service
  @@locker = DRbObject.new_with_uri(url)
end

.release(name) ⇒ Object



17
18
19
# File 'lib/with_lock/client.rb', line 17

def self.release(name)
  locker.release(identity,scoped_name(name))
end

.scopeObject



52
53
54
55
# File 'lib/with_lock/client.rb', line 52

def self.scope
  @@scope ||= Rails.env if defined? Rails
  @@scope ||= File.expand_path('.').split(File::SEPARATOR).last
end

.scoped_name(name) ⇒ Object



5
6
7
# File 'lib/with_lock/client.rb', line 5

def self.scoped_name(name)
  "#{scope}-#{name}"
end

.with_lock(name, timeout = 5, &block) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/with_lock/client.rb', line 25

def self.with_lock(name, timeout=5, &block)
  begin
    locked = mine?(name) && increment(name)
    locked ||= get(name,timeout) || raise(WithLock::LockException.new("Failed to obtain lock #{name} in #{timeout} seconds."))
    yield
  ensure
    if locker_available?
      decrement(name).to_i > 0 || release(name) || logger.debug("Warning: lock #{name} not released!")
    end
  end
end