Class: EC2APIProxy::Proxy

Inherits:
EM::Connection
  • Object
show all
Defined in:
lib/ec2-api-proxy/proxy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Proxy



13
14
15
16
17
# File 'lib/ec2-api-proxy/proxy.rb', line 13

def initialize(options)
  @options = options
  @memcached = Dalli::Client.new(options[:memcached], :compress => options[:compress])
  @logger = Logger.new($stdout)
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



10
11
12
# File 'lib/ec2-api-proxy/proxy.rb', line 10

def logger
  @logger
end

#memcachedObject (readonly)

Returns the value of attribute memcached.



11
12
13
# File 'lib/ec2-api-proxy/proxy.rb', line 11

def memcached
  @memcached
end

#optionsObject (readonly)

Returns the value of attribute options.



9
10
11
# File 'lib/ec2-api-proxy/proxy.rb', line 9

def options
  @options
end

Instance Method Details

#post_initObject



19
20
21
22
23
24
25
26
27
28
# File 'lib/ec2-api-proxy/proxy.rb', line 19

def post_init
  if (peername = get_peername)
    @connect_from = Socket.unpack_sockaddr_in(peername)
  end

  if @options[:debug]
    port, ip = @connect_from
    @logger.debug("proxy: connect from #{ip}:#{port}")
  end
end

#receive_data(data) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/ec2-api-proxy/proxy.rb', line 39

def receive_data(data)
  EM.defer {
    begin
      endpoint, params = parse_proxy_request(data)
      key = params_to_key(params)

      if (cache = @memcached.get(key))
        @logger.debug("proxy: cache hit (length=#{cache.length})") if @options[:debug]
        send_data(cache)
        close_connection_after_writing
      else
        @logger.debug("proxy: cache miss") if @options[:debug]
        @backend = EM.connect(endpoint.host, endpoint.port, EC2APIProxy::Backend, self, key)

        if @backend.error?
          @logger.error("proxy: backend connection error: #{data.inspect}")
          send_error('ec2-api-proxy-backend-connection-error', 'backend connection error')
          close_backend_connection
          close_connection_after_writing
        else
          @backend.send_data(data)
        end
      end
    rescue => e
      @logger.warn("#{e.class.name}: #{e.message}")
      send_error(e.class.name, e.message)
      close_backend_connection
      close_connection_after_writing
    end
  }
end

#unbindObject



30
31
32
33
34
35
36
37
# File 'lib/ec2-api-proxy/proxy.rb', line 30

def unbind
  close_backend_connection

  if @options[:debug]
    port, ip = @connect_from
    @logger.debug("proxy: unbind connection from #{ip}:#{port}")
  end
end