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

contrib/packs/actions/pack_mgmt/register.py (1 issue)

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 os
17
18
from st2client.client import Client
19
from st2client.models.keyvalue import KeyValuePair  # pylint: disable=no-name-in-module
20
from st2common.runners.base_action import Action
21
22
__all__ = [
23
    'St2RegisterAction'
24
]
25
26
COMPATIBILITY_TRANSFORMATIONS = {
27
    'runners': 'runner',
28
    'triggers': 'trigger',
29
    'sensors': 'sensor',
30
    'actions': 'action',
31
    'rules': 'rule',
32
    'rule_types': 'rule_type',
33
    'aliases': 'alias',
34
    'policiy_types': 'policy_type',
35
    'policies': 'policy',
36
    'configs': 'config',
37
}
38
39
40
def filter_none_values(value):
41
    """
42
    Filter out string "None" values from the provided dict.
43
    :rtype: ``dict``
44
    """
45
    result = dict([(k, v) for k, v in value.items() if v != "None"])
46
    return result
47
48
49
def format_result(item):
50
    if not item:
51
        return None
52
53
    return item.to_dict()
54
55
56
class St2RegisterAction(Action):
57
    def __init__(self, config):
58
        super(St2RegisterAction, self).__init__(config)
59
        self._client = Client
60
        self._kvp = KeyValuePair
61
        self.client = self._get_client()
62
63
    def run(self, register, packs=None):
64
        types = []
65
66
        for type in register.split(','):
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...
67
            if type in COMPATIBILITY_TRANSFORMATIONS:
68
                types.append(COMPATIBILITY_TRANSFORMATIONS[type])
69
            else:
70
                types.append(type)
71
72
        method_kwargs = {
73
            'types': types
74
        }
75
76
        if packs:
77
            method_kwargs['packs'] = packs
78
79
        result = self._run_client_method(method=self.client.packs.register,
80
                                         method_kwargs=method_kwargs,
81
                                         format_func=format_result)
82
        # TODO: make sure to return proper model
83
        return result
84
85
    def _get_client(self):
86
        base_url, api_url, auth_url = self._get_st2_urls()
87
        token = self._get_auth_token()
88
        cacert = self._get_cacert()
89
90
        client_kwargs = {}
91
        if cacert:
92
            client_kwargs['cacert'] = cacert
93
94
        return self._client(base_url=base_url, api_url=api_url,
95
                            auth_url=auth_url, token=token,
96
                            **client_kwargs)
97
98
    def _get_st2_urls(self):
99
        # First try to use base_url from config.
100
        base_url = self.config.get('base_url', None)
101
        api_url = self.config.get('api_url', None)
102
        auth_url = self.config.get('auth_url', None)
103
104
        # not found look up from env vars. Assuming the pack is
105
        # configuered to work with current StackStorm instance.
106
        if not base_url:
107
            api_url = os.environ.get('ST2_ACTION_API_URL', None)
108
            auth_url = os.environ.get('ST2_ACTION_AUTH_URL', None)
109
110
        return base_url, api_url, auth_url
111
112
    def _get_auth_token(self):
113
        # First try to use auth_token from config.
114
        token = self.config.get('auth_token', None)
115
116
        # not found look up from env vars. Assuming the pack is
117
        # configuered to work with current StackStorm instance.
118
        if not token:
119
            token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None)
120
121
        return token
122
123
    def _get_cacert(self):
124
        cacert = self.config.get('cacert', None)
125
        return cacert
126
127
    def _run_client_method(self, method, method_kwargs, format_func, format_kwargs=None):
128
        """
129
        Run the provided client method and format the result.
130
131
        :param method: Client method to run.
132
        :type method: ``func``
133
134
        :param method_kwargs: Keyword arguments passed to the client method.
135
        :type method_kwargs: ``dict``
136
137
        :param format_func: Function for formatting the result.
138
        :type format_func: ``func``
139
140
        :rtype: ``list`` of ``dict``
141
        """
142
        # Filter out parameters with string value of "None"
143
        # This is a work around since the default values can only be strings
144
        method_kwargs = filter_none_values(method_kwargs)
145
        method_name = method.__name__
146
        self.logger.debug('Calling client method "%s" with kwargs "%s"' % (method_name,
147
                                                                           method_kwargs))
148
149
        result = method(**method_kwargs)
150
        result = format_func(result, **format_kwargs or {})
151
        return result
152