forked from zalando-stups/lizzy
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added endpoint for a stack's request count (zalando-stups#221)
- Loading branch information
fsander
committed
Feb 22, 2018
1 parent
65d2918
commit 4240517
Showing
9 changed files
with
294 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
from datetime import datetime, timedelta | ||
from logging import getLogger | ||
|
||
import boto3 | ||
from botocore.exceptions import ClientError | ||
|
||
from lizzy.exceptions import ObjectNotFound | ||
|
||
|
||
class AWS(object): | ||
|
||
def __init__(self, region: str): | ||
super().__init__() | ||
self.logger = getLogger('lizzy.app.aws') | ||
self.region = region | ||
|
||
def get_load_balancer_info(self, stack_id: str): | ||
cf = boto3.client("cloudformation", self.region) | ||
try: | ||
response = cf.describe_stack_resource(StackName=stack_id, LogicalResourceId="AppLoadBalancer") | ||
lb_id = response['StackResourceDetail']['PhysicalResourceId'] | ||
lb_type = response['StackResourceDetail']['ResourceType'] | ||
return lb_id, lb_type | ||
except ClientError as e: | ||
msg = e.response.get('Error', {}).get('Message', 'Unknown') | ||
if all(marker in msg for marker in [stack_id, 'does not exist']): | ||
raise ObjectNotFound(msg) | ||
else: | ||
raise e | ||
|
||
def get_request_count(self, lb_id: str, lb_type: str, minutes: int = 5): | ||
cw = boto3.client('cloudwatch', self.region) | ||
end = datetime.utcnow() | ||
start = end - timedelta(minutes=minutes) | ||
kwargs = { | ||
'MetricName': 'RequestCount', | ||
'StartTime': start, | ||
'EndTime': end, | ||
'Period': 60 * minutes, | ||
'Statistics': ['Sum'] | ||
} | ||
if lb_type == 'AWS::ElasticLoadBalancingV2::LoadBalancer': | ||
kwargs.update({ | ||
'Namespace': 'AWS/ApplicationELB', | ||
'Dimensions': [{ | ||
'Name': 'LoadBalancer', | ||
'Value': lb_id.split('/', 1)[1] | ||
}] | ||
}) | ||
elif lb_type == 'AWS::ElasticLoadBalancing::LoadBalancer': | ||
kwargs.update({ | ||
'Namespace': 'AWS/ELB', | ||
'Dimensions': [{ | ||
'Name': 'LoadBalancerName', | ||
'Value': lb_id | ||
}] | ||
}) | ||
else: | ||
raise Exception('unknown load balancer type: ' + lb_type) | ||
metrics = cw.get_metric_statistics(**kwargs) | ||
if len(metrics['Datapoints']) > 0: | ||
return int(metrics['Datapoints'][0]['Sum']) | ||
return 0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,5 @@ | ||
botocore | ||
boto3 | ||
connexion==1.1.5 | ||
environmental>=1.1 | ||
decorator | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
from unittest.mock import MagicMock | ||
|
||
import pytest | ||
|
||
|
||
@pytest.fixture | ||
def mock_aws(monkeypatch): | ||
mock = MagicMock() | ||
mock.return_value = mock | ||
|
||
monkeypatch.setattr('lizzy.api.AWS', mock) | ||
return mock |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
from unittest.mock import MagicMock | ||
|
||
import pytest | ||
from botocore.exceptions import ClientError | ||
|
||
from lizzy.apps.aws import AWS | ||
from lizzy.exceptions import (ObjectNotFound) | ||
|
||
|
||
def test_get_load_balancer_info_expired_token(monkeypatch): | ||
with pytest.raises(ClientError): | ||
cf = MagicMock() | ||
cf.describe_stack_resource.side_effect = ClientError( | ||
{'Error': { | ||
'Code': 'ExpiredToken', | ||
'Message': 'The security token included in the request is expired' | ||
}}, | ||
'DescribeStackResources' | ||
) | ||
monkeypatch.setattr('boto3.client', lambda *args, **kwargs: cf) | ||
aws = AWS('region') | ||
aws.get_load_balancer_info('stack-id-version') | ||
cf.describe_stack_resource.assert_called_with( | ||
**{'StackName': 'stack-id-version', 'LogicalResourceId': 'AppLoadBalancer'} | ||
) | ||
|
||
|
||
def test_get_load_balancer_info_stack_not_found(monkeypatch): | ||
with pytest.raises(ObjectNotFound) as e: | ||
cf = MagicMock() | ||
msg = "Stack 'stack-id-version' does not exist" | ||
cf.describe_stack_resource.side_effect = ClientError( | ||
{'Error': { | ||
'Code': 'ValidationError', | ||
'Message': msg | ||
}}, | ||
'DescribeStackResources' | ||
) | ||
monkeypatch.setattr('boto3.client', lambda *args, **kwargs: cf) | ||
aws = AWS('region') | ||
aws.get_load_balancer_info('stack-id-version') | ||
cf.describe_stack_resource.assert_called_with( | ||
**{'StackName': 'stack-id-version', 'LogicalResourceId': 'AppLoadBalancer'} | ||
) | ||
assert e.uid == msg | ||
|
||
|
||
def test_get_load_balancer_info_stack_without_load_balancer(monkeypatch): | ||
with pytest.raises(ObjectNotFound) as e: | ||
cf = MagicMock() | ||
msg = "Resource AppLoadBalancer does not exist for stack stack-id-version" | ||
cf.describe_stack_resource.side_effect = ClientError( | ||
{'Error': { | ||
'Code': 'ValidationError', | ||
'Message': msg | ||
}}, | ||
'DescribeStackResources' | ||
) | ||
monkeypatch.setattr('boto3.client', lambda *args, **kwargs: cf) | ||
aws = AWS('region') | ||
aws.get_load_balancer_info('stack-id-version') | ||
cf.describe_stack_resource.assert_called_with( | ||
**{'StackName': 'stack-id-version', 'LogicalResourceId': 'AppLoadBalancer'} | ||
) | ||
assert e.uid == msg | ||
|
||
|
||
def test_get_load_balancer_info_happy_path(monkeypatch): | ||
cf = MagicMock() | ||
cf.describe_stack_resource.return_value = { | ||
'StackResourceDetail': { | ||
'PhysicalResourceId': 'lb-id', | ||
'ResourceType': 'lb-type' | ||
} | ||
} | ||
monkeypatch.setattr('boto3.client', lambda *args, **kwargs: cf) | ||
aws = AWS('region') | ||
lb_id, lb_type = aws.get_load_balancer_info('stack-id-version') | ||
cf.describe_stack_resource.assert_called_with( | ||
**{'StackName': 'stack-id-version', 'LogicalResourceId': 'AppLoadBalancer'} | ||
) | ||
assert lb_id == 'lb-id' | ||
assert lb_type == 'lb-type' | ||
|
||
|
||
def test_get_request_count_invalid_lb_type(): | ||
aws = AWS('region') | ||
with pytest.raises(Exception) as e: | ||
aws.get_request_count('lb-id', 'invalid-lb-type') | ||
assert e.msg == 'unknown load balancer type: invalid-lb-type' | ||
|
||
|
||
@pytest.mark.parametrize( | ||
'elb_name, elb_type, response, expected_result', | ||
[ | ||
('lb_name', 'AWS::ElasticLoadBalancing::LoadBalancer', {'Datapoints': [{'Sum': 4176}]}, 4176), | ||
('lb_name', 'AWS::ElasticLoadBalancing::LoadBalancer', {'Datapoints': []}, 0), | ||
('arn:aws:cf:region:account:stack/stack-id-version/uuid', 'AWS::ElasticLoadBalancingV2::LoadBalancer', | ||
{'Datapoints': [{'Sum': 94374}]}, 94374), | ||
('arn:aws:cf:region:account:stack/stack-id-version/uuid', 'AWS::ElasticLoadBalancingV2::LoadBalancer', | ||
{'Datapoints': []}, 0), | ||
]) | ||
def test_get_load_balancer_with_classic_lb_sum_present(monkeypatch, elb_name, elb_type, response, expected_result): | ||
cw = MagicMock() | ||
cw.get_metric_statistics.return_value = response | ||
monkeypatch.setattr('boto3.client', lambda *args, **kwargs: cw) | ||
aws = AWS('region') | ||
request_count = aws.get_request_count(elb_name, elb_type) | ||
assert request_count == expected_result |