Test Failed
Push — master ( e380d0...f5671d )
by W
02:58
created

st2api/st2api/controllers/v1/action_views.py (5 issues)

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
from mongoengine import ValidationError
17
import six
18
19
from st2api.controllers import resource
20
from st2common.exceptions.db import StackStormDBObjectNotFoundError
21
from st2common import log as logging
22
from st2common.content import utils
23
from st2common.models.api.action import ActionAPI
24
from st2common.models.utils import action_param_utils
25
from st2common.persistence.action import Action
26
from st2common.persistence.runner import RunnerType
27
from st2common.rbac.types import PermissionType
28
from st2common.rbac import utils as rbac_utils
29
from st2common.router import abort
30
31
__all__ = [
32
    'OverviewController',
33
    'ParametersViewController',
34
    'EntryPointController'
35
]
36
37
http_client = six.moves.http_client
38
39
LOG = logging.getLogger(__name__)
40
41
42
class LookupUtils(object):
43
44
    @staticmethod
45
    def _get_action_by_id(id):
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in id.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
46
        try:
47
            return Action.get_by_id(id)
48
        except Exception as e:
49
            msg = 'Database lookup for id="%s" resulted in exception. %s' % (id, e)
50
            LOG.exception(msg)
51
            abort(http_client.NOT_FOUND, msg)
52
53
    @staticmethod
54
    def _get_runner_by_id(id):
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in id.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
55
        try:
56
            return RunnerType.get_by_id(id)
57
        except (ValueError, ValidationError) as e:
58
            msg = 'Database lookup for id="%s" resulted in exception. %s' % (id, e)
59
            LOG.exception(msg)
60
            abort(http_client.NOT_FOUND, msg)
61
62
    @staticmethod
63
    def _get_runner_by_name(name):
64
        try:
65
            return RunnerType.get_by_name(name)
66
        except (ValueError, ValidationError) as e:
67
            msg = 'Database lookup for name="%s" resulted in exception. %s' % (id, e)
68
            LOG.exception(msg)
69
            abort(http_client.NOT_FOUND, msg)
70
71
72
class ParametersViewController(object):
73
74
    def get_one(self, action_id, requester_user):
75
        return self._get_one(action_id, requester_user=requester_user)
76
77
    @staticmethod
78
    def _get_one(action_id, requester_user):
79
        """
80
            List merged action & runner parameters by action id.
81
82
            Handle:
83
                GET /actions/views/parameters/1
84
        """
85
        action_db = LookupUtils._get_action_by_id(action_id)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _get_action_by_id was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
86
        LOG.info('Found action: %s, runner: %s', action_db, action_db.runner_type['name'])
87
88
        permission_type = PermissionType.ACTION_VIEW
89
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
90
                                                          resource_db=action_db,
91
                                                          permission_type=permission_type)
92
93
        runner_db = LookupUtils._get_runner_by_name(action_db.runner_type['name'])
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _get_runner_by_name was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
94
        all_params = action_param_utils.get_params_view(
95
            action_db=action_db, runner_db=runner_db, merged_only=True)
96
97
        return {'parameters': all_params}
98
99
100
class OverviewController(resource.ContentPackResourceController):
101
    model = ActionAPI
102
    access = Action
103
    supported_filters = {}
104
105
    query_options = {
106
        'sort': ['pack', 'name']
107
    }
108
109
    include_reference = True
110
111
    def get_one(self, ref_or_id, requester_user):
112
        """
113
            List action by id.
114
115
            Handle:
116
                GET /actions/views/overview/1
117
        """
118
        resp = super(OverviewController, self)._get_one(ref_or_id,
119
                                                        requester_user=requester_user,
120
                                                        permission_type=PermissionType.ACTION_VIEW)
121
        action_api = ActionAPI(**resp.json)
122
        result = self._transform_action_api(action_api=action_api, requester_user=requester_user)
123
        resp.json = result
124
        return resp
125
126
    def get_all(self, sort=None, offset=0, limit=None, requester_user=None, **raw_filters):
127
        """
128
            List all actions.
129
130
            Handles requests:
131
                GET /actions/views/overview
132
        """
133
        resp = super(OverviewController, self)._get_all(sort=sort,
134
                                                        offset=offset,
135
                                                        limit=limit,
136
                                                        raw_filters=raw_filters,
137
                                                        requester_user=requester_user)
138
        result = []
139
        for item in resp.json:
140
            action_api = ActionAPI(**item)
141
            result.append(self._transform_action_api(action_api=action_api,
142
                                                     requester_user=requester_user))
143
        resp.json = result
144
        return resp
145
146
    @staticmethod
147
    def _transform_action_api(action_api, requester_user):
148
        action_id = action_api.id
149
        result = ParametersViewController._get_one(action_id=action_id,
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _get_one was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
150
                                                   requester_user=requester_user)
151
        action_api.parameters = result.get('parameters', {})
152
        return action_api
153
154
155
class EntryPointController(resource.ContentPackResourceController):
156
    model = ActionAPI
157
    access = Action
158
159
    supported_filters = {}
160
161
    def get_all(self):
162
        return abort(404)
163
164
    def get_one(self, ref_or_id, requester_user):
165
        """
166
            Outputs the file associated with action entry_point
167
168
            Handles requests:
169
                GET /actions/views/entry_point/1
170
        """
171
        LOG.info('GET /actions/views/entry_point with ref_or_id=%s', ref_or_id)
172
        action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
173
174
        permission_type = PermissionType.ACTION_VIEW
175
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
176
                                                          resource_db=action_db,
177
                                                          permission_type=permission_type)
178
179
        pack = getattr(action_db, 'pack', None)
180
        entry_point = getattr(action_db, 'entry_point', None)
181
182
        abs_path = utils.get_entry_point_abs_path(pack, entry_point)
183
184
        if not abs_path:
185
            raise StackStormDBObjectNotFoundError('Action ref_or_id=%s has no entry_point to output'
186
                                                  % ref_or_id)
187
188
        with open(abs_path) as file:
189
            content = file.read()
190
191
        return content
192
193
194
class ActionViewsController(object):
195
    parameters = ParametersViewController()
196
    overview = OverviewController()
197
    entry_point = EntryPointController()
198
199
200
parameters_view_controller = ParametersViewController()
201
overview_controller = OverviewController()
202
entry_point_controller = EntryPointController()
203