Skip to content

Commit

Permalink
Throw EventNotSupportedError if unkonwn event was given
Browse files Browse the repository at this point in the history
  • Loading branch information
janschumann committed Dec 13, 2018
1 parent 749c1cf commit 2b3d64d
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 34 deletions.
57 changes: 28 additions & 29 deletions AutoscalingLifecycle/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
from logging import Logger
from logging import DEBUG
from logging import Logger

from transitions import EventData
from transitions import Machine
Expand All @@ -14,6 +14,12 @@
from .logging import Formatter
from .logging import Logging
from .logging import MessageFormatter
from .exceptions import ConfigurationError
from .exceptions import TriggerParameterConfigurationError
from .exceptions import StopIterationAfterTrigger
from .exceptions import StopProcessingAfterStateChange
from .exceptions import CommandNotFoundError
from .exceptions import EventNotSupportedError


def listify(obj):
Expand All @@ -23,10 +29,10 @@ def listify(obj):


class LifecycleData(object):

LAUNCHING = 'autoscaling:EC2_INSTANCE_LAUNCHING'
TERMINATING = 'autoscaling:EC2_INSTANCE_TERMINATING'


def __init__(self, data: dict):
self.data = data
self.metadata = self.data.get('NotificationMetadata')
Expand Down Expand Up @@ -121,11 +127,13 @@ def __init__(self, event: dict):

self.name = self._event.get('detail-type')
if self.is_command():
# unmarshal parameters
self.get_detail().update({ 'parameters': json.loads(self.get_detail().get('parameters')) })
if self.is_lifecycle():
self.name = '%s for %s' % (self.name, self._lifecycle_data.get_lifecycle_transition())

elif self.is_scheduled():
self.name = self._event.get('resources')[0].split('/')[-1]
self.name = self.get_resources()[0]


def get_name(self):
Expand Down Expand Up @@ -217,13 +225,17 @@ def to_str(self):
if self.is_command():
msg = '%s finished commands %s on %s' % (
msg,
','.join(json.loads(self.get_detail().get('parameters')).get('commands')),
','.join([resource.split('/')[-1] for resource in self._event.get('resources')])
','.join(self.get_detail().get('parameters').get('commands')),
','.join(self.get_resources())
)

return msg


def get_resources(self) -> list:
return [resource.split('/')[-1] for resource in self._event.get('resources')]


def is_successful(self, *args) -> bool:
"""
*args are required to support this method within transition configs
Expand Down Expand Up @@ -319,7 +331,11 @@ def node(self, node: Node):
def initialize(self, event: Event):
self.event = event
if self.event.is_command():
command = self.get_command_repository().pop(self.event.get_raw().get('detail').get('command-id'))
try:
command = self.get_command_repository().pop(self.event.get_raw().get('detail').get('command-id'))
except CommandNotFoundError:
raise EventNotSupportedError('This event does not support this event.')

self.event.set_lifecycle_data(command.get('LifecycleData', dict()))
self.event.set_name(command.get('EventName', ''))

Expand Down Expand Up @@ -403,7 +419,7 @@ def _send_command(self, comment: str, commands: list, target_nodes = None, comma
}

if self.event.is_lifecycle():
metadata.update({'LifecycleData': self.event.get_lifecycle_data().to_dict()})
metadata.update({ 'LifecycleData': self.event.get_lifecycle_data().to_dict() })

command_id = self.clients.get('ssm').send_command(target_node_ids, comment, commands, command_timeout)
self.repositories.get('command').register(command_id, metadata)
Expand Down Expand Up @@ -448,27 +464,6 @@ def do_remove_from_db(self, *args):
self.repositories.get('node').delete(self.node)


class ConfigurationError(RuntimeError):
def get_message(self):
return self.args[0]


class TriggerParameterConfigurationError(ConfigurationError):
pass


class StopIterationAfterTrigger(Exception):
""" Signal the end trigger from LifecycleHandler.__process(). """
def get_message(self):
return self.args[0]


class StopProcessingAfterStateChange(Exception):
""" Signal the end from LifecycleHandler.__process(). """
def get_message(self):
return self.args[0]


class LifecycleHandler(object):
"""
:type machine: Machine
Expand Down Expand Up @@ -501,6 +496,7 @@ class LifecycleHandler(object):
'trigger'
]


#
# initialization
#
Expand Down Expand Up @@ -726,6 +722,7 @@ def __process(self, triggers: list):
else:
self.__process(triggers)


#
# private built-in trigger functions
#
Expand Down Expand Up @@ -791,7 +788,9 @@ def __log_autoscaling_activity(self, event_data: EventData):
repr(event_data), activity)

if activity == dict():
self.__get_logger().warning('Could not find autoscaling activity for node %s', _lifecycle_data.get_instance_id())
self.__get_logger().warning('Could not find autoscaling activity for node %s',
_lifecycle_data.get_instance_id())


#
# convenience methods
Expand Down
3 changes: 2 additions & 1 deletion AutoscalingLifecycle/entity.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from logging import Logger

from .clients import DynamoDbClient
from .exceptions import CommandNotFoundError


class Repository(object):
Expand Down Expand Up @@ -42,7 +43,7 @@ def get(self, id: str):
def pop(self, id: str):
command = self.get(id)
if command == { }:
raise RuntimeError('Could not load command %s.' % id)
raise CommandNotFoundError('Could not load command %s.' % id)
self.delete(id)

return command
Expand Down
30 changes: 30 additions & 0 deletions AutoscalingLifecycle/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

class BaseError(RuntimeError):
def get_message(self):
return self.args[0]


class CommandNotFoundError(BaseError):
pass


class ConfigurationError(BaseError):
pass


class TriggerParameterConfigurationError(BaseError):
pass


class StopIterationAfterTrigger(BaseError):
""" Signal the end trigger from LifecycleHandler.__process(). """
pass


class StopProcessingAfterStateChange(BaseError):
""" Signal the end from LifecycleHandler.__process(). """
pass


class EventNotSupportedError(BaseError):
pass
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## 0.61.0

IMPROVEMENTS:

* Throw EventNotSupportedError if unkonwn event was given
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
deps:
python3.6 -m venv pyenv
pyenv/bin/pip install --upgrade -r requirements.txt
python3.6 -m venv .venv
.venv/bin/pip install --upgrade -r requirements.txt

test: deps
pyenv/bin/python -m unittest discover
.venv/bin/python -m unittest discover

show-version:
@cat setup.py | grep version | sed 's/.*version = "//' | sed 's/",//'
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

setuptools.setup(
name = "AutoscalingLifecycle",
version = "0.60.0",
version = "0.61.0",
author = "Jan Schumann",
author_email = "[email protected]",
description = "A library to handle aws autoscaling lifecycle events",
Expand Down

0 comments on commit 2b3d64d

Please sign in to comment.