get_inventory.py 18.7 KB
Newer Older
Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
1
2
3
# ---------------------------------------------------------------------
# Huawei.MA5600T.get_inventory
# ---------------------------------------------------------------------
bee26's avatar
bee26 committed
4
# Copyright (C) 2007-2022 The NOC Project
Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
5
6
# See LICENSE for details
# ---------------------------------------------------------------------
7

Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
8
# Python modules
9
import re
10
from collections import namedtuple, defaultdict
11
12
13

# Third party modules
from dateutil.parser import parse
Dmitry Volodin's avatar
Dmitry Volodin committed
14

Dmitry Lukhtionov's avatar
Dmitry Lukhtionov committed
15
# NOC modules
16
17
from noc.core.script.base import BaseScript
from noc.sa.interfaces.igetinventory import IGetInventory
18
from noc.core.text import parse_kv
19
from noc.core.mib import mib
20
21
22
23
24


class Script(BaseScript):
    name = "Huawei.MA5600T.get_inventory"
    interface = IGetInventory
Andrey Vertiprahov's avatar
Andrey Vertiprahov committed
25
    always_prefer = "C"
26

bee26's avatar
bee26 committed
27
28
29
30
31
    SNMP_UNKNOWN_VALUE = 2147483647
    SNMP_INVALID_VALUE = -1

    MEASURE_TYPES = {
        "C": "Celsius",
bee26's avatar
bee26 committed
32
        "%R.H.": "Percent",
bee26's avatar
bee26 committed
33
34
35
36
        "V": "Volt DC",
        "A": "Ampere",
    }

37
    rx_slot = re.compile(
Dmitry Volodin's avatar
Dmitry Volodin committed
38
39
40
        r"^\s*Pcb\s+Version\s*:\s+(?P<part_no>\S+)\s+" r"VER (?P<revision>\S+)\s*\n",
        re.MULTILINE | re.IGNORECASE,
    )
41
    rx_sub = re.compile(
42
        r"^\s*(VOIP)?SubBoard(\[(?P<number>\d+)\])?:\s*\n"
43
44
        r"^\s*Pcb\s+Version\s*:\s+(?P<part_no>\S+)\s+"
        r"VER (?P<revision>\S+)\s*\n",
Dmitry Volodin's avatar
Dmitry Volodin committed
45
46
        re.MULTILINE | re.IGNORECASE,
    )
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
    rx_inv_item_split = re.compile(
        r"\[(?P<role>Back[Pp]lane|FanFrame|Slot|Main_Board|Daughter_Board)(?:_(?P<num>\d+)|)\]\n"
        r"\/\$\[(?:Archi(?:e|)ve(?:r|)s\s*Info|Board\s*Integration)\s*Version\]\n"
        r"\/\$(?:Archi(?:e|)ve(?:r|)s\s*Info|Board\s*Integration)\s*Version=3\.0\n+",
        re.MULTILINE,
    )

    rx_inv_port_split = re.compile(
        r"\[[Pp]ort_(?P<name>\S+)\]\n"
        r"\/\$\[(?:Archi(?:e|)ve(?:r|)s\s*Info|Board\s*Integration)\s*Version\]\n"
        r"\/\$(?:Archi(?:e|)ve(?:r|)s\s*Info|Board\s*Integration)\s*Version=3\.0\n+",
        re.MULTILINE,
    )

    rx_int_elabel = re.compile(
        r"\[(?P<sec_name>"
        r"(?P<role>Rack|Back[Pp]lane|FanFrame|Slot|Main_Board|Daughter_Board|[Pp]ort)(?:_(?P<num>\S+)|))\]\n"
        r"\/\$\[(?:Archi(?:e|)ve(?:r|)s\s*Info|Board\s*Integration)\s*Version\]\n"
        r"\/\$(?:Archi(?:e|)ve(?:r|)s\s*Info|Board\s*Integration)\s*Version=3\.0\n+"
        r"(?P<properties>\[Board Properties\]\n(?:(?:\S+\=.*|[\w\s*,\(\)\*\/\-]+)\n)+)?",
        re.MULTILINE,
    )

    rx_int_elabel_universal = re.compile(
        r"\[(?P<sec_name>"
        r"(?P<role>Rack|Back[Pp]lane|FanFrame|Slot|Main_Board|Daughter_Board|[Pp]ort)(?:_(?P<num>\S+)|))\]\n"
        r"(?:\/\$\[.+\]\n"
        r"+\/\$(?:\S+=.*)\n+)+"
        r"(?P<properties>\[Board Properties\]\n(?:(?:\S+\=.*|[\w\s*,\(\)\*\/\-]+)\n)+)?",
        re.MULTILINE,
    )
    inventory_item = namedtuple(
        "InvItem", ["name", "num", "parent", "description", "type", "vendor", "barcode", "mnf_date"]
    )

    inv_property_map = {
        "boardtype": "type",
        "barcode": "barcode",
        "description": "description",
        "/edescription": "description",
        "manufactured": "mnf_date",
        "vendorname": "vendor",
    }

