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

"2011-04-05"
DEFAULT_HOST =
"elasticloadbalancing.amazonaws.com"
DEFAULT_PATH =
'/'
DEFAULT_PROTOCOL =
'https'
DEFAULT_PORT =
443
LISTENER_PROTOCOLS =
[ 'HTTP', 'HTTPS', 'TCP', 'SSL' ]
@@bench =
AwsBenchmarkingBlock.new

Constants included from RightAwsBaseInterface

RightAwsBaseInterface::BLOCK_DEVICE_KEY_MAPPING, RightAwsBaseInterface::DEFAULT_SIGNATURE_VERSION

Constants inherited from RightAwsBase

RightAwsBase::AMAZON_PROBLEMS, RightAwsBase::RAISE_ON_TIMEOUT_ON_ACTIONS

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_hash_with_key_mapping, #amazonize_list, #amazonize_list_with_key_mapping, #cache_hits?, caching, caching=, #caching?, #destroy_connection, #generate_request_impl, #get_connection, #get_connections_storage, #get_server_url, #incrementally_list_items, #init, #map_api_keys_and_values, #on_exception, #request_cache_or_info, #request_info_impl, #signed_service_params, #update_cache, #with_connection_options

Methods inherited from RightAwsBase

amazon_problems, amazon_problems=, raise_on_timeout_on_actions, raise_on_timeout_on_actions=

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

  • :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



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

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



77
78
79
# File 'lib/elb/right_elb_interface.rb', line 77

def self.bench_service
  @@bench.service
end

.bench_xmlObject



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

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 }


282
283
284
285
286
287
# File 'lib/elb/right_elb_interface.rb', line 282

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.right_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


350
351
352
353
354
355
356
# File 'lib/elb/right_elb_interface.rb', line 350

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


364
365
366
367
368
369
370
# File 'lib/elb/right_elb_interface.rb', line 364

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

:ssl_certificate_id => ‘arn:aws:iam::123456789012:user/division_abc/subdivision_xyz/Bob’ } ])

#=> "test-kd1-1519253964.us-east-1.elb.amazonaws.com"


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

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.right_blank?
    listeners = { :protocol           => :http,
                  :load_balancer_port => 80,
                  :instance_port      => 80 }
  end
  request_hash = merge_listeners_into_request_hash(request_hash, listeners)
  link = generate_request("CreateLoadBalancer", request_hash)
  request_info(link, CreateLoadBalancerParser.new(:logger => @logger))
end

#create_load_balancer_listeners(load_balancer_name, listeners) ⇒ Object

:ssl_certificate_id => ‘arn:aws:iam::123456789012:user/division_abc/subdivision_xyz/Bob’ } ]) #=> true



226
227
228
229
230
231
# File 'lib/elb/right_elb_interface.rb', line 226

def create_load_balancer_listeners(load_balancer_name, listeners)
  request_hash = { 'LoadBalancerName' => load_balancer_name }
  request_hash = merge_listeners_into_request_hash(request_hash, listeners)
  link = generate_request("CreateLoadBalancerListeners", request_hash)
  request_info(link, RightHttp2xxParser.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.



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

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

#delete_load_balancer_listeners(load_balancer_name, *load_balancer_ports) ⇒ Object

Removes listeners from the load balancer for the specified port number.

elb.delete_load_balancer_listeners( 'kd_test', 80, 443) #=> true


237
238
239
240
241
242
243
# File 'lib/elb/right_elb_interface.rb', line 237

def delete_load_balancer_listeners(load_balancer_name, *load_balancer_ports)
  load_balancer_ports.flatten!
  request_hash = { 'LoadBalancerName' => load_balancer_name }
  request_hash.merge!( amazonize_list("LoadBalancerPorts.member", load_balancer_ports ) )
  link = generate_request("DeleteLoadBalancerListeners", request_hash )
  request_info(link, DeleteLoadBalancerParser.new(:logger => @logger))
end

#delete_load_balancer_policy(load_balancer_name, policy_name) ⇒ Object

Deletes a policy from the load balancer. The specified policy must not be enabled for any listeners.

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


394
395
396
397
398
399
# File 'lib/elb/right_elb_interface.rb', line 394

def delete_load_balancer_policy(load_balancer_name, policy_name)
  request_hash = { 'LoadBalancerName'        => load_balancer_name,
                   'PolicyName'              => policy_name }
  link = generate_request("DeleteLoadBalancerPolicy", request_hash)
  request_info(link, RightHttp2xxParser.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"]


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

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" } ]


306
307
308
309
310
311
312
# File 'lib/elb/right_elb_interface.rb', line 306

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"}]}]


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

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.right_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"]


263
264
265
266
267
268
269
# File 'lib/elb/right_elb_interface.rb', line 263

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"]


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

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:



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

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

#merge_listeners_into_request_hash(request_hash, listeners) ⇒ Object


Helpers



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/elb/right_elb_interface.rb', line 413

def merge_listeners_into_request_hash(request_hash, listeners) # :nodoc:
  listeners = [listeners] unless listeners.is_a?(Array)
  request_hash.merge(amazonize_list( ['Listeners.member.?.Protocol',
                                      'Listeners.member.?.LoadBalancerPort',
                                      'Listeners.member.?.InstancePort',
                                      'Listeners.member.?.SSLCertificateId'],
                                      listeners.map{ |i|
                                        [ (i[:protocol]           || 'HTTP').to_s.upcase,
                                           i[:load_balancer_port] || 80,
                                           i[:instance_port]      || 80,
                                           i[:ssl_certificate_id]]
                                      },
                                      :default => :skip_nils
                                   )
                    )
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"]


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

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



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

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

#set_load_balancer_listener_ssl_certificate(load_balancer_name, load_balancer_port, ssl_sertificate_id) ⇒ Object



401
402
403
404
405
406
407
# File 'lib/elb/right_elb_interface.rb', line 401

def set_load_balancer_listener_ssl_certificate(load_balancer_name, load_balancer_port, ssl_sertificate_id)
  request_hash = { 'LoadBalancerName' => load_balancer_name,
                   'LoadBalancerPort' => load_balancer_port,
                   'SSLCertificateId' => ssl_sertificate_id }
  link = generate_request("SetLoadBalancerListenerSSLCertificate", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
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


377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/elb/right_elb_interface.rb', line 377

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 }
  if policy_names.right_blank?
    request_hash['PolicyNames'] = ''
  else
    request_hash.merge!(amazonize_list('PolicyNames.member', policy_names))
  end
  link = generate_request("SetLoadBalancerPoliciesOfListener", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
end