Test Setup Failed
Push — master ( 561579...99c26c )
by
unknown
05:31
created

EntryPointController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 37
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
B get_one() 0 28 3
A get_all() 0 2 1
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
        result = []
138
        for item in resp.json:
139
            action_api = ActionAPI(**item)
140
            result.append(self._transform_action_api(action_api=action_api,
141
                                                     requester_user=requester_user))
142
        resp.json = result
143
        return resp
144
145
    @staticmethod
146
    def _transform_action_api(action_api, requester_user):
147
        action_id = action_api.id
148
        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...
149
                                                   requester_user=requester_user)
150
        action_api.parameters = result.get('parameters', {})
151
        return action_api
152
153
154
class EntryPointController(resource.ContentPackResourceController):
155
    model = ActionAPI
156
    access = Action
157
158
    supported_filters = {}
159
160
    def get_all(self):
161
        return abort(404)
162
163
    def get_one(self, ref_or_id, requester_user):
164
        """
165
            Outputs the file associated with action entry_point
166
167
            Handles requests:
168
                GET /actions/views/entry_point/1
169
        """
170
        LOG.info('GET /actions/views/entry_point with ref_or_id=%s', ref_or_id)
171
        action_db = self._get_by_ref_or_id(ref_or_id=ref_or_id)
172
173
        permission_type = PermissionType.ACTION_VIEW
174
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
175
                                                          resource_db=action_db,
176
                                                          permission_type=permission_type)
177
178
        pack = getattr(action_db, 'pack', None)
179
        entry_point = getattr(action_db, 'entry_point', None)
180
181
        abs_path = utils.get_entry_point_abs_path(pack, entry_point)
182
183
        if not abs_path:
184
            raise StackStormDBObjectNotFoundError('Action ref_or_id=%s has no entry_point to output'
185
                                                  % ref_or_id)
186
187
        with open(abs_path) as file:
188
            content = file.read()
189
190
        return content
191
192
193
class ActionViewsController(object):
194
    parameters = ParametersViewController()
195
    overview = OverviewController()
196
    entry_point = EntryPointController()
197
198
199
parameters_view_controller = ParametersViewController()
200
overview_controller = OverviewController()
201
entry_point_controller = EntryPointController()
202