bee26's avatar
bee26 committed
92
    def get_chassis_sensors(self):
bee26's avatar
bee26 committed
93
94
        if not self.has_snmp():
            return []
bee26's avatar
bee26 committed
95
96
97
        r = []
        # hwAnaChannelTable
        for oid, v in self.snmp.getnext("1.3.6.1.4.1.2011.6.1.1.2.1.2", bulk=False):
bee26's avatar
bee26 committed
98
99
100
            key = oid.rsplit(".", 1)[-1]
            measure = self.snmp.get(f"1.3.6.1.4.1.2011.6.1.1.2.1.4.{key}")
            value = self.snmp.get(f"1.3.6.1.4.1.2011.6.1.1.2.1.9.{key}")
101
102
103
104
105
106
107
108
109
110
            if value and value != self.SNMP_UNKNOWN_VALUE and measure:
                r += [
                    {
                        "name": v,
                        "status": True,
                        "description": v,
                        "measurement": self.MEASURE_TYPES[measure],
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.1.1.2.1.9.{key}",
                    }
                ]
bee26's avatar
bee26 committed
111
112
        # hwDigChannelTable
        for oid, v in self.snmp.getnext("1.3.6.1.4.1.2011.6.1.1.3.1.2", bulk=False):
bee26's avatar
bee26 committed
113
            key = oid.rsplit(".", 1)[-1]
bee26's avatar
bee26 committed
114
115
            v = v.lower()
            if "door" in v or "heater" in v:
bee26's avatar
bee26 committed
116
                value = self.snmp.get(f"1.3.6.1.4.1.2011.6.1.1.3.1.4.{key}")
117
                if value and value != self.SNMP_INVALID_VALUE:
118
119
120
121
122
123
124
125
126
                    r += [
                        {
                            "name": v,
                            "status": True,
                            "description": v,
                            "measurement": "Scalar",
                            "snmp_oid": f"1.3.6.1.4.1.2011.6.1.1.3.1.4.{key}",
                        }
                    ]
bee26's avatar
bee26 committed
127
128
        # hwFanTable
        for oid, v in self.snmp.getnext("1.3.6.1.4.1.2011.6.1.1.5.1.1", bulk=False):
bee26's avatar
bee26 committed
129
130
            key = oid.rsplit(".", 1)[-1]
            value = self.snmp.get(f"1.3.6.1.4.1.2011.6.1.1.5.1.7.{key}")
131
132
133
134
135
136
137
138
139
140
            if value and value != self.SNMP_UNKNOWN_VALUE:
                r += [
                    {
                        "name": "fan_temp",
                        "status": True,
                        "description": "Температура в блоке вентиляторов",
                        "measurement": "Celsius",
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.1.1.5.1.7.{key}",
                    }
                ]
bee26's avatar
bee26 committed
141
            value = self.snmp.get(f"1.3.6.1.4.1.2011.6.1.1.5.1.9.{key}")
142
143
144
145
146
147
148
149
150
151
            if value and value != self.SNMP_INVALID_VALUE:
                r += [
                    {
                        "name": "fan_speed",
                        "status": True,
                        "description": "Скорость вращения вентиляторов",
                        "measurement": "Percent",
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.1.1.5.1.9.{key}",
                    }
                ]
bee26's avatar
bee26 committed
152
153
        # hwACInputEntry
        for oid, v in self.snmp.getnext("1.3.6.1.4.1.2011.6.2.1.2.1.2", bulk=False):
