Class: RightAws::ElbInterface

Inherits:
RightAwsBase show all
Includes:
RightAwsBaseInterface
Defined in:
lib/elb/right_elb_interface.rb

Overview

RightAWS::ElbInterface – RightScale Amazon Elastic Load Balancer interface

The RightAws::ElbInterface class provides a complete interface to Amazon’s Elastic Load Balancer service.

For explanations of the semantics of each call, please refer to Amazon’s documentation at docs.amazonwebservices.com/ElasticLoadBalancing/latest/DeveloperGuide/

Create an interface handle:

elb = RightAws::ElbInterface.new(aws_access_key_id, aws_security_access_key)

Create an new load balancer:

elb.create_load_balancer( 'test-kd1',
                         ['us-east-1a', 'us-east-1b'],
                         [ { :protocol => :http, :load_balancer_port => 80,  :instance_port => 80 },

{ :protocol => :tcp, :load_balancer_port => 443, :instance_port => 443 } ])

Configure its health checking:

elb.configure_health_check( 'test-kd1',
                            { :healthy_threshold => 9,
                              :unhealthy_threshold => 3,
                              :target => "TCP:433",
                              :timeout => 6,
                              :interval => 31}

Register instances with the balancer:

elb.register_instances_with_load_balancer('test-kd1', 'i-8b8bcbe2', 'i-bf8bcbd6') #=> ["i-8b8bcbe2", "i-bf8bcbd6"]

Add new availability zones:

elb.enable_availability_zones_for_load_balancer("test-kd1", "us-east-1c")

Defined Under Namespace

Classes: AvailabilityZonesForLoadBalancerParser, CreateLoadBalancerParser, DeleteLoadBalancerParser, DescribeInstanceHealthParser, DescribeLoadBalancersParser, HealthCheckParser, InstancesWithLoadBalancerParser

Constant Summary collapse

API_VERSION =

Amazon ELB API version being used

"2009-11-25"
DEFAULT_HOST =
"elasticloadbalancing.amazonaws.com"
DEFAULT_PATH =
'/'
DEFAULT_PROTOCOL =
'https'
DEFAULT_PORT =
443
@@bench =
AwsBenchmarkingBlock.new

Constants included from RightAwsBaseInterface

RightAwsBaseInterface::BLOCK_DEVICE_KEY_MAPPING, RightAwsBaseInterface::DEFAULT_SIGNATURE_VERSION

Constants inherited from RightAwsBase

RightAwsBase::AMAZON_PROBLEMS

Instance Attribute Summary

Attributes included from RightAwsBaseInterface

#aws_access_key_id, #aws_secret_access_key, #cache, #connection, #last_errors, #last_request, #last_request_id, #last_response, #logger, #params, #signature_version

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RightAwsBaseInterface

#amazonize_block_device_mappings, #amazonize_list, #cache_hits?, caching, caching=, #caching?, #destroy_connection, #generate_request_impl, #get_connection, #get_connections_storage, #get_server_url, #init, #on_exception, #request_cache_or_info, #request_info_impl, #signed_service_params, #update_cache

Methods inherited from RightAwsBase

amazon_problems, amazon_problems=

Constructor Details

#initialize(aws_access_key_id = nil, aws_secret_access_key = nil, params = {}) ⇒ ElbInterface

Create a new handle to an ELB account. All handles share the same per process or per thread HTTP connection to Amazon ELB. Each handle is for a specific account. The params have the following options:

  • :endpoint_url a fully qualified url to Amazon API endpoint (this overwrites: :server, :port, :service, :protocol). Example: ‘elasticloadbalancing.amazonaws.com

  • :server: ELB service host, default: DEFAULT_HOST

  • :port: ELB service port, default: DEFAULT_PORT

  • :protocol: ‘http’ or ‘https’, default: DEFAULT_PROTOCOL

  • :multi_thread: true=HTTP connection per thread, false=per process

  • :logger: for log messages, default: RAILS_DEFAULT_LOGGER else STDOUT

  • :signature_version: The signature version : ‘0’,‘1’ or ‘2’(default)

  • :cache: true/false(default): caching works for: describe_load_balancers



91
92
93
94
95
96
97
98
99
100
101
# File 'lib/elb/right_elb_interface.rb', line 91

def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
  init({ :name                => 'ELB',
         :default_host        => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).host   : DEFAULT_HOST,
         :default_port        => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).port   : DEFAULT_PORT,
         :default_service     => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).path   : DEFAULT_PATH,
         :default_protocol    => ENV['ELB_URL'] ? URI.parse(ENV['ELB_URL']).scheme : DEFAULT_PROTOCOL,
         :default_api_version => ENV['ELB_API_VERSION'] || API_VERSION },
       aws_access_key_id    || ENV['AWS_ACCESS_KEY_ID'] ,
       aws_secret_access_key|| ENV['AWS_SECRET_ACCESS_KEY'],
       params)
