Merge pull request #588 from dhepper/elb_vpcs

Improved the ELBBackend
This commit is contained in:
Steve Pulec 2016-04-23 19:34:40 -04:00
commit 1b4a9bd553
3 changed files with 104 additions and 35 deletions

View File

@ -10,6 +10,7 @@ from boto.ec2.elb.attributes import (
)
from boto.ec2.elb.policies import Policies
from moto.core import BaseBackend
from moto.ec2.models import ec2_backends
from .exceptions import LoadBalancerNotFoundError, TooManyTagsError, BadHealthCheckDefinition
@ -47,7 +48,7 @@ class FakeBackend(object):
class FakeLoadBalancer(object):
def __init__(self, name, zones, ports, scheme='internet-facing',):
def __init__(self, name, zones, ports, scheme='internet-facing', vpc_id=None, subnets=None):
self.name = name
self.health_check = None
self.instance_ids = []
@ -60,6 +61,8 @@ class FakeLoadBalancer(object):
self.policies.other_policies = []
self.policies.app_cookie_stickiness_policies = []
self.policies.lb_cookie_stickiness_policies = []
self.subnets = subnets or []
self.vpc_id = vpc_id or 'vpc-56e10e3d'
self.tags = {}
for port in ports:
@ -149,11 +152,22 @@ class FakeLoadBalancer(object):
class ELBBackend(BaseBackend):
def __init__(self):
def __init__(self, region_name=None):
self.region_name = region_name
self.load_balancers = {}
def create_load_balancer(self, name, zones, ports, scheme='internet-facing'):
new_load_balancer = FakeLoadBalancer(name=name, zones=zones, ports=ports, scheme=scheme)
def reset(self):
region_name = self.region_name
self.__dict__ = {}
self.__init__(region_name)
def create_load_balancer(self, name, zones, ports, scheme='internet-facing', subnets=None):
vpc_id = None
ec2_backend = ec2_backends[self.region_name]
if subnets:
subnet = ec2_backend.get_subnet(subnets[0])
vpc_id = subnet.vpc_id
new_load_balancer = FakeLoadBalancer(name=name, zones=zones, ports=ports, scheme=scheme, subnets=subnets, vpc_id=vpc_id)
self.load_balancers[name] = new_load_balancer
return new_load_balancer
@ -286,4 +300,4 @@ class ELBBackend(BaseBackend):
elb_backends = {}
for region in boto.ec2.elb.regions():
elb_backends[region.name] = ELBBackend()
elb_backends[region.name] = ELBBackend(region.name)

View File

