Completed
Pull Request — master (#496)
by
unknown
02:49
created

ICSPBaseActions.check_results()   A

Complexity

Conditions 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
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 requests
17
import copy
18
from st2actions.runners.pythonrunner import Action
19
20
21
class ICSPBaseActions(Action):
22
23
    def __init__(self, config):
24
        super(ICSPBaseActions, self).__init__(config)
25
        self.icsp_host = config['host']
26
        self.icsp_user = config['user']
27
        self.icsp_pass = config['pass']
28
        self.icsp_apiv = config['apiv']
29
        self.icsp_sslverify = config['sslverify']
30
31
    def check_results(self, results):
32
        # Check for errorCode json element
33
        if 'errorCode' in results:
34
            raise Exception("Error: %s" % (results["recommendedActions"]))
35
36
    def set_connection(self, connection=None):
37
        if connection:
38
            if 'host' in connection:
39
                self.icsp_host = connection['host']
40
            if 'user' in connection:
41
                self.icsp_user = connection['user']
42
            if 'pass' in connection:
43
                self.icsp_pass = connection['pass']
44
            if 'apiv' in connection:
45
                self.icsp_apiv = connection['apiv']
46
            if 'sslverify' in connection:
47
                if connection['sslverify'].lower() == "false":
48
                    self.icsp_sslverify = False
49
                else:
50
                    self.icsp_sslverify = True
51
52
    def get_sessionid(self):
53
        url = 'https://%s/rest/login-sessions' % self.icsp_host
54
        payload = {'userName': self.icsp_user, 'password': self.icsp_pass}
55
        headers = {'accept': 'application/json',
56
                   'accept-language': 'en-us',
57
                   'Content-Type': 'application/json'}
58
        p = requests.post(url, headers=headers,
59
                          json=payload, verify=self.icsp_sslverify)
60
        results = p.json()
61
        self.check_results(results)
62
        self.icsp_sessionid = results["sessionID"]
0 ignored issues
show
Coding Style introduced by
The attribute icsp_sessionid was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
63
64
        # added here due to the requirement of the session id
65
        self.base_headers = {'Auth': self.icsp_sessionid,
0 ignored issues
show
Coding Style introduced by
The attribute base_headers was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
66
                             'X-Api-Version': self.icsp_apiv}
67
68
        return results["sessionID"]
69
70
    def extract_id(self, joburi):
71
        jobid = str(joburi)
72
        return int(jobid.split("/")[-1])
73
74
    def get_mids(self, ids, idtype):
75
        endpoint = "/rest/os-deployment-servers"
76
        getresults = self.icsp_get(endpoint)
77
        servers = getresults["members"]
78
        mids = []
79
        for id in ids:
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...
80
            for server in servers:
81
                if idtype == 'serialnumber':
82
                    if ((server["serialNumber"] == id) and
83
                            (server["mid"] not in mids)):
84
                        mids.append(int(server["mid"]))
85
                if idtype == 'uuid':
86
                    if ((server["uuid"] == id) and
87
                            (server["mid"] not in mids)):
88
                        mids.append(int(server["mid"]))
89
        return mids
90
91
    def validate_mids (self, identifiers):
0 ignored issues
show
Coding Style introduced by
No space allowed before bracket
def validate_mids (self, identifiers):
^
Loading history...
92
        for n in identifiers:
93
            try:
94
                int(n)
95
            except:
96
                raise ValueError("Identifier provided is not a MID")
97
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
98
    def icsp_get(self, endpoint):
99
        url = 'https://%s%s' % (self.icsp_host, endpoint)
100
        headers = copy.copy(self.base_headers)
101
        p = requests.get(url, headers=headers, verify=self.icsp_sslverify)
102
        results = p.json()
103
        self.check_results(results)
104
        return results
105
106
    def icsp_put(self, endpoint, payload):
107
        url = 'https://%s%s' % (self.icsp_host, endpoint)
108
        headers = copy.copy(self.base_headers)
109
        p = requests.put(url, headers=headers,
110
                         json=payload, verify=self.icsp_sslverify)
111
        results = p.json()
112
        self.check_results(results)
113
        return
114
115
    def icsp_post(self, endpoint, payload):
116
        url = 'https://%s%s' % (self.icsp_host, endpoint)
117
        headers = copy.copy(self.base_headers)
118
        headers['Content-type'] = "application/json"
119
        p = requests.post(url, headers=headers,
120
                          data=payload, verify=self.icsp_sslverify)
121
        results = p.json()
122
        self.check_results(results)
123
        return results
124
125
    def icsp_delete(self, endpoint):
126
        url = 'https://%s%s' % (self.icsp_host, endpoint)
127
        headers = copy.copy(self.base_headers)
128
        requests.delete(url, headers=headers, verify=self.icsp_sslverify)
129
        return
130