Module: Distlock::ZK::Common

Included in:
ExclusiveLock
Defined in:
lib/distlock/zk/common.rb

Instance Method Summary collapse

Instance Method Details

#closeObject

access @zk directly here, we don’t want to lazy instantiate again if closed already



58
59
60
61
62
63
64
65
66
# File 'lib/distlock/zk/common.rb', line 58

def close
  begin
    @zk.close if @zk
  rescue StandardError, ZookeeperExceptions::ZookeeperException => error
    logger.error("Distlock::ZK::Common#close: caught and squashed error while closing connection - #{error}")
  end

  @zk = nil
end

#create_sequenced_ephemeral(path, prefix = "lock") ⇒ Object



49
50
51
52
53
54
55
# File 'lib/distlock/zk/common.rb', line 49

def create_sequenced_ephemeral(path, prefix="lock")
  lock_path = [path, "#{prefix}-#{zk.client_id}-"].join("/")
  logger.debug lock_path
  result = zk.create(:path => lock_path, :sequence => true, :ephemeral => true)
  logger.debug result
  result[:path]
end

#exists?(path) ⇒ Boolean

does a node exist for the given path?

Returns:

  • (Boolean)


21
22
23
24
25
# File 'lib/distlock/zk/common.rb', line 21

def exists?(path)
  result = zk.stat(:path => path)[:stat].exists
  logger.debug "checking if #{path} exists - #{result}"
  result
end

#loggerObject



12
13
14
# File 'lib/distlock/zk/common.rb', line 12

def logger
  @logger ||= Logger.new(STDOUT)
end

#logger=(logger) ⇒ Object



16
17
18
# File 'lib/distlock/zk/common.rb', line 16

def logger=(logger)
  @logger = logger
end

#safe_create(path) ⇒ Object

create all levels of the hierarchy as necessary i.e. for “/foo/bar/baz”, creates the following nodes -

/foo /foo/bar /foo/bar/baz



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/distlock/zk/common.rb', line 34

def safe_create(path)
  path_elements = path.split("/").reject{ |x| x=="" }
  
  all = []
  while(!path_elements.empty?)
    all << path_elements
    path_elements = path_elements[0..-2]
  end

  all.reverse.each do |path_elements|
    path = "/" + path_elements.join("/")
    zk.create(:path => path) unless exists?(path)
  end
end

#zkObject



6
7
8
9
10
# File 'lib/distlock/zk/common.rb', line 6

def zk
  @zk ||= begin
    zk = Zookeeper.new(@options[:host], @options[:timeout])
  end
end