@ -27,13 +27,16 @@ class ELBResponse(BaseResponse):
availability_zones = self._get_multi_param("AvailabilityZones.member")
ports = self._get_list_prefix("Listeners.member")
scheme = self._get_param('Scheme')
subnets = self._get_multi_param("Subnets.member")
self.elb_backend.create_load_balancer(
elb = self.elb_backend.create_load_balancer(
name=load_balancer_name,
zones=availability_zones,
ports=ports,
scheme=scheme
scheme=scheme,
subnets=subnets,
)
self._add_tags(elb)
template = self.response_template(CREATE_LOAD_BALANCER_TEMPLATE)
return template.render()
@ -229,31 +232,7 @@ class ELBResponse(BaseResponse):
if not elb:
raise LoadBalancerNotFoundError(load_balancer_name)
value = 'Tags.member.{0}.Value'.format(number)
key = 'Tags.member.{0}.Key'.format(number)
tag_values = []
tag_keys = []
for t_key, t_val in sorted(self.querystring.items()):
if t_key.startswith('Tags.member.'):
if t_key.split('.')[3] == 'Key':
tag_keys.extend(t_val)
elif t_key.split('.')[3] == 'Value':
tag_values.extend(t_val)
counts = {}
for i in tag_keys:
counts[i] = tag_keys.count(i)
counts = sorted(counts.items(), key=lambda i:i[1], reverse=True)
if counts and counts[0][1] > 1:
# We have dupes...
raise DuplicateTagKeysError(counts[0])
for tag_key, tag_value in zip(tag_keys, tag_values):
elb.add_tag(tag_key, tag_value)
self._add_tags(elb)
template = self.response_template(ADD_TAGS_TEMPLATE)
return template.render()
@ -290,6 +269,31 @@ class ELBResponse(BaseResponse):
template = self.response_template(DESCRIBE_TAGS_TEMPLATE)
return template.render(load_balancers=elbs)
def _add_tags(self, elb):
tag_values = []
tag_keys = []
for t_key, t_val in sorted(self.querystring.items()):
if t_key.startswith('Tags.member.'):
if t_key.split('.')[3] == 'Key':
tag_keys.extend(t_val)
elif t_key.split('.')[3] == 'Value':
tag_values.extend(t_val)
counts = {}
for i in tag_keys:
counts[i] = tag_keys.count(i)
counts = sorted(counts.items(), key=lambda i:i[1], reverse=True)
if counts and counts[0][1] > 1:
# We have dupes...
raise DuplicateTagKeysError(counts[0])
for tag_key, tag_value in zip(tag_keys, tag_values):
elb.add_tag(tag_key, tag_value)
ADD_TAGS_TEMPLATE = """<AddTagsResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/">
<AddTagsResult/>
<ResponseMetadata>
@ -369,7 +373,11 @@ DESCRIBE_LOAD_BALANCERS_TEMPLATE = """<DescribeLoadBalancersResponse xmlns="http
<UnhealthyThreshold>{{ load_balancer.health_check.unhealthy_threshold }}</UnhealthyThreshold>
{% endif %}
</HealthCheck>
<VPCId>vpc-56e10e3d</VPCId>
{% if load_balancer.vpc_id %}
<VPCId>{{ load_balancer.vpc_id }}</VPCId>
{% else %}
<VPCId />
{% endif %}
<ListenerDescriptions>
{% for listener in load_balancer.listeners %}
<member>
@ -452,6 +460,9 @@ DESCRIBE_LOAD_BALANCERS_TEMPLATE = """<DescribeLoadBalancersResponse xmlns="http
{% endfor %}
</BackendServerDescriptions>
<Subnets>
{% for subnet in load_balancer.subnets %}
<member>{{ subnet }}</member>
{% endfor %}
</Subnets>
</member>
{% endfor %}

View File

@ -614,11 +614,11 @@ def test_add_remove_tags():
client.add_tags(LoadBalancerNames=['my-lb'],
Tags=[{
'Key': 'a',
'Value': 'a'
'Value': 'b'
}])
tags = dict([(d['Key'], d['Value']) for d in client.describe_tags(LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags']])
tags.should.have('a').should.equal('a')
tags.should.have.key('a').which.should.equal('b')
client.add_tags(LoadBalancerNames=['my-lb'],
Tags=[{
@ -719,3 +719,47 @@ def test_add_remove_tags():
lb_tags['my-lb'].shouldnt.have.key('other')
lb_tags['other-lb'].should.have.key('other').which.should.equal('something')
@mock_elb
def test_create_with_tags():
client = boto3.client('elb', region_name='us-east-1')
client.create_load_balancer(
LoadBalancerName='my-lb',
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':80, 'InstancePort':8080}],
AvailabilityZones=['us-east-1a', 'us-east-1b'],
Tags=[{
'Key': 'k',
'Value': 'v'
}]
)
tags = dict((d['Key'], d['Value']) for d in client.describe_tags(LoadBalancerNames=['my-lb'])['TagDescriptions'][0]['Tags'])
tags.should.have.key('k').which.should.equal('v')
@mock_ec2
@mock_elb
def test_subnets():
ec2 = boto3.resource('ec2', region_name='us-east-1')
vpc = ec2.create_vpc(
CidrBlock='172.28.7.0/24',
InstanceTenancy='default'
)
subnet = ec2.create_subnet(
VpcId=vpc.id,
CidrBlock='172.28.7.192/26'
)
client = boto3.client('elb', region_name='us-east-1')
client.create_load_balancer(
LoadBalancerName='my-lb',
Listeners=[{'Protocol':'tcp', 'LoadBalancerPort':80, 'InstancePort':8080}],
Subnets=[subnet.id]
)
lb = client.describe_load_balancers()['LoadBalancerDescriptions'][0]
lb.should.have.key('Subnets').which.should.have.length_of(1)
lb['Subnets'][0].should.equal(subnet.id)
lb.should.have.key('VPCId').which.should.equal(vpc.id)