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.
Passed
Push — regana/mac-dev ( 625243...be7637 )
by
unknown
09:18 queued 03:37
created

_get_action_instance()   B

Complexity

Conditions 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 28
rs 8.5806
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
parent_args is re-defining a name which is already available in the outer-scope (previously defined on line 143).

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
parameters is re-defining a name which is already available in the outer-scope (previously defined on line 141).

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
53
        self._pack = pack
54
        self._file_path = file_path
55
        self._parameters = parameters or {}
56
        self._parent_args = parent_args or []
57
        self._class_name = None
58
        self._logger = logging.getLogger('PythonActionWrapper')
59
60
        try:
61
            config.parse_args(args=self._parent_args)
62
        except Exception:
63
            pass
64
        else:
65
            db_setup()
66
67
    def run(self):
68
        action = self._get_action_instance()
69
        output = action.run(**self._parameters)
70
71
        # Print output to stdout so the parent can capture it
72
        sys.stdout.write(ACTION_OUTPUT_RESULT_DELIMITER)
73
        print_output = None
74
        try:
75
            print_output = json.dumps(output)
76
        except:
77
            print_output = str(output)
78
        sys.stdout.write(print_output + '\n')
79
        sys.stdout.write(ACTION_OUTPUT_RESULT_DELIMITER)
80
81
    def _get_action_instance(self):
82
        actions_cls = action_loader.register_plugin(Action, self._file_path)
83
        action_cls = actions_cls[0] if actions_cls and len(actions_cls) > 0 else None
84
85
        if not action_cls:
86
            raise Exception('File "%s" has no action or the file doesn\'t exist.' %
87
                            (self._file_path))
88
89
        config_parser = ContentPackConfigParser(pack_name=self._pack)
90
        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...
91
92
        if config:
93
            LOG.info('Using config "%s" for action "%s"' % (config.file_path,
94
                                                            self._file_path))
95
96
            action_instance = action_cls(config=config.config)
97
        else:
98
            LOG.info('No config found for action "%s"' % (self._file_path))
99
            action_instance = action_cls(config={})
100
101
        # Setup action_instance proeprties
102
        action_instance.logger = self._set_up_logger(action_cls.__name__)
103
        action_instance.datastore = DatastoreService(logger=action_instance.logger,
104
                                                     pack_name=self._pack,
105
                                                     class_name=action_cls.__name__,
106
                                                     api_username="action_service")
107
108
        return action_instance
109
110
    def _set_up_logger(self, action_name):
111
        """
112
        Set up a logger which logs all the messages with level DEBUG
113
        and above to stderr.
114
        """
115
        logger_name = 'actions.python.%s' % (action_name)
116
        logger = logging.getLogger(logger_name)
117
118
        console = stdlib_logging.StreamHandler()
119
        console.setLevel(stdlib_logging.DEBUG)
120
121
        formatter = stdlib_logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
122
        console.setFormatter(formatter)
123
        logger.addHandler(console)
124
        logger.setLevel(stdlib_logging.DEBUG)
125
126
        return logger
127
128
129
if __name__ == '__main__':
130
    parser = argparse.ArgumentParser(description='Python action runner process wrapper')
131
    parser.add_argument('--pack', required=True,
132
                        help='Name of the pack this action belongs to')
133
    parser.add_argument('--file-path', required=True,
134
                        help='Path to the action module')
135
    parser.add_argument('--parameters', required=False,
136
                        help='Serialized action parameters')
137
    parser.add_argument('--parent-args', required=False,
138
                        help='Command line arguments passed to the parent process')
139
    args = parser.parse_args()
140
141
    parameters = args.parameters
142
    parameters = json.loads(parameters) if parameters else {}
143
    parent_args = json.loads(args.parent_args) if args.parent_args else []
144
145
    assert isinstance(parent_args, list)
146
147
    obj = PythonActionWrapper(pack=args.pack,
148
                              file_path=args.file_path,
149
                              parameters=parameters,
150
                              parent_args=parent_args)
151
152
    obj.run()
153