end

Class Method Details

.bench_serviceObject



75
76
77
# File 'lib/elb/right_elb_interface.rb', line 75

def self.bench_service
  @@bench.service
end

.bench_xmlObject



72
73
74
# File 'lib/elb/right_elb_interface.rb', line 72

def self.bench_xml
  @@bench.xml
end

Instance Method Details

#configure_health_check(load_balancer_name, health_check) ⇒ Object

Define an application healthcheck for the instances. Returns an updated health check configuration for the load balancer.

hc = elb.configure_health_check( 'test-kd1',
                                 { :healthy_threshold => 9,
                                   :unhealthy_threshold => 3,
                                   :target => "TCP:433",
                                   :timeout => 6,
                                   :interval => 31}
pp hc #=> { :target=>"TCP:433", :timeout=>6, :interval=>31, :healthy_threshold=>9, :unhealthy_threshold=>3 }


252
253
254
255
256
257
# File 'lib/elb/right_elb_interface.rb', line 252

def configure_health_check(load_balancer_name, health_check)
  request_hash = { 'LoadBalancerName' => load_balancer_name }
  health_check.each{ |key, value| request_hash["HealthCheck.#{key.to_s.camelize}"] = value }
  link = generate_request("ConfigureHealthCheck", request_hash)
  request_info(link, HealthCheckParser.new(:logger => @logger))
end

Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie. This policy can only be associated with HTTP listeners.

elb.create_app_cookie_stickiness_policy('my-load-balancer', 'MyLoadBalancerPolicy', 'MyCookie') #=> true


320
321
322
323
324
325
326
# File 'lib/elb/right_elb_interface.rb', line 320

def create_app_cookie_stickiness_policy(load_balancer_name, policy_name, cookie_name)
  request_hash = { 'LoadBalancerName' => load_balancer_name,
                   'PolicyName'       => policy_name,
                   'CookieName'       => cookie_name }
  link = generate_request("CreateAppCookieStickinessPolicy", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
end

Generates a stickiness policy with sticky session lifetimes controlled by the lifetime of the browser (user-agent) or a specified expiration period. This policy can only be associated only with HTTP listeners.

elb.create_lb_cookie_stickiness_policy('my-load-balancer', 'MyLoadBalancerPolicy', 60) #=> true


334
335
336
337
338
339
340
# File 'lib/elb/right_elb_interface.rb', line 334

def create_lb_cookie_stickiness_policy(load_balancer_name, policy_name, cookie_expiration_period)
  request_hash = { 'LoadBalancerName'        => load_balancer_name,
                   'PolicyName'              => policy_name,
                   'CookieExpirationPeriod'  => cookie_expiration_period }
  link = generate_request("CreateLBCookieStickinessPolicy", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
end

#create_load_balancer(load_balancer_name, availability_zones = [], listeners = []) ⇒ Object

puts lb #=> “test-kd1-1519253964.us-east-1.elb.amazonaws.com”



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/elb/right_elb_interface.rb', line 181

def create_load_balancer(load_balancer_name, availability_zones=[], listeners=[])
  request_hash = { 'LoadBalancerName' => load_balancer_name }
  # merge zones
  request_hash.merge!( amazonize_list("AvailabilityZones.member", availability_zones) )
  # merge listeners
  if listeners.blank?
    listeners = { :protocol           => :http,
                  :load_balancer_port => 80,
                  :instance_port      => 80 }
  end
  listeners = [listeners] unless listeners.is_a?(Array)
  request_hash.merge!( amazonize_list( ['Listeners.member.?.Protocol',
                                        'Listeners.member.?.LoadBalancerPort',
                                        'Listeners.member.?.InstancePort'],
                                         listeners.map{|i| [ (i[:protocol] || 'HTTP').to_s.upcase,
                                                             (i[:load_balancer_port] || 80),
                                                             (i[:instance_port] || 80) ] } ) )
  link = generate_request("CreateLoadBalancer", request_hash)
  request_info(link, CreateLoadBalancerParser.new(:logger => @logger))
end

#delete_load_balancer(load_balancer_name) ⇒ Object

Delete load balancer. Returns true on success.

elb.delete_load_balancer('test-kd1') #=> true

Amazon: Because this API has been designed to be idempotent, even if the LoadBalancer does not exist or has been deleted, DeleteLoadBalancer still returns a success.



210
211
212
213
# File 'lib/elb/right_elb_interface.rb', line 210

def delete_load_balancer(load_balancer_name)
  link = generate_request("DeleteLoadBalancer", 'LoadBalancerName' => load_balancer_name)
  request_info(link, DeleteLoadBalancerParser.new(:logger => @logger))
end

#deregister_instances_with_load_balancer(load_balancer_name, *instances) ⇒ Object

Remove instance(s) from the load balancer. Returns an updated list of instances for the load balancer.

elb.deregister_instances_with_load_balancer('test-kd1', 'i-8b8bcbe2') #=> ["i-bf8bcbd6"]


302
303
304
305
306
307
308
# File 'lib/elb/right_elb_interface.rb', line 302

def deregister_instances_with_load_balancer(load_balancer_name, *instances)
  instances.flatten!
  request_hash = amazonize_list("Instances.member.?.InstanceId", instances)
  request_hash.merge!( 'LoadBalancerName' => load_balancer_name )
  link = generate_request("DeregisterInstancesFromLoadBalancer", request_hash)
  request_info(link, InstancesWithLoadBalancerParser.new(:logger => @logger))
end

#describe_instance_health(load_balancer_name, *instances) ⇒ Object

Describe the current state of the instances of the specified load balancer. Returns a list of the instances.

elb.describe_instance_health('test-kd1', 'i-8b8bcbe2', 'i-bf8bcbd6') #=>
    [ { :description => "Instance registration is still in progress",
        :reason_code => "ELB",
        :instance_id => "i-8b8bcbe2",
        :state       => "OutOfService" },
      { :description => "Instance has failed at least the UnhealthyThreshold number of health checks consecutively.",
        :reason_code => "Instance",
        :instance_id => "i-bf8bcbd6",
        :state       => "OutOfService" } ]


276
277
278
279
280
281
282
# File 'lib/elb/right_elb_interface.rb', line 276

def describe_instance_health(load_balancer_name, *instances)
  instances.flatten!
  request_hash = amazonize_list("Instances.member.?.InstanceId", instances)
  request_hash.merge!( 'LoadBalancerName' => load_balancer_name )
  link = generate_request("DescribeInstanceHealth", request_hash)
  request_info(link, DescribeInstanceHealthParser.new(:logger => @logger))
end

#describe_load_balancers(*load_balancers) ⇒ Object


Load Balancers

Describe load balancers. Returns an array of load balancers.

elb.describe_load_balancers #=>
  [ { :health_check =>
      { :healthy_threshold => 10,
        :unhealthy_threshold => 2,
        :target => "TCP:80",
        :timeout => 5,
        :interval => 30},
      :load_balancer_name => "test-kd1",
      :availability_zones => ["us-east-1a", "us-east-1b"],
      :listeners =>
       [ { :protocol => "HTTP", :load_balancer_port => "80",  :instance_port => "80" },
         { :protocol => "TCP",  :load_balancer_port => "443", :instance_port => "443" } ],
      :created_time => "2009-05-27T11:59:11.000Z",
      :dns_name => "test-kd1-1519253964.us-east-1.elb.amazonaws.com",
      :instances => [] } ]

elb.describe_load_balancers("test-kd1") #=>
  [{:load_balancer_name=>"test-kd1",
    :instances=>["i-9fc056f4", "i-b3debfd8"],
    :health_check=>
     {:interval=>30,
      :healthy_threshold=>10,
      :target=>"TCP:80",
      :unhealthy_threshold=>2,
      :timeout=>5},
    :dns_name=>"test-kd1-869291821.us-east-1.elb.amazonaws.com",
    :listeners=>
     [{:load_balancer_port=>"80",
       :policy_names=>["my-policy-1"],
       :instance_port=>"80",
       :protocol=>"HTTP"},
      {:load_balancer_port=>"8080",
       :policy_names=>["my-policy-lb-1"],
       :instance_port=>"8080",
       :protocol=>"HTTP"},
      {:load_balancer_port=>"443",
       :policy_names=>[],
       :instance_port=>"443",
       :protocol=>"TCP"}],
    :created_time=>"2010-04-15T12:04:49.000Z",
    :availability_zones=>["us-east-1a", "us-east-1b"],
    :app_cookie_stickiness_policies=>
     [{:policy_name=>"my-policy-1", :cookie_name=>"my-cookie-1"}],
    :lb_cookie_stickiness_policies=>
     [{:cookie_expiration_period=>60, :policy_name=>"my-policy-lb-1"}]}]


165
166
167
168
169
170
# File 'lib/elb/right_elb_interface.rb', line 165

def describe_load_balancers(*load_balancers)
  load_balancers = load_balancers.flatten.compact
  request_hash = amazonize_list("LoadBalancerNames.member", load_balancers)
  link = generate_request("DescribeLoadBalancers", request_hash)
  request_cache_or_info(:describe_load_balancers, link,  DescribeLoadBalancersParser, @@bench, load_balancers.blank?)
end

#disable_availability_zones_for_load_balancer(load_balancer_name, *availability_zones) ⇒ Object

Remove one or more zones from a load balancer. Returns a list of updated availability zones for the load balancer.

elb.disable_availability_zones_for_load_balancer("test-kd1", "us-east-1c") #=> ["us-east-1a"]


233
234
235
236
237
238
239
# File 'lib/elb/right_elb_interface.rb', line 233

def disable_availability_zones_for_load_balancer(load_balancer_name, *availability_zones)
  availability_zones.flatten!
  request_hash = amazonize_list("AvailabilityZones.member", availability_zones)
  request_hash.merge!( 'LoadBalancerName' => load_balancer_name )
  link = generate_request("DisableAvailabilityZonesForLoadBalancer", request_hash)
  request_info(link, AvailabilityZonesForLoadBalancerParser.new(:logger => @logger))
end

#enable_availability_zones_for_load_balancer(load_balancer_name, *availability_zones) ⇒ Object

Add one or more zones to a load balancer. Returns a list of updated availability zones for the load balancer.

elb.enable_availability_zones_for_load_balancer("test-kd1", "us-east-1c") #=> ["us-east-1a", "us-east-1c"]


220
221
222
223
224
225
226
# File 'lib/elb/right_elb_interface.rb', line 220

def enable_availability_zones_for_load_balancer(load_balancer_name, *availability_zones)
  availability_zones.flatten!
  request_hash = amazonize_list("AvailabilityZones.member", availability_zones)
  request_hash.merge!( 'LoadBalancerName' => load_balancer_name )
  link = generate_request("EnableAvailabilityZonesForLoadBalancer", request_hash)
  request_info(link, AvailabilityZonesForLoadBalancerParser.new(:logger => @logger))
end

#generate_request(action, params = {}) ⇒ Object

:nodoc:



103
104
105
# File 'lib/elb/right_elb_interface.rb', line 103

def generate_request(action, params={}) #:nodoc:
  generate_request_impl(:get, action, params )
end

#register_instances_with_load_balancer(load_balancer_name, *instances) ⇒ Object

Add new instance(s) to the load balancer. Returns an updated list of instances for the load balancer.

elb.register_instances_with_load_balancer('test-kd1', 'i-8b8bcbe2', 'i-bf8bcbd6') #=> ["i-8b8bcbe2", "i-bf8bcbd6"]


289
290
291
292
293
294
295
# File 'lib/elb/right_elb_interface.rb', line 289

def register_instances_with_load_balancer(load_balancer_name, *instances)
  instances.flatten!
  request_hash = amazonize_list("Instances.member.?.InstanceId", instances)
  request_hash.merge!( 'LoadBalancerName' => load_balancer_name )
  link = generate_request("RegisterInstancesWithLoadBalancer", request_hash)
  request_info(link, InstancesWithLoadBalancerParser.new(:logger => @logger))
end

#request_info(request, parser) ⇒ Object

Sends request to Amazon and parses the response Raises AwsError if any banana happened



109
110
111
# File 'lib/elb/right_elb_interface.rb', line 109

def request_info(request, parser)  #:nodoc:
  request_info_impl(:lbs_connection, @@bench, request, parser)
end

#set_load_balancer_policies_of_listener(load_balancer_name, load_balancer_port, *policy_names) ⇒ Object

Associates, updates, or disables a policy with a listener on the load balancer. Only zero(0) or one(1) policy can be associated with a listener.

elb.set_load_balancer_policies_of_listener('my-load-balancer', 80, 'MyLoadBalancerPolicy') #=> true


347
348
349
350
351
352
353
354
# File 'lib/elb/right_elb_interface.rb', line 347

def set_load_balancer_policies_of_listener(load_balancer_name, load_balancer_port, *policy_names)
  policy_names.flatten!
  request_hash = { 'LoadBalancerName' => load_balancer_name,
                   'LoadBalancerPort' => load_balancer_port }
  request_hash.merge!(amazonize_list('PolicyNames.member', policy_names))
  link = generate_request("SetLoadBalancerPoliciesOfListener", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
end