Passed
Push — master ( 99c26c...6c755b )
by
unknown
03:20
created

invoke_post_run()   B

Complexity

Conditions 3

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 33
rs 8.8571
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import logging as stdlib_logging
17
18
from st2actions.container.service import RunnerContainerService
19
from st2common import log as logging
20
from st2common.runners import base as runners
21
from st2common.util import action_db as action_db_utils
22
23
24
__all__ = [
25
    'get_logger_for_python_runner_action',
26
    'get_action_class_instance'
27
]
28
29
LOG = logging.getLogger(__name__)
30
31
32
def get_logger_for_python_runner_action(action_name):
33
    """
34
    Set up a logger which logs all the messages with level DEBUG and above to stderr.
35
    """
36
    logger_name = 'actions.python.%s' % (action_name)
37
    logger = logging.getLogger(logger_name)
38
39
    console = stdlib_logging.StreamHandler()
40
    console.setLevel(stdlib_logging.DEBUG)
41
42
    formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
43
    console.setFormatter(formatter)
44
    logger.addHandler(console)
45
    logger.setLevel(stdlib_logging.DEBUG)
46
47
    return logger
48
49
50
def get_action_class_instance(action_cls, config=None, action_service=None):
51
    """
52
    Instantiate and return Action class instance.
53
54
    :param action_cls: Action class to instantiate.
55
    :type action_cls: ``class``
56
57
    :param config: Config to pass to the action class.
58
    :type config: ``dict``
59
60
    :param action_service: ActionService instance to pass to the class.
61
    :type action_service: :class:`ActionService`
62
    """
63
    kwargs = {}
64
    kwargs['config'] = config
65
    kwargs['action_service'] = action_service
66
67
    # Note: This is done for backward compatibility reasons. We first try to pass
68
    # "action_service" argument to the action class constructor, but if that doesn't work (e.g. old
69
    # action which hasn't been updated yet), we resort to late assignment post class instantiation.
70
    # TODO: Remove in next major version once all the affected actions have been updated.
71
    try:
72
        action_instance = action_cls(**kwargs)
73
    except TypeError as e:
74
        if 'unexpected keyword argument \'action_service\'' not in str(e):
75
            raise e
76
77
        LOG.debug('Action class (%s) constructor doesn\'t take "action_service" argument, '
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
78
                  'falling back to late assignment...' % (action_cls.__class__.__name__))
79
80
        action_service = kwargs.pop('action_service', None)
81
        action_instance = action_cls(**kwargs)
82
        action_instance.action_service = action_service
83
84
    return action_instance
85
86
87
def invoke_post_run(liveaction_db, action_db=None):
88
    LOG.info('Invoking post run for action execution %s.', liveaction_db.id)
89
90
    # Identify action and runner.
91
    if not action_db:
92
        action_db = action_db_utils.get_action_by_ref(liveaction_db.action)
93
94
    if not action_db:
95
        LOG.exception('Unable to invoke post run. Action %s no longer exists.',
96
                      liveaction_db.action)
97
        return
98
99
    LOG.info('Action execution %s runs %s of runner type %s.',
100
             liveaction_db.id, action_db.name, action_db.runner_type['name'])
101
102
    # Get an instance of the action runner.
103
    runnertype_db = action_db_utils.get_runnertype_by_name(action_db.runner_type['name'])
104
    runner = runners.get_runner(runnertype_db.runner_module)
105
106
    # Configure the action runner.
107
    runner.container_service = RunnerContainerService()
108
    runner.action = action_db
109
    runner.action_name = action_db.name
110
    runner.action_execution_id = str(liveaction_db.id)
111
    runner.entry_point = RunnerContainerService.get_entry_point_abs_path(
112
        pack=action_db.pack, entry_point=action_db.entry_point)
113
    runner.context = getattr(liveaction_db, 'context', dict())
114
    runner.callback = getattr(liveaction_db, 'callback', dict())
115
    runner.libs_dir_path = RunnerContainerService.get_action_libs_abs_path(
116
        pack=action_db.pack, entry_point=action_db.entry_point)
117
118
    # Invoke the post_run method.
119
    runner.post_run(liveaction_db.status, liveaction_db.result)
120