Test Failed
Pull Request — master (#3658)
by Lakshmi
06:41
created

ActionRunner.get_pack_ref()   A

Complexity

Conditions 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
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 abc
17
import six
18
from oslo_config import cfg
19
20
from st2common import log as logging
21
from st2common.constants import action as action_constants
22
from st2common.constants import pack as pack_constants
23
from st2common.exceptions.actionrunner import ActionRunnerCreateError
24
from st2common.util import action_db as action_utils
25
from st2common.util.loader import register_runner, register_callback_module
26
from st2common.util.api import get_full_public_api_url
27
from st2common.util.deprecation import deprecated
28
29
__all__ = [
30
    'ActionRunner',
31
    'AsyncActionRunner',
32
    'ShellRunnerMixin',
33
    'get_runner'
34
]
35
36
37
LOG = logging.getLogger(__name__)
38
39
# constants to lookup in runner_parameters
40
RUNNER_COMMAND = 'cmd'
41
42
43
def get_runner(module_name):
44
    """Load the module and return an instance of the runner."""
45
46
    LOG.debug('Runner loading python module: %s', module_name)
47
    try:
48
        # TODO: Explore modifying this to support register_plugin
49
        module = register_runner(module_name)
50
    except Exception as e:
51
        LOG.exception('Failed to import module %s.', module_name)
52
        raise ActionRunnerCreateError(e)
53
54
    LOG.debug('Instance of runner module: %s', module)
55
56
    runner = module.get_runner()
57
    LOG.debug('Instance of runner: %s', runner)
58
    return runner
59
60
61
@six.add_metaclass(abc.ABCMeta)
62
class ActionRunner(object):
63
    """
64
        The interface that must be implemented by each StackStorm
65
        Action Runner implementation.
66
    """
67
68
    def __init__(self, runner_id):
69
        """
70
        :param id: Runner id.
71
        :type id: ``str``
72
        """
73
        self.runner_id = runner_id
74
75
        self.runner_type_db = None
76
        self.runner_parameters = None
77
        self.action = None
78
        self.action_name = None
79
        self.liveaction = None
80
        self.liveaction_id = None
81
        self.execution = None
82
        self.execution_id = None
83
        self.entry_point = None
84
        self.libs_dir_path = None
85
        self.context = None
86
        self.callback = None
87
        self.auth_token = None
88
        self.rerun_ex_ref = None
89
90
    def pre_run(self):
91
        runner_enabled = getattr(self.runner_type_db, 'enabled', True)
92
        runner_name = getattr(self.runner_type_db, 'name', 'unknown')
93
        if not runner_enabled:
94
            msg = ('Runner "%s" has been disabled by the administrator' %
95
                   (runner_name))
96
            raise ValueError(msg)
97
98
    # Run will need to take an action argument
99
    # Run may need result data argument
100
    @abc.abstractmethod
101
    def run(self, action_parameters):
102
        raise NotImplementedError()
103
104
    def pause(self):
105
        runner_name = getattr(self.runner_type_db, 'name', 'unknown')
106
        raise NotImplementedError('Pause is not supported for runner %s.' % runner_name)
107
108
    def resume(self):
109
        runner_name = getattr(self.runner_type_db, 'name', 'unknown')
110
        raise NotImplementedError('Resume is not supported for runner %s.' % runner_name)
111
112
    def cancel(self):
113
        return (
114
            action_constants.LIVEACTION_STATUS_CANCELED,
115
            self.liveaction.result,
116
            self.liveaction.context
117
        )
118
119
    def post_run(self, status, result):
120
        callback = self.callback or {}
121
122
        if callback and not (set(['url', 'source']) - set(callback.keys())):
0 ignored issues
show
Unused Code Coding Style introduced by
There is an unnecessary parenthesis after not.
Loading history...
123
            callback_url = callback['url']
124
            callback_module_name = callback['source']
125
126
            try:
127
                callback_module = register_callback_module(callback_module_name)
128
            except:
129
                LOG.exception('Failed importing callback module: %s', callback_module_name)
130
131
            callback_handler = callback_module.get_instance()
132
133
            callback_handler.callback(
134
                callback_url,
135
                self.context,
136
                status,
137
                result
138
            )
139
140
    @deprecated
141
    def get_pack_name(self):
142
        return self.get_pack_ref()
143
144
    def get_pack_ref(self):
145
        """
146
        Retrieve pack name for the action which is being currently executed.
147
148
        :rtype: ``str``
149
        """
150
        if self.action:
151
            return self.action.pack
152
153
        return pack_constants.DEFAULT_PACK_NAME
154
155
    def get_user(self):
156
        """
157
        Retrieve a name of the user which triggered this action execution.
158
159
        :rtype: ``str``
160
        """
161
        context = getattr(self, 'context', {}) or {}
162
        user = context.get('user', cfg.CONF.system_user.user)
163
164
        return user
165
166
    def _get_common_action_env_variables(self):
167
        """
168
        Retrieve common ST2_ACTION_ environment variables which will be available to the action.
169
170
        Note: Environment variables are prefixed with ST2_ACTION_* so they don't clash with CLI
171
        environment variables.
172
173
        :rtype: ``dict``
174
        """
175
        result = {}
176
        result['ST2_ACTION_PACK_NAME'] = self.get_pack_ref()
177
        result['ST2_ACTION_EXECUTION_ID'] = str(self.execution_id)
178
        result['ST2_ACTION_API_URL'] = get_full_public_api_url()
179
180
        if self.auth_token:
181
            result['ST2_ACTION_AUTH_TOKEN'] = self.auth_token.token
182
183
        return result
184
185
    def __str__(self):
186
        attrs = ', '.join(['%s=%s' % (k, v) for k, v in six.iteritems(self.__dict__)])
187
        return '%s@%s(%s)' % (self.__class__.__name__, str(id(self)), attrs)
188
189
190
@six.add_metaclass(abc.ABCMeta)
191
class AsyncActionRunner(ActionRunner):
192
    pass
193
194
195
class ShellRunnerMixin(object):
196
    """
197
    Class which contains utility functions to be used by shell runners.
198
    """
199
200
    def _transform_named_args(self, named_args):
201
        """
202
        Transform named arguments to the final form.
203
204
        :param named_args: Named arguments.
205
        :type named_args: ``dict``
206
207
        :rtype: ``dict``
208
        """
209
        if named_args:
210
            return {self._kwarg_op + k: v for (k, v) in six.iteritems(named_args)}
211
        return None
212
213
    def _get_script_args(self, action_parameters):
214
        """
215
        :param action_parameters: Action parameters.
216
        :type action_parameters: ``dict``
217
218
        :return: (positional_args, named_args)
219
        :rtype: (``str``, ``dict``)
220
        """
221
        # TODO: return list for positional args, command classes should escape it
222
        # and convert it to string
223
224
        is_script_run_as_cmd = self.runner_parameters.get(RUNNER_COMMAND, None)
225
226
        pos_args = ''
227
        named_args = {}
228
229
        if is_script_run_as_cmd:
230
            pos_args = self.runner_parameters.get(RUNNER_COMMAND, '')
231
            named_args = action_parameters
232
        else:
233
            pos_args, named_args = action_utils.get_args(action_parameters, self.action)
234
235
        return pos_args, named_args
236