summaryrefslogtreecommitdiffstats
path: root/compass-tasks/hdsdiscovery/utils.py
blob: 72adb0afd44d2896786ebf3c267a2f5cb7006499 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# Copyright 2014 Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Utility functions
   Including functions of get/getbulk/walk/set of snmp for three versions
"""
import imp
import logging
import re
import subprocess

from compass.hdsdiscovery.error import TimeoutError


def load_module(mod_name, path, host=None, credential=None):
    """Load a module instance.

    :param str mod_name: module name
    :param str path: directory of the module
    :param str host: switch ip address
    :param str credential: credential used to access switch
    """
    try:
        mod_file, path, descr = imp.find_module(mod_name, [path])
        if mod_file:
            mod = imp.load_module(mod_name, mod_file, path, descr)
            if host and credential:
                instance = getattr(mod, mod.CLASS_NAME)(host, credential)
            else:
                instance = getattr(mod, mod.CLASS_NAME)()

        return instance
    except ImportError as exc:
        logging.error('No such module found: %s', mod_name)
        logging.exception(exc)
        return None


def ssh_remote_execute(host, username, password, cmd):
    """SSH to execute script on remote machine

    :param host: ip of the remote machine
    :param username: username to access the remote machine
    :param password: password to access the remote machine
    :param cmd: command to execute
    """
    try:
        import paramiko
        if not cmd:
            logging.error("[hdsdiscovery][utils][ssh_remote_execute] command"
                          "is None! Failed!")
            return None

        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host, username=username, password=password, timeout=15)
        stdin, stdout, stderr = client.exec_command(cmd)
        result = stdout.readlines()
        return result

    except ImportError as exc:
        logging.error("[hdsdiscovery][utils][ssh_remote_execute] failed to"
                      "load module 'paramiko', donnot exist!")
        logging.exception(exc)
        return None

    except Exception as exc:
        logging.error("[hdsdiscovery][utils][ssh_remote_execute] failed: %s",
                      cmd)
        logging.exception(exc)
        return None

    finally:
        stdin.close()
        stdout.close()
        stderr.close()
        client.close()


def valid_ip_format(ip_address):
    """Valid the format of an Ip address."""

    if not re.match(r'^((([0-2]?\d{0,2}\.){3}([0-2]?\d{0,2}))'
                    r'|(([\da-fA-F]{1,4}:){7}([\da-fA-F]{1,4})))$',
                    ip_address):
        # check IP's format is match ipv4 or ipv6 by regex
        return False

    return True

#################################################################
# Implement snmpwalk and snmpget funtionality
# The structure of returned dictionary will by tag/iid/value/type
#################################################################
AUTH_VERSIONS = {
    '1': 1,
    '2c': 2,
    '3': 3
}


def snmp_walk(host, credential, *args, **kwargs):
    """Impelmentation of snmpwalk functionality

    :param host: switch ip
    :param credential: credential to access switch
    :param args: OIDs
    :param kwargs: key-value pairs
    """
    try:
        import netsnmp

    except ImportError:
        logging.error("Module 'netsnmp' do not exist! Please install it first")
        return None

    if 'version' not in credential or 'community' not in credential:
        logging.error("[utils] missing 'version' and 'community' in %s",
                      credential)
        return None

    version = None
    if credential['version'] in AUTH_VERSIONS:
        version = AUTH_VERSIONS[credential['version']]

    varbind_list = []
    for arg in args:
        varbind = netsnmp.Varbind(arg)
        varbind_list.append(varbind)

    var_list = netsnmp.VarList(*varbind_list)

    netsnmp.snmpwalk(var_list,
                     DestHost=host,
                     Version=version,
                     Community=credential['community'],
                     **kwargs)

    result = []
    if not var_list:
        logging.error("[hsdiscovery][utils][snmp_walk] retrived no record!")
        return result

    for var in var_list:
        response = {}
        response['elem_name'] = var.tag
        response['iid'] = var.iid
        response['value'] = var.val
        response['type'] = var.type
        result.append(response)

    return result


def snmp_get(host, credential, object_type, **kwargs):
    """Impelmentation of snmp get functionality

    :param object_type: mib object
    :param host: switch ip
    :param credential: the dict of credential to access switch
    """
    try:
        import netsnmp

    except ImportError:
        logging.error("Module 'netsnmp' do not exist! Please install it first")
        return None

    if 'version' not in credential or 'community' not in credential:
        logging.error('[uitls][snmp_get] missing keywords in %s for %s',
                      credential, host)
        return None

    version = None
    if credential['version'] in AUTH_VERSIONS:
        version = AUTH_VERSIONS[credential['version']]

    varbind = netsnmp.Varbind(object_type)
    res = netsnmp.snmpget(varbind,
                          DestHost=host,
                          Version=version,
                          Community=credential['community'],
                          **kwargs)
    if res and res[0]:
        return res[0]

    logging.info('no result found for %s %s', host, credential)
    return None


SSH_CREDENTIALS = {"username": "", "password": ""}
SNMP_V2_CREDENTIALS = {"version": "", "community": ""}


def is_valid_snmp_v2_credential(credential):
    """check if credential is valid snmp v2 credential."""
    if credential.keys() != SNMP_V2_CREDENTIALS.keys():
        return False
    if credential['version'] != '2c':
        logging.error("The value of version in credential is not '2c'!")
        return False
    return True


def is_valid_ssh_credential(credential):
    """check if credential is valid ssh credential."""
    if credential.keys() != SSH_CREDENTIALS.keys():
        return False
    return True


def snmpget_by_cl(host, credential, oid, timeout=8, retries=3):
    """snmpget by credential."""
    if not is_valid_snmp_v2_credential(credential):
        logging.error("[utils][snmpget_by_cl] Credential %s cannot be used "
                      "for SNMP request!", credential)
        return None

    version = credential['version']
    community = credential['community']
    cmd = "snmpget -v %s -c %s -Ob -r %s -t %s %s %s" % (
        version, community, retries, timeout, host, oid)

    returncode, output, err = exec_command(cmd)

    if returncode and err:
        logging.error("[snmpget_by_cl] %s", err)
        raise TimeoutError(err.strip('\n'))

    return output.strip('\n')


def snmpwalk_by_cl(host, credential, oid, timeout=5, retries=3):
    """snmpwalk by credential."""
    if not is_valid_snmp_v2_credential(credential):
        logging.error("[utils][snmpwalk_by_cl] Credential %s cannot be used "
                      "for SNMP request!", credential)
        return None

    version = credential['version']
    community = credential['community']
    cmd = "snmpwalk -v %s -c %s -Cc -r %s -t %s -Ob %s %s" % (
        version, community, retries, timeout, host, oid)

    returncode, output, err = exec_command(cmd)

    if returncode and err:
        logging.debug("[snmpwalk_by_cl] %s ", err)
        raise TimeoutError(err)

    result = []
    if not output:
        return result

    output = output.split('\n')
    for line in output:
        if not line:
            continue
        temp = {}
        arr = line.split(" ")
        temp['iid'] = arr[0].split('.', 1)[-1]
        temp['value'] = arr[-1]
        result.append(temp)

    return result


def exec_command(command):
    """Execute command.

    Return a tuple: returncode, output and error message(None if no error).
    """
    sub_p = subprocess.Popen(command,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    output, err_msg = sub_p.communicate()
    return (sub_p.returncode, output, err_msg)