bee26's avatar
bee26 committed
154
            key = oid.rsplit(".", 1)[-1]
bee26's avatar
bee26 committed
155
            if v:
156
157
158
159
160
161
162
163
164
                r += [
                    {
                        "name": "ac_state",
                        "status": True,
                        "description": "Наличие напряжения AC",
                        "measurement": "Scalar",
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.2.1.2.{key}",
                    }
                ]
bee26's avatar
bee26 committed
165
            value = self.snmp.get(f"1.3.6.1.4.1.2011.6.2.1.2.1.3.{key}")
166
167
168
169
170
171
172
173
174
175
            if value and value != self.SNMP_INVALID_VALUE:
                r += [
                    {
                        "name": "ac_volt",
                        "status": True,
                        "description": "Напряжение AC",
                        "measurement": "Volt AC",
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.2.1.3.{key}",
                    }
                ]
bee26's avatar
bee26 committed
176
177
        # hwDCOutEntry
        for oid, v in self.snmp.getnext("1.3.6.1.4.1.2011.6.2.1.3.1.1", bulk=False):
bee26's avatar
bee26 committed
178
            key = oid.rsplit(".", 1)[-1]
bee26's avatar
bee26 committed
179
            if v:
180
181
182
183
184
185
186
187
188
                r += [
                    {
                        "name": "dc_volt",
                        "status": True,
                        "description": "Напряжение DC",
                        "measurement": "Volt DC",
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.3.1.1.{key}",
                    }
                ]
bee26's avatar
bee26 committed
189
            value = self.snmp.get(f"1.3.6.1.4.1.2011.6.2.1.3.1.2.{key}")
190
191
192
193
194
195
196
197
198
199
            if value and value != self.SNMP_INVALID_VALUE:
                r += [
                    {
                        "name": "dc_current",
                        "status": True,
                        "description": "Ток DC",
                        "measurement": "Ampere",
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.3.1.2.{key}",
                    }
                ]
bee26's avatar
bee26 committed
200
            value = self.snmp.get(f"1.3.6.1.4.1.2011.6.2.1.3.1.5.{key}")
bee26's avatar
bee26 committed
201
            if value:
202
203
204
205
206
207
208
209
210
                r += [
                    {
                        "name": "dc_state",
                        "status": True,
                        "description": "Наличие напряжения DC",
                        "measurement": "Scalar",
                        "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.3.1.5.{key}",
                    }
                ]
bee26's avatar
bee26 committed
211
212
        # hwBatteryTable
        for oid, v in self.snmp.getnext("1.3.6.1.4.1.2011.6.2.1.6.3.1.2", bulk=False):
bee26's avatar
bee26 committed
213
            key = oid.rsplit(".", 1)[-1]
bee26's avatar
bee26 committed
214
            if v > 0:
bee26's avatar
bee26 committed
215
216
217
                volt = self.snmp.get(f"1.3.6.1.4.1.2011.6.2.1.6.3.1.4.{key}")
                current = self.snmp.get(f"1.3.6.1.4.1.2011.6.2.1.6.3.1.6.{key}")
                temp = self.snmp.get(f"1.3.6.1.4.1.2011.6.2.1.6.3.1.7.{key}")
bee26's avatar
bee26 committed
218
                if temp != self.SNMP_UNKNOWN_VALUE and volt != self.SNMP_INVALID_VALUE:
219
220
221
                    r += [
                        {
                            "name": "battery_volt",
bee26's avatar
bee26 committed
222
                            "status": True,
223
224
225
                            "description": "Напряжение АКБ",
                            "measurement": "Volt DC",
                            "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.6.3.1.4.{key}",
bee26's avatar
bee26 committed
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
                    ]
                    if current != self.SNMP_INVALID_VALUE:
                        r += [
                            {
                                "name": "battery_current",
                                "status": True,
                                "description": "Ток АКБ",
                                "measurement": "Ampere",
                                "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.6.3.1.6.{key}",
                            }
                        ]
                    r += [
                        {
                            "name": "battery_temp",
                            "status": True,
                            "description": "Температура АКБ",
                            "measurement": "Celsius",
                            "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.6.3.1.7.{key}",
                        },
                        {
                            "name": "battery_state",
                            "status": True,
                            "description": "Текущее состояние АКБ",
                            "measurement": "Scalar",
                            "snmp_oid": f"1.3.6.1.4.1.2011.6.2.1.6.3.1.8.{key}",
                        },
                    ]
bee26's avatar
bee26 committed
254
255
        return r

256
257
258
259
260
261
262
263
    def parse_elabel(self, out):
        """
        Function parse 'display elabel'
        :param out: 'display elabel output'
        :type out: str
        :return:
        :rtype: inventory_item
        """
264
        r = []
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
290
291
292
293
294
295
        parent = None
        for match in self.rx_int_elabel_universal.finditer(out):
            match = match.groupdict()
            if not match:
                continue
            elif match["role"] in {"Slot", "Rack"}:
                parent = match["sec_name"]
            if not match["properties"]:
                self.logger.debug(
                    "[%s] Empty [Board Properties] section. Skipping...", match["sec_name"]
                )
                continue
            p = parse_kv(self.inv_property_map, match["properties"], sep="=")
            if "vendor" not in p and "type" not in p:
                raise self.UnexpectedResultError("Partial parsed properties")
            elif "vendor" not in p and p["type"].startswith("H"):
                p["vendor"] = "Huawei"
            elif not p["vendor"]:
                self.logger.debug("[%s] Empty Vendor Properties. Skipping...", match["sec_name"])
                continue
            r += [
                self.inventory_item(
                    **{
                        "name": match["sec_name"],
                        "num": int(match["num"] or 0),
                        "parent": parent,
                        "description": p.get("description"),
                        "type": p.get("type"),
                        "vendor": p.get("vendor", "Unknown"),
                        "barcode": p.get("barcode"),
                        "mnf_date": p.get("mnf_date"),
Dmitry Volodin's avatar
Dmitry Volodin committed
296
                    }
297
298
299
300
                )
            ]
        return r

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
    tc_type_map = {"767": "BOARD", "146021": "BOARD"}

    def get_ma5600_subboard(self):
        # SubBoard
        subboard = defaultdict(list)
        for (slot_index, slot_type, slot_ver, slot_descr) in self.snmp.get_tables(
            [
                mib["HUAWEI-DEVICE-MIB::hwSubslotType"],
                mib["HUAWEI-DEVICE-MIB::hwSubslotVersion"],
                mib["HUAWEI-DEVICE-MIB::hwSubSlotDesc"],
            ],
            bulk=False,
        ):
            if not slot_descr:
                continue
            _, slot_num, board_num = slot_index.rsplit(".", 2)
            if board_num == "65535":
                continue
            part_no = slot_descr[:-1]
            subboard[int(slot_num)] += [
                {
                    "type": "SUBBOARD",
                    "number": board_num,
                    "vendor": "Huawei",
                    "part_no": part_no,
                    "description": slot_descr,
                }
            ]
        return subboard

    def execute_snmp(self, **kwargs):
        """
        Slot part_no is not full (ex. ADFE)
        :param kwargs:
        :return:
        """
        r = []
        # Chassis
        for oid, frame_descr in self.snmp.getnext(mib["HUAWEI-DEVICE-MIB::hwFrameDesc"]):
            r += [
                {
                    "type": "CHASSIS",
                    "number": 0,
                    "vendor": "Huawei",
                    "part_no": frame_descr.split("_")[0],
                    "serial": None,
                    "description": "",
                    "mnf_date": None,
                }
            ]
        subboard = self.get_ma5600_subboard()
        # Slots
        for (
            slot_index,
            slot_type,
            slot_descr,
            slot_subs,
            slot_phys_serial,
        ) in self.snmp.get_tables(
            [
                mib["HUAWEI-DEVICE-MIB::hwSlotType"],
                mib["HUAWEI-DEVICE-MIB::hwSlotDesc"],
                mib["HUAWEI-DEVICE-MIB::hwSubSlots"],
                mib["HUAWEI-DEVICE-MIB::hwSlotPhySerialNum"],
            ],
            bulk=False,
        ):
            _, slot_num = slot_index.rsplit(".", 1)
            part_no, _, _ = slot_descr.split("_")
            r += [
                {
                    "type": self.tc_type_map.get(slot_type, "BOARD"),
                    "number": slot_num,
                    "vendor": "Huawei",
                    "part_no": part_no.strip(),
                    "serial": slot_phys_serial,
                    "description": slot_descr,
                }
            ]
            if int(slot_num) in subboard:
                r += subboard[slot_num]
bee26's avatar
bee26 committed
382
        sensors = self.get_chassis_sensors()
383
        if r and sensors:
bee26's avatar
bee26 committed
384
            r[0]["sensors"] = sensors
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
        return r

    def execute_inventory_board(self, **kwargs):
        """
        Uses if display elabel command unsupported
        :param kwargs:
        :return:
        """
        r = []
        serial = {}
        for oid, phys_num in self.snmp.getnext(
            mib["HUAWEI-DEVICE-MIB::hwSlotPhySerialNum"], bulk=False
        ):
            _, slot_num = oid.rsplit(".", 1)
            serial[int(slot_num)] = phys_num
        max_slot, boards = self.profile.get_board(self)
        for board in boards:
            r += [
                self.inventory_item(
                    **{
                        "name": "main_board",
                        "num": int(board["num"] or 0),
                        "parent": None,
                        "description": "",
                        "type": board["name"],
                        "vendor": "Huawei",
                        "barcode": serial[board["num"]],
                        "mnf_date": None,
                    }
                )
            ]
        return r

418
419
    def execute_cli(self, **kwargs):
        r = []
420
        subboards = None
421
422
423
        if self.is_dslam:
            # On MA5600 chassis and subboard serial is not supported
            # frame = self.cli("display frame info 0")
424
425
426
427
428
429
430
            part_no = "H511UPBA"  # MA5600
            descr = "MA5600's H511UPBA backplane, with double CELLBUS and GE bus"
            # Detect MA5600/MA5603
            slots, _ = self.profile.get_board(self)
            if slots == 7:
                part_no = "MA5603"
                descr = "MA5603 subrack"
431
432
433
434
435
            r += [
                {
                    "type": "CHASSIS",
                    "number": 0,
                    "vendor": "Huawei",
436
                    "part_no": part_no,
437
                    "serial": None,
438
                    "description": descr,
439
440
                }
            ]
441
            subboards = self.get_ma5600_subboard()
442
        with self.profile.diagnose(self):
443
444
445
446
447
448
449
            try:
                v = self.cli("display elabel 0", allow_empty_response=False)
                if "This operation will take several seconds, please wait..." in v:
                    v = self.cli("", allow_empty_response=False)
                parse_result = self.parse_elabel(v)
            except self.CLISyntaxError:
                v = ""
450
        if not v:
451
452
            parse_result = self.execute_inventory_board()
        #     raise NotImplementedError("Not supported 'display elabel' command")
453
454
455
456
457
        for item in parse_result:
            self.logger.debug("Inventory item: %s", item)
            num = item.num
            item_name = item.name.lower()
            if num == 0 and item.parent:
458
                num = int(item.parent.split("_")[-1])
459
460
461
462
463
464
            if item_name.startswith("port"):
                i_type = "XCVR"
            elif item_name.startswith("fan"):
                i_type = "FAN"
            elif item_name.startswith("slot") and "PWC" in item.type:
                i_type = "PWR"
465
            elif item_name.startswith("main_board") and "Assembly Chassis" not in item.description:
466
                i_type = "BOARD"
467
468
            elif item_name.startswith("daughter_board"):
                i_type = "DAUGHTERBOARD"
469
470
471
472
473
474
475
476
477
478
            else:
                i_type = "CHASSIS"
            data = {
                "type": i_type,
                "number": num,
                "vendor": item.vendor,
                "part_no": item.type,
                "serial": item.barcode,
                "description": item.description,
            }
479
480
481
482
483
484
            if item.mnf_date:
                try:
                    mfg_date = parse(item.mnf_date)
                    data["mfg_date"] = mfg_date.strftime("%Y-%m-%d")
                except ValueError:
                    pass
485
            r += [data]
486
487
            if subboards and data["number"] in subboards:
                r += subboards[data["number"]]
bee26's avatar
bee26 committed
488
        sensors = self.get_chassis_sensors()
489
        if r and sensors:
bee26's avatar
bee26 committed
490
            r[0]["sensors"] = sensors
491
        return r