GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#5)
by
unknown
09:42 queued 01:59
created

_get_action_instance()   B

Complexity

Conditions 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 23
rs 8.7972
cc 4
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 sys
17
import json
18
import argparse
19
import logging as stdlib_logging
20
21
from st2common import log as logging
22
from st2actions import config
23
from st2actions.runners.pythonrunner import Action
24
from st2common.util import loader as action_loader
25
from st2common.util.config_parser import ContentPackConfigParser
26
from st2common.constants.action import ACTION_OUTPUT_RESULT_DELIMITER
27
from st2common.service_setup import db_setup
28
from st2common.services.datastore import DatastoreService
29
30
__all__ = [
31
    'PythonActionWrapper'
32
]
33
34
LOG = logging.getLogger(__name__)
35
36
37
class PythonActionWrapper(object):
38
    def __init__(self, pack, file_path, parameters=None, parent_args=None):
0 ignored issues
show
Comprehensibility Bug introduced by
parameters is re-defining a name which is already available in the outer-scope (previously defined on line 134).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
Comprehensibility Bug introduced by
parent_args is re-defining a name which is already available in the outer-scope (previously defined on line 136).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
39
        """
40
        :param pack: Name of the pack this action belongs to.
41
        :type pack: ``str``
42
43
        :param file_path: Path to the action module.
44
        :type file_path: ``str``
45
46
        :param parameters: action parameters.
47
        :type parameters: ``dict`` or ``None``
48
49
        :param parent_args: Command line arguments passed to the parent process.
50
        :type parse_args: ``list``
51
        """
52
        db_setup()
53
54
        self._pack = pack
55
        self._file_path = file_path
56
        self._parameters = parameters or {}
57
        self._parent_args = parent_args or []
58
        self._class_name = None
59
        self._logger = logging.getLogger('PythonActionWrapper')
60
61
        try:
62
            config.parse_args(args=self._parent_args)
63
        except Exception:
64
            pass
65
66
    def run(self):
67
        action = self._get_action_instance()
68
        output = action.run(**self._parameters)
69
70
        # Print output to stdout so the parent can capture it
71
        sys.stdout.write(ACTION_OUTPUT_RESULT_DELIMITER)
72
        print_output = None
73
        try:
74
            print_output = json.dumps(output)
75
        except:
76
            print_output = str(output)
77
        sys.stdout.write(print_output + '\n')
78
        sys.stdout.write(ACTION_OUTPUT_RESULT_DELIMITER)
79
80
    def _get_action_instance(self):
81
        actions_cls = action_loader.register_plugin(Action, self._file_path)
82
        action_cls = actions_cls[0] if actions_cls and len(actions_cls) > 0 else None
83
84
        if not action_cls:
85
            raise Exception('File "%s" has no action or the file doesn\'t exist.' %
86
                            (self._file_path))
87
88
        config_parser = ContentPackConfigParser(pack_name=self._pack)
89
        config = config_parser.get_action_config(action_file_path=self._file_path)
0 ignored issues
show
Comprehensibility Bug introduced by
config is re-defining a name which is already available in the outer-scope (previously defined on line 22).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
90
91
        action_cls.datastore = DatastoreService(logger=self._set_up_logger(),
92
                                                pack_name=self._pack,
93
                                                class_name=action_cls.__name__,
94
                                                api_username="action_service")
95
        if config:
96
            LOG.info('Using config "%s" for action "%s"' % (config.file_path,
97
                                                            self._file_path))
98
99
            return action_cls(config=config.config)
100
        else:
101
            LOG.info('No config found for action "%s"' % (self._file_path))
102
            return action_cls(config={})
103
104
    def _set_up_logger(self):
105
        """
106
        Set up a logger which logs all the messages with level DEBUG
107
        and above to stderr.
108
        """
109
        logger = logging.getLogger('PythonActionWrapper')
110
111
        console = stdlib_logging.StreamHandler()
112
        console.setLevel(stdlib_logging.DEBUG)
113
114
        formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
115
        console.setFormatter(formatter)
116
        logger.addHandler(console)
117
        logger.setLevel(stdlib_logging.DEBUG)
118
119
        return logger
120
121
122
if __name__ == '__main__':
123
    parser = argparse.ArgumentParser(description='Python action runner process wrapper')
124
    parser.add_argument('--pack', required=True,
125
                        help='Name of the pack this action belongs to')
126
    parser.add_argument('--file-path', required=True,
127
                        help='Path to the action module')
128
    parser.add_argument('--parameters', required=False,
129
                        help='Serialized action parameters')
130
    parser.add_argument('--parent-args', required=False,
131
                        help='Command line arguments passed to the parent process')
132
    args = parser.parse_args()
133
134
    parameters = args.parameters
135
    parameters = json.loads(parameters) if parameters else {}
136
    parent_args = json.loads(args.parent_args) if args.parent_args else []
137
    assert isinstance(parent_args, list)
138
139
    obj = PythonActionWrapper(pack=args.pack,
140
                              file_path=args.file_path,
141
                              parameters=parameters,
142
                              parent_args=parent_args)
143
144
    obj.run()
145