Completed
Pull Request — master (#2842)
by Edward
05:07
created

PackSearchController   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 8
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A post() 0 6 2
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 pecan
17
from pecan.rest import RestController
18
import six
19
20
import st2common
21
from st2common import log as logging
22
from st2common.bootstrap.triggersregistrar import TriggersRegistrar
23
from st2common.bootstrap.sensorsregistrar import SensorsRegistrar
24
from st2common.bootstrap.actionsregistrar import ActionsRegistrar
25
from st2common.bootstrap.aliasesregistrar import AliasesRegistrar
26
from st2common.bootstrap.policiesregistrar import PolicyRegistrar
27
import st2common.bootstrap.policiesregistrar as policies_registrar
28
import st2common.bootstrap.runnersregistrar as runners_registrar
29
from st2common.bootstrap.rulesregistrar import RulesRegistrar
30
import st2common.bootstrap.ruletypesregistrar as rule_types_registrar
31
from st2common.bootstrap.configsregistrar import ConfigsRegistrar
32
import st2common.content.utils as content_utils
33
from st2common.models.api.base import jsexpose
34
from st2api.controllers.resource import ResourceController
35
from st2api.controllers.v1.actionexecutions import ActionExecutionsControllerMixin
36
from st2common.models.api.action import LiveActionCreateAPI
37
from st2common.models.api.pack import PackAPI
38
from st2common.models.api.pack import PackInitRequestAPI
39
from st2common.models.api.pack import PackInstallRequestAPI
40
from st2common.models.api.pack import PackRegisterRequestAPI
41
from st2common.models.api.pack import PackSearchRequestAPI
42
from st2common.models.api.pack import PackAsyncAPI
43
from st2common.persistence.pack import Pack
44
from st2common.rbac.types import PermissionType
45
from st2common.rbac.decorators import request_user_has_permission
46
from st2common.rbac.decorators import request_user_has_resource_db_permission
47
from st2common.services import packs as packs_service
48
49
http_client = six.moves.http_client
50
51
__all__ = [
52
    'PacksController',
53
    'BasePacksController'
54
]
55
56
LOG = logging.getLogger(__name__)
57
58
ENTITIES = {
59
    'action': (ActionsRegistrar, 'actions'),
60
    'trigger': (TriggersRegistrar, 'triggers'),
61
    'sensor': (SensorsRegistrar, 'sensors'),
62
    'rule': (RulesRegistrar, 'rules'),
63
    'alias': (AliasesRegistrar, 'aliases'),
64
    'policy': (PolicyRegistrar, 'policy'),
65
    'config': (ConfigsRegistrar, 'config')
66
}
67
68
69
class PackInitController(ActionExecutionsControllerMixin, RestController):
70
71
    @jsexpose(body_cls=PackInitRequestAPI, status_code=http_client.ACCEPTED)
72
    def post(self, args):
73
        parameters = vars(args)
74
75
        new_liveaction_api = LiveActionCreateAPI(action='packs.create',
76
                                                 parameters=parameters,
77
                                                 user=None)
78
79
        execution = self._handle_schedule_execution(liveaction_api=new_liveaction_api)
80
81
        return PackAsyncAPI(execution_id=execution.id)
82
83
84
class PackInstallController(ActionExecutionsControllerMixin, RestController):
85
86
    @jsexpose(body_cls=PackInstallRequestAPI, status_code=http_client.ACCEPTED)
87
    def post(self, pack_install_request):
88
        parameters = {
89
            'packs': pack_install_request.packs
90
        }
91
92
        new_liveaction_api = LiveActionCreateAPI(action='packs.install',
93
                                                 parameters=parameters,
94
                                                 user=None)
95
96
        execution = self._handle_schedule_execution(liveaction_api=new_liveaction_api)
97
98
        return PackAsyncAPI(execution_id=execution.id)
99
100
101
class PackUninstallController(ActionExecutionsControllerMixin, RestController):
102
103
    @jsexpose(body_cls=PackInstallRequestAPI, arg_types=[str], status_code=http_client.ACCEPTED)
104
    def post(self, pack_uninstall_request, ref_or_id=None):
105
        if ref_or_id:
106
            parameters = {
107
                'packs': [ref_or_id]
108
            }
109
        else:
110
            parameters = {
111
                'packs': pack_uninstall_request.packs
112
            }
113
114
        new_liveaction_api = LiveActionCreateAPI(action='packs.uninstall',
115
                                                 parameters=parameters,
116
                                                 user=None)
117
118
        execution = self._handle_schedule_execution(liveaction_api=new_liveaction_api)
119
120
        return PackAsyncAPI(execution_id=execution.id)
121
122
123
class PackRegisterController(RestController):
124
125
    @jsexpose(body_cls=PackRegisterRequestAPI)
126
    def post(self, pack_register_request):
127
        if pack_register_request and hasattr(pack_register_request, 'types'):
128
            types = pack_register_request.types
129
        else:
130
            types = ['runner', 'action', 'trigger', 'sensor', 'rule', 'rule_type', 'alias',
131
                     'policy_type', 'policy', 'config']
132
133
        if pack_register_request and hasattr(pack_register_request, 'packs'):
134
            packs = pack_register_request.packs
135
        else:
136
            packs = None
137
138
        result = {}
139
140
        if 'runner' in types or 'action' in types:
141
            result['runners'] = runners_registrar.register_runners(experimental=True)
142
        if 'rule_type' in types or 'rule' in types:
143
            result['rule_types'] = rule_types_registrar.register_rule_types()
144
        if 'policy_type' in types or 'policy' in types:
145
            result['policy_types'] = policies_registrar.register_policy_types(st2common)
146
147
        use_pack_cache = True
148
149
        for type, (Registrar, name) in six.iteritems(ENTITIES):
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in type.

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

Loading history...
150
            if type in types:
151
                registrar = Registrar(use_pack_cache=use_pack_cache,
152
                                      fail_on_failure=False)
153
                if packs:
154
                    for pack in packs:
155
                        pack_path = content_utils.get_pack_base_path(pack)
156
                        result[name] = registrar.register_from_pack(pack_dir=pack_path)
157
                else:
158
                    packs_base_paths = content_utils.get_packs_base_paths()
159
                    result[name] = registrar.register_from_packs(base_dirs=packs_base_paths)
160
161
        return result
162
163
164
class PackSearchController(RestController):
165
166
    @jsexpose(body_cls=PackSearchRequestAPI)
167
    def post(self, pack_search_request):
168
        if hasattr(pack_search_request, 'query'):
169
            return packs_service.search_pack_index(pack_search_request.query)
170
        else:
171
            return packs_service.get_pack_from_index(pack_search_request.pack)
172
173
174
class BasePacksController(ResourceController):
175
    model = PackAPI
176
    access = Pack
177
178
    def _get_one_by_ref_or_id(self, ref_or_id, exclude_fields=None):
179
        LOG.info('GET %s with ref_or_id=%s', pecan.request.path, ref_or_id)
180
181
        instance = self._get_by_ref_or_id(ref_or_id=ref_or_id, exclude_fields=exclude_fields)
182
183
        if not instance:
184
            msg = 'Unable to identify resource with ref_or_id "%s".' % (ref_or_id)
185
            pecan.abort(http_client.NOT_FOUND, msg)
186
            return
187
188
        from_model_kwargs = self._get_from_model_kwargs_for_request(request=pecan.request)
189
        result = self.model.from_model(instance, **from_model_kwargs)
190
        LOG.debug('GET %s with ref_or_id=%s, client_result=%s', pecan.request.path, ref_or_id,
191
                  result)
192
193
        return result
194
195
    def _get_by_ref_or_id(self, ref_or_id, exclude_fields=None):
196
        resource_db = self._get_by_id(resource_id=ref_or_id, exclude_fields=exclude_fields)
197
198
        if not resource_db:
199
            # Try ref
200
            resource_db = self._get_by_ref(ref=ref_or_id, exclude_fields=exclude_fields)
201
202
        return resource_db
203
204
    def _get_by_ref(self, ref, exclude_fields=None):
205
        """
206
        Note: In this case "ref" is pack name and not StackStorm's ResourceReference.
207
        """
208
        resource_db = self.access.query(ref=ref, exclude_fields=exclude_fields).first()
209
        return resource_db
210
211
212
class PacksController(BasePacksController):
213
    from st2api.controllers.v1.packviews import PackViewsController
214
215
    model = PackAPI
216
    access = Pack
217
    supported_filters = {
218
        'name': 'name',
219
        'ref': 'ref'
220
    }
221
222
    query_options = {
223
        'sort': ['ref']
224
    }
225
226
    # Nested controllers
227
    init = PackInitController()
228
    install = PackInstallController()
229
    uninstall = PackUninstallController()
230
    register = PackRegisterController()
231
    search = PackSearchController()
232
    views = PackViewsController()
233
234
    @request_user_has_permission(permission_type=PermissionType.PACK_LIST)
235
    @jsexpose()
236
    def get_all(self, **kwargs):
237
        return super(PacksController, self)._get_all(**kwargs)
238
239
    @request_user_has_resource_db_permission(permission_type=PermissionType.PACK_VIEW)
240
    @jsexpose(arg_types=[str])
241
    def get_one(self, ref_or_id):
242
        return self._get_one_by_ref_or_id(ref_or_id=ref_or_id)
243