Class: Scales::Server::Proxy::Backend

Inherits:
Object
  • Object
show all
Defined in:
lib/scales-server/proxy/backend.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Backend

Returns a new instance of Backend.

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
# File 'lib/scales-server/proxy/backend.rb', line 11

def initialize(options={})
  raise ArgumentError, "Please provide a :url and :load" unless options[:url]
  @url   = options[:url]
  @load  = options[:load] || 0
  parsed = URI.parse(@url)
  @host, @port = parsed.host, parsed.port
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



7
8
9
# File 'lib/scales-server/proxy/backend.rb', line 7

def host
  @host
end

#loadObject

Returns the value of attribute load.



8
9
10
# File 'lib/scales-server/proxy/backend.rb', line 8

def load
  @load
end

#portObject (readonly)

Returns the value of attribute port.



7
8
9
# File 'lib/scales-server/proxy/backend.rb', line 7

def port
  @port
end

#urlObject (readonly) Also known as: to_s

Returns the value of attribute url.



7
8
9
# File 'lib/scales-server/proxy/backend.rb', line 7

def url
  @url
end

Class Method Details

.add(ports) ⇒ Object



19
20
21
# File 'lib/scales-server/proxy/backend.rb', line 19

def self.add(ports)
  ports.each{ |port| @ports << { :url => "http://0.0.0.0:#{port}" } }
end

.listObject



46
47
48
# File 'lib/scales-server/proxy/backend.rb', line 46

def self.list
  @list ||= @ports.map { |backend| new backend }
end

.portsObject



23
24
25
# File 'lib/scales-server/proxy/backend.rb', line 23

def self.ports
  @ports.map{ |port| port[:url].split(":").last }
end

.select(strategy = :balanced) {|backend| ... } ⇒ Object

Yields:

  • (backend)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/scales-server/proxy/backend.rb', line 27

def self.select(strategy = :balanced)
  @strategy = strategy.to_sym
  case @strategy
    when :balanced
      backend = list.sort_by { |b| b.load }.first
    when :roundrobin
      @pool   = list.clone if @pool.nil? || @pool.empty?
      backend = @pool.shift
    when :random
      backend = list[ rand(list.size-1) ]
    else
      raise ArgumentError, "Unknown strategy: #{@strategy}"
  end

  Callbacks.on_select.call(backend)
  yield backend if block_given?
  backend
end

.strategyObject



50
51
52
# File 'lib/scales-server/proxy/backend.rb', line 50

def self.strategy
  @strategy
end

Instance Method Details

#decrement_counterObject



58
59
60
# File 'lib/scales-server/proxy/backend.rb', line 58

def decrement_counter
  self.load -= 1
end

#increment_counterObject



54
55
56
# File 'lib/scales-server/proxy/backend.rb', line 54

def increment_counter
  self.load += 1
end