Class: EtcdDiscovery::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/etcd-discovery/service.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(arg) ⇒ Service

Returns a new instance of Service.



8
9
10
11
12
13
14
15
16
# File 'lib/etcd-discovery/service.rb', line 8

def initialize(arg)
  if arg.is_a? Etcd::Node
    @attributes = JSON.parse arg.value
  elsif arg.is_a? Hash
    @attributes = arg
  else
    raise TypeError, "requires a Etcd::Node or a Hash, not a #{arg.class}"
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



6
7
8
# File 'lib/etcd-discovery/service.rb', line 6

def attributes
  @attributes
end

Class Method Details

.get(service) ⇒ Object

Raises:

  • (TypeError)


18
19
20
21
22
23
24
25
26
27
28
# File 'lib/etcd-discovery/service.rb', line 18

def self.get(service)
  raise TypeError, "service should be a String, is a #{service.class}" unless service.is_a? String

  client = EtcdDiscovery.config.client
  begin
    service = client.get("/services_infos/#{service}")
    return self.new service.node
  rescue Etcd::KeyNotFound
    return self.new({'name' => service})
  end
end

Instance Method Details

#allObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/etcd-discovery/service.rb', line 30

def all
  client = EtcdDiscovery.config.client
  begin
    node = client.get("/services/#{attributes['name']}", recursive: true).node
  rescue Etcd::KeyNotFound
    raise ServiceNotFound, attributes['name']
  end
  if node.children.length == 0
    raise ServiceNotFound, attributes['name']
  end
  hosts = []
  node.children.each do |c|
    hosts << Host.new(c)
  end
  return hosts
end

#oneObject



47
48
49
# File 'lib/etcd-discovery/service.rb', line 47

def one
  all.sample
end

#set_credentials(user, password) ⇒ Object



70
71
72
73
# File 'lib/etcd-discovery/service.rb', line 70

def set_credentials(user, password)
  @attributes['user'] = user
  @attributes['password'] = password
end

#to_jsonObject



66
67
68
# File 'lib/etcd-discovery/service.rb', line 66

def to_json
  attributes.to_json
end

#to_uri(schemes = ["https", "http"]) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/etcd-discovery/service.rb', line 51

def to_uri(schemes = ["https", "http"])
  a = attributes
  return one.to_uri(schemes) unless a['public']

  schemes = [schemes] if !schemes.is_a?(Array)
  scheme = schemes.select{|s|
    !a['ports'][s].nil?
  }.first
  if a['user'].nil? || a['user'] == ""
    URI("#{scheme}://#{a['hostname']}:#{a['ports'][scheme]}")
  else
    URI("#{scheme}://#{a['user']}:#{a['password']}@#{a['hostname']}:#{a['ports'][scheme]}")
  end
end