|
| 1 | +import logging |
| 2 | +from samtranslator.model.exceptions import InvalidResourceException, InvalidDocumentException |
| 3 | +from samtranslator.plugins import BasePlugin, LifeCycleEvents |
| 4 | + |
| 5 | +LOG = logging.getLogger(__name__) |
| 6 | + |
| 7 | + |
| 8 | +class SamPlugins(object): |
| 9 | + """ |
| 10 | + Class providing support for arbitrary plugins that can extend core SAM translator in interesting ways. |
| 11 | + Use this class to register plugins that get called when certain life cycle events happen in the translator. |
| 12 | + Plugins work only on resources that are natively supported by SAM (ie. AWS::Serverless::* resources) |
| 13 | +
|
| 14 | + Following Life Cycle Events are available: |
| 15 | +
|
| 16 | + **Resource Level** |
| 17 | + - before_transform_resource: Invoked before SAM translator processes a resource's properties. |
| 18 | + - [Coming Soon] after_transform_resource |
| 19 | +
|
| 20 | + **Template Level** |
| 21 | + - before_transform_template |
| 22 | + - after_transform_template |
| 23 | +
|
| 24 | + When a life cycle event happens in the translator, this class will invoke the corresponding "hook" method on the |
| 25 | + each of the registered plugins to process. Plugins are free to modify internal state of the template or resources |
| 26 | + as they see fit. They can even raise an exception when the resource or template doesn't contain properties |
| 27 | + of certain structure (Ex: Only PolicyTemplates are allowed in SAM template) |
| 28 | +
|
| 29 | + ## Plugin Implementation |
| 30 | +
|
| 31 | + ### Defining a plugin |
| 32 | + A plugin is a subclass of `BasePlugin` that implements one or more methods capable of processing the life cycle |
| 33 | + events. |
| 34 | + These methods have a prefix `on_` followed by the name of the life cycle event. For example, to handle |
| 35 | + `before_transform_resource` event, implement a method called `on_before_transform_resource`. We call these methods |
| 36 | + as "hooks" which are methods capable of handling this event. |
| 37 | +
|
| 38 | + ### Hook Methods |
| 39 | + Arguments passed to the hook method is different for each life cycle event. Check out the hook methods in the |
| 40 | + `BasePlugin` class for detailed description of the method signature |
| 41 | +
|
| 42 | + ### Raising validation errors |
| 43 | + Plugins must raise an `samtranslator.model.exception.InvalidResourceException` when the input SAM template does |
| 44 | + not conform to the expectation |
| 45 | + set by the plugin. SAM translator will convert this into a nice error message and display to the user. |
| 46 | + """ |
| 47 | + |
| 48 | + def __init__(self, initial_plugins=None): |
| 49 | + """ |
| 50 | + Initialize the plugins class with an optional list of plugins |
| 51 | +
|
| 52 | + :param BasePlugin or list initial_plugins: Single plugin or a List of plugins to initialize with |
| 53 | + """ |
| 54 | + self._plugins = [] |
| 55 | + |
| 56 | + if initial_plugins is None: |
| 57 | + initial_plugins = [] |
| 58 | + |
| 59 | + if not isinstance(initial_plugins, list): |
| 60 | + initial_plugins = [initial_plugins] |
| 61 | + |
| 62 | + for plugin in initial_plugins: |
| 63 | + self.register(plugin) |
| 64 | + |
| 65 | + def register(self, plugin): |
| 66 | + """ |
| 67 | + Register a plugin. New plugins are added to the end of the plugins list. |
| 68 | +
|
| 69 | + :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks |
| 70 | + :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already |
| 71 | + registered |
| 72 | + :return: None |
| 73 | + """ |
| 74 | + |
| 75 | + if not plugin or not isinstance(plugin, BasePlugin): |
| 76 | + raise ValueError("Plugin must be implemented as a subclass of BasePlugin class") |
| 77 | + |
| 78 | + if self.is_registered(plugin.name): |
| 79 | + raise ValueError("Plugin with name {} is already registered".format(plugin.name)) |
| 80 | + |
| 81 | + self._plugins.append(plugin) |
| 82 | + |
| 83 | + def is_registered(self, plugin_name): |
| 84 | + """ |
| 85 | + Checks if a plugin with given name is already registered |
| 86 | +
|
| 87 | + :param plugin_name: Name of the plugin |
| 88 | + :return: True if plugin with given name is already registered. False, otherwise |
| 89 | + """ |
| 90 | + |
| 91 | + return plugin_name in [p.name for p in self._plugins] |
| 92 | + |
| 93 | + def _get(self, plugin_name): |
| 94 | + """ |
| 95 | + Retrieves the plugin with given name |
| 96 | +
|
| 97 | + :param plugin_name: Name of the plugin to retrieve |
| 98 | + :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise |
| 99 | + """ |
| 100 | + |
| 101 | + for p in self._plugins: |
| 102 | + if p.name == plugin_name: |
| 103 | + return p |
| 104 | + |
| 105 | + return None |
| 106 | + |
| 107 | + def act(self, event, *args, **kwargs): |
| 108 | + """ |
| 109 | + Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. |
| 110 | + *args and **kwargs will be passed directly to the plugin's hook functions |
| 111 | +
|
| 112 | + :param samtranslator.plugins.LifeCycleEvents event: Event to act upon |
| 113 | + :return: Nothing |
| 114 | + :raises ValueError: If event is not a valid life cycle event |
| 115 | + :raises NameError: If a plugin does not have the hook method defined |
| 116 | + :raises Exception: Any exception that a plugin raises |
| 117 | + """ |
| 118 | + |
| 119 | + if not isinstance(event, LifeCycleEvents): |
| 120 | + raise ValueError("'event' must be an instance of LifeCycleEvents class") |
| 121 | + |
| 122 | + method_name = "on_" + event.name |
| 123 | + |
| 124 | + for plugin in self._plugins: |
| 125 | + |
| 126 | + if not hasattr(plugin, method_name): |
| 127 | + raise NameError( |
| 128 | + "'{}' method is not found in the plugin with name '{}'".format(method_name, plugin.name) |
| 129 | + ) |
| 130 | + |
| 131 | + try: |
| 132 | + getattr(plugin, method_name)(*args, **kwargs) |
| 133 | + except (InvalidResourceException, InvalidDocumentException) as ex: |
| 134 | + # Don't need to log these because they don't result in crashes |
| 135 | + raise ex |
| 136 | + except Exception as ex: |
| 137 | + LOG.exception("Plugin '%s' raised an exception: %s", plugin.name, ex) |
| 138 | + raise ex |
| 139 | + |
| 140 | + def __len__(self): |
| 141 | + """ |
| 142 | + Returns the number of plugins registered with this class |
| 143 | +
|
| 144 | + :return integer: Number of plugins registered |
| 145 | + """ |
| 146 | + return len(self._plugins) |
0 commit comments