Completed
Pull Request — master (#466)
by
unknown
02:27
created

OrionBaseAction.get_ncm_transfer_results()   B

Complexity

Conditions 5

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 5
dl 0
loc 27
rs 8.0894
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 time
17
18
from st2actions.runners.pythonrunner import Action
19
from orionsdk import SwisClient
20
21
22
class OrionBaseAction(Action):
23
    def __init__(self, config):
24
        super(OrionBaseAction, self).__init__(config)
25
26
        self.client = None
27
28
        if "orion" not in self.config:
29
            raise ValueError("Orion host details not in the config.yaml")
30
31
    def connect(self, platform):
32
        try:
33
            self.client = SwisClient(
34
                self.config['orion'][platform]['host'],
35
                self.config['orion'][platform]['user'],
36
                self.config['orion'][platform]['password'])
37
        except KeyError:
38
            raise ValueError("Orion host details not in the config.yaml")
39
40
    def query(self, swql, **kargs):
41
        return self.client.query(swql, **kargs)
42
43
    def invoke(self, entity, verb, *args):
44
        return self.client.invoke(entity, verb, *args)
45
46
    def create(self, entity, **kargs):
47
        return self.client.create(entity, **kargs)
48
49
    def node_exists(self, caption, ip_address):
50
        swql = """SELECT NodeID, IPAddress FROM Orion.Nodes
51
                  WHERE Caption=@caption"""
52
        kargs = {'caption': caption}
53
        caption_data = self.query(swql, **kargs)
54
55
        swql = """SELECT NodeID, IPAddress FROM Orion.Nodes
56
                  WHERE IPAddress=@ip_address"""
57
        kargs = {'ip_address': ip_address}
58
        ip_data = self.query(swql, **kargs)
59
60
        if len(caption_data['results']) >= 1 or len(ip_data['results']) >= 1:
61
            return True
62
        else:
63
            return False
64
65
    def get_node_id(self, caption):
66
        swql = "SELECT NodeID FROM Orion.Nodes WHERE Caption=@caption"
67
        kargs = {'caption': caption}
68
        data = self.query(swql, **kargs)
69
70
        if len(data['results']) == 1:
71
            try:
72
                return data['results'][0]['NodeID']
73
            except IndexError:
74
                raise ValueError("Invalid Node")
75
        elif len(data['results']) >= 2:
76
            raise ValueError("Muliple Nodes match '{}' Caption".format(
77
                caption))
78
        elif len(data['results']) == 0:
79
            raise ValueError("No matching Caption for '{}'".format(
80
                caption))
81
82
    def get_ncm_node_id(self, caption):
83
        """
84
        Queries the Network configuration Manager nodes table on the Orion
85
        platform for the NodeID of a given node name (aka NodeCaption).
86
87
        Raises: IndexError on Invalid number of nodes (e.g. 0 or 2+).
88
89
        Returns: A single node id.
90
        """
91
92
        swql = "SELECT NodeID FROM Cirrus.Nodes WHERE NodeCaption=@node"
93
        kargs = {'node': caption}
94
        data = self.query(swql, **kargs)
95
96
        if len(data['results']) == 1:
97
            try:
98
                return data['results'][0]['NodeID']
99
            except IndexError:
100
                raise IndexError("Invalid Node")
101
        elif len(data['results']) >= 2:
102
            raise IndexError("Muliple Nodes match '{}' NodeCaption".format(
103
                caption))
104
        elif len(data['results']) == 0:
105
            raise IndexError("No matching NodeCaption for '{}'".format(
106
                caption))
107
108
    def get_ncm_transfer_results(self, transfer_id):
109
        ts = {}
110
        while True:
111
            swql = """SELECT TransferID, Action, Status, ErrorMessage,
112
            DeviceOutput FROM NCM.TransferResults
113
            WHERE TransferID=@transfer_id"""
114
            kargs = {'transfer_id': transfer_id}
115
116
            transfer_data = self.query(swql, **kargs)
117
            status = transfer_data['results'][0]['Status']
118
119
            if status == 1:
120
                time.sleep(10)
121
            elif status == 2:
122
                ts['status'] = "Complete"
123
                break
124
            elif status == 3:
125
                ts['status'] = "Error"
126
                ts['ErrorMessage'] = transfer_data['results'][0][
127
                    'ErrorMessage']
128
                break
129
            else:
130
                ts['status'] = "Unknown"
131
                ts['ErrorMessage'] = "Invalid stauts: {}".format(status)
132
                break
133
134
        return ts
135
136
    def status_code_to_text(self, status):
137
        """
138
        Takes an Solarwinds Orion status code and translates it to
139
        human text and also a colour that can be used in Slack.
140
        """
141
142
        if status == 0:
143
            return ("Unknown", "grey")
144
        elif status == 1:
145
            return ("Up", "good")
146
        elif status == 2:
147
            return ("Down", "danger")
148
        elif status == 3:
149
            return ("Warning", "warning")
150
        elif status == 14:
151
            return ("Critical", "danger")
152
153
    def send_user_error(self, message):
154
        print(message)
155