Class: Discovery::Discovery

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(discovery_uris, client = HTTPClient.new) ⇒ Discovery

Returns a new instance of Discovery.



17
18
19
20
# File 'lib/discovery/discovery.rb', line 17

def initialize(discovery_uris, client = HTTPClient.new)
  @client = client
  @discovery_uris = discovery_uris
end

Class Method Details

.for_environment(environment) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/discovery/discovery.rb', line 3

def self.for_environment(environment)
  environment ||= "local"

  discoveryrc = File.expand_path("~/.discoveryrc")
  unless File.exist?(discoveryrc) then
    File.open(discoveryrc, "w"){ |f| f.puts("local = http://localhost:8080") }
  end

  value = File.readlines(discoveryrc).map { |l| l.strip.split(/\s*=\s*/, 2) }.select { |k, v| k == environment }.map { |k, v| v }.first
  raise "No such environment '#{environment}'" if value.nil?
  discovery_uris = value.split(/\s*,\s*/)
  return Discovery.new(discovery_uris)
end

Instance Method Details

#lookup(type, pool) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/discovery/discovery.rb', line 22

def lookup(type, pool)
  service_descriptors = []
  @discovery_uris.each do |discovery_uri|
    begin
      url = "#{discovery_uri}/v1/service/#{type}/#{pool}"
      puts "Getting services at \"#{url}\"" if Verbose
      response = @client.get(url)
      if response.status == HTTP::Status::OK then
        body = response.body
        if body.is_a?(HTTP::Message::Body) then
          body = body.content
        end
        service_descriptors = JSON.parse(body)["services"]
        break
      end
    rescue => e
      # ignored
      p "ERROR:: #{e}" if Verbose
    end
  end

  if service_descriptors.nil? then
    return nil
  end

  return service_descriptors
end