| 1 |
from collections import OrderedDict |
| 2 |
from functools import reduce |
| 3 |
import re |
| 4 |
import copy |
| 5 |
import logging |
| 6 |
|
| 7 |
from jinja2 import Template, meta |
| 8 |
from transitions import Machine |
| 9 |
import pyparsing as pp |
| 10 |
|
| 11 |
logger = logging.getLogger("jnpr.junos.factory.state_machine") |
| 12 |
|
| 13 |
|
| 14 |
class Identifiers: |
| 15 |
""" |
| 16 |
This class static variables can be used when defining regex view. For ex: |
| 17 |
_PFENotificationStatsTable: |
| 18 |
title: PFE Notification statistics |
| 19 |
key: name |
| 20 |
view: _PFENotificationStatsView |
| 21 |
|
| 22 |
_PFENotificationStatsView: |
| 23 |
regex: |
| 24 |
value: numbers |
| 25 |
name: words |
| 26 |
""" |
| 27 |
|
| 28 |
printables = pp.OneOrMore(pp.Word(pp.printables)) |
| 29 |
numbers = ( |
| 30 |
pp.Word(pp.nums) + pp.Optional(pp.Literal(".") + pp.Word(pp.nums)) |
| 31 |
).setParseAction(lambda i: "".join(i)) |
| 32 |
hex_numbers = pp.OneOrMore(pp.Word(pp.nums, min=1)) & pp.OneOrMore( |
| 33 |
pp.Word("abcdefABCDEF", min=1) |
| 34 |
) |
| 35 |
word = pp.Word(pp.alphanums) | pp.Word(pp.alphas) |
| 36 |
words = (pp.OneOrMore(word)).setParseAction(lambda i: " ".join(i)) |
| 37 |
percentage = pp.Word(pp.nums) + pp.Literal("%") |
| 38 |
header_bar = ( |
| 39 |
pp.OneOrMore(pp.Word("-")) | pp.OneOrMore(pp.Word("=")) |
| 40 |
) + pp.StringEnd() |
| 41 |
|
| 42 |
|
| 43 |
def data_type(item): |
| 44 |
""" |
| 45 |
|
| 46 |
Args: |
| 47 |
item: string element parsed from the blob. |
| 48 |
|
| 49 |
Returns: item converted to data type it should represent |
| 50 |
|
| 51 |
""" |
| 52 |
try: |
| 53 |
obj = Identifiers.numbers.parseString(item, parseAll=True) |
| 54 |
if "." in obj[0]: |
| 55 |
return float |
| 56 |
else: |
| 57 |
return int |
| 58 |
except pp.ParseException as ex: |
| 59 |
pass |
| 60 |
try: |
| 61 |
Identifiers.hex_numbers.parseString(item, parseAll=True) |
| 62 |
return str # special case |
| 63 |
except pp.ParseException as ex: |
| 64 |
pass |
| 65 |
return str |
| 66 |
|
| 67 |
|
| 68 |
def convert_to_data_type(items): |
| 69 |
""" |
| 70 |
|
| 71 |
Args: |
| 72 |
items: list of string objects |
| 73 |
|
| 74 |
Returns: list of converted data type objects |
| 75 |
|
| 76 |
""" |
| 77 |
item_types = map(data_type, items) |
| 78 |
return list(map(lambda x, y: int(x) if y is int else x.strip(), items, item_types)) |
| 79 |
|
| 80 |
|
| 81 |
class StateMachine(Machine): |
| 82 |
def __init__(self, table_view): |
| 83 |
self._data = {} |
| 84 |
self._table = table_view |
| 85 |
self._view = self._table.VIEW |
| 86 |
self._raw = "" |
| 87 |
self._lines = [] |
| 88 |
self.states = [ |
| 89 |
"row_column", |
| 90 |
"title_data", |
| 91 |
"regex_data", |
| 92 |
"delimiter_data", |
| 93 |
"exists_bool_data", |
| 94 |
] |
| 95 |
self.transitions = [ |
| 96 |
{ |
| 97 |
"trigger": "column_provided", |
| 98 |
"source": "*", |
| 99 |
"dest": "row_column", |
| 100 |
"conditions": "match_columns", |
| 101 |
"before": "check_header_bar", |
| 102 |
"after": "parse_raw_columns", |
| 103 |
}, |
| 104 |
{ |
| 105 |
"trigger": "check_next_row", |
| 106 |
"source": "row_column", |
| 107 |
"dest": "row_column", |
| 108 |
"conditions": "prev_next_row_same_type", |
| 109 |
"after": "parse_raw_columns", |
| 110 |
}, |
| 111 |
{ |
| 112 |
"trigger": "title_provided", |
| 113 |
"source": "start", |
| 114 |
"dest": "title_data", |
| 115 |
"conditions": ["match_title", "title_not_followed_by_columns"], |
| 116 |
"after": "parse_title_data", |
| 117 |
}, |
| 118 |
{ |
| 119 |
"trigger": "regex_provided", |
| 120 |
"source": "title_data", |
| 121 |
"dest": "regex_data", |
| 122 |
"conditions": ["match_title"], |
| 123 |
"before": "check_header_bar", |
| 124 |
"after": "parse_using_regex", |
| 125 |
}, |
| 126 |
{ |
| 127 |
"trigger": "delimiter_without_title", |
| 128 |
"source": "start", |
| 129 |
"dest": "delimiter_data", |
| 130 |
"after": "parse_using_delimiter", |
| 131 |
}, |
| 132 |
{ |
| 133 |
"trigger": "delimiter_with_title", |
| 134 |
"source": ["start", "delimiter_data"], |
| 135 |
"dest": "delimiter_data", |
| 136 |
"conditions": ["match_title"], |
| 137 |
"before": "check_header_bar", |
| 138 |
"after": "parse_using_delimiter", |
| 139 |
}, |
| 140 |
{ |
| 141 |
"trigger": "regex_with_item", |
| 142 |
"source": ["start", "regex_data"], |
| 143 |
"dest": "regex_data", |
| 144 |
"after": "parse_using_item_and_regex", |
| 145 |
}, |
| 146 |
{ |
| 147 |
"trigger": "regex_parser", |
| 148 |
"source": "start", |
| 149 |
"dest": "regex_data", |
| 150 |
"after": "parse_using_regex", |
| 151 |
}, |
| 152 |
{ |
| 153 |
"trigger": "regex_parser", |
| 154 |
"source": "regex_data", |
| 155 |
"dest": "regex_data", |
| 156 |
"after": "parse_using_regex", |
| 157 |
}, |
| 158 |
{ |
| 159 |
"trigger": "regex_parser", |
| 160 |
"source": "row_column", |
| 161 |
"dest": "regex_data", |
| 162 |
"after": "parse_using_regex", |
| 163 |
}, |
| 164 |
{ |
| 165 |
"trigger": "exists_check", |
| 166 |
"source": ["start", "regex_data", "row_column"], |
| 167 |
"dest": "exists_bool_data", |
| 168 |
"after": "parse_exists", |
| 169 |
}, |
| 170 |
{ |
| 171 |
"trigger": "exists_check", |
| 172 |
"source": "title_data", |
| 173 |
"dest": "exists_bool_data", |
| 174 |
"after": "parse_exists", |
| 175 |
}, |
| 176 |
] |
| 177 |
Machine.__init__( |
| 178 |
self, |
| 179 |
states=self.states, |
| 180 |
transitions=self.transitions, |
| 181 |
initial="start", |
| 182 |
send_event=True, |
| 183 |
) |
| 184 |
|
| 185 |
def parse(self, lines): |
| 186 |
""" |
| 187 |
Starting point to parse string blob section. In case of nested table |
| 188 |
this API will get called in recursive call. |
| 189 |
|
| 190 |
Args: |
| 191 |
lines: list of lines which was received from rpc reply <output>. |
| 192 |
|
| 193 |
Returns: dictionary (self._data) with parsed data. |
| 194 |
|
| 195 |
""" |
| 196 |
self._lines = copy.deepcopy(lines) |
| 197 |
self._raw = "\n".join(lines) |
| 198 |
if self._view is None: |
| 199 |
if self._table.DELIMITER is not None: |
| 200 |
if self._table.TITLE is not None: |
| 201 |
self.delimiter_with_title() |
| 202 |
else: |
| 203 |
self.delimiter_without_title() |
| 204 |
elif self._table.TITLE is not None: |
| 205 |
self.title_provided() |
| 206 |
elif self._table.ITEM is not None and self._table.ITEM != "*": |
| 207 |
self._parse_item_iter(lines) |
| 208 |
else: |
| 209 |
if self._view.TITLE is not None or self._table.TITLE: |
| 210 |
self.title_provided() |
| 211 |
if len(self._view.REGEX) > 0: |
| 212 |
if self._table.ITEM is not None: |
| 213 |
self.regex_with_item() |
| 214 |
else: |
| 215 |
self.regex_parser() |
| 216 |
if len(self._view.COLUMNS) > 0: |
| 217 |
self.column_provided() |
| 218 |
if len(self._view.EXISTS) > 0: |
| 219 |
self.exists_check() |
| 220 |
if len(self._view.FIELDS) > 0: |
| 221 |
if self._table.ITEM is not None and self._table.ITEM != "*": |
| 222 |
return self._parse_item_iter(lines) |
| 223 |
for key, value in self._view.FIELDS.items(): |
| 224 |
tbl = value["table"] |
| 225 |
tbl._view = tbl.VIEW |
| 226 |
if tbl._view is None: |
| 227 |
self._data[key] = StateMachine(tbl).parse(lines) |
| 228 |
continue |
| 229 |
if len(tbl._view.COLUMNS) > 0: |
| 230 |
self._data[key] = StateMachine(tbl).parse(lines) |
| 231 |
if tbl._view.TITLE is not None or tbl.TITLE is not None: |
| 232 |
self._data[key] = StateMachine(tbl).parse(lines) |
| 233 |
if self._table.EVAL: |
| 234 |
self._eval_in_full_data() |
| 235 |
return self._data |
| 236 |
|
| 237 |
def _eval_in_full_data(self): |
| 238 |
""" |
| 239 |
To eval expression from full set of data (self._data). Sets key in |
| 240 |
self._data itself. |
| 241 |
|
| 242 |
Returns: None |
| 243 |
""" |
| 244 |
for name, expression in self._table.EVAL.items(): |
| 245 |
t = Template(expression) |
| 246 |
expression = t.render(data=self._data) |
| 247 |
try: |
| 248 |
val = eval(expression) |
| 249 |
except Exception as ex: |
| 250 |
logger.error("eval expression for '%s' failed due to %s" % (name, ex)) |
| 251 |
self._data[name] = None |
| 252 |
else: |
| 253 |
self._data[name] = val |
| 254 |
|
| 255 |
def _parse_item_iter(self, lines): |
| 256 |
""" |
| 257 |
There are cases when similar data set repeats. With item its easier to |
| 258 |
split string blob into different sections. |
| 259 |
Args: |
| 260 |
lines: list of lines |
| 261 |
|
| 262 |
Returns: dictionary (self._data) with parsed data. |
| 263 |
|
| 264 |
""" |
| 265 |
self._raw = "\n".join(lines) |
| 266 |
pat = pp.Regex(self._table.ITEM) |
| 267 |
x = [] |
| 268 |
for result, start, end in pat.scanString(self._raw): |
| 269 |
x.append((start, end)) |
| 270 |
for i in range(len(x)): |
| 271 |
try: |
| 272 |
raw = self._raw[x[i][0] : x[i + 1][0]] |
| 273 |
except IndexError: |
| 274 |
raw = self._raw[x[i][0] :] |
| 275 |
lines = raw.splitlines() |
| 276 |
obj = re.search(self._table.ITEM, lines[0]) |
| 277 |
groups = obj.groups() |
| 278 |
groups = [data_type(val)(val) for val in groups] |
| 279 |
if len(groups) >= 1: |
| 280 |
if len(groups) != len( |
| 281 |
self._table.KEY |
| 282 |
if isinstance(self._table.KEY, list) |
| 283 |
else [self._table.KEY] |
| 284 |
): |
| 285 |
raise KeyError( |
| 286 |
"Table with grouped item must contain " "corresponding key(s)" |
| 287 |
) |
| 288 |
master_key = groups[0] if len(groups) == 1 else tuple(groups) |
| 289 |
self._data[master_key] = {} |
| 290 |
if self._view is not None: |
| 291 |
for key, value in self._view.FIELDS.items(): |
| 292 |
tbl = value["table"] |
| 293 |
tbl._view = tbl.VIEW |
| 294 |
if tbl._view is not None and len(tbl._view.COLUMNS) > 0: |
| 295 |
self._data[master_key][key] = StateMachine(tbl).parse(lines) |
| 296 |
if tbl.TITLE is not None or tbl._view.TITLE is not None: |
| 297 |
self._data[master_key][key] = StateMachine(tbl).parse(lines) |
| 298 |
else: |
| 299 |
self._table.TITLE = lines[0] |
| 300 |
delimiter = self._table.DELIMITER or r"\s\s+" |
| 301 |
temp_dict = {} |
| 302 |
pre_space_delimit = self._get_pre_space_delimiter(lines[1]) |
| 303 |
for line in lines[1:]: |
| 304 |
if re.match(pre_space_delimit + r"\s+", line): |
| 305 |
break |
| 306 |
if line.startswith(pre_space_delimit): |
| 307 |
try: |
| 308 |
items = re.split(delimiter, line.strip()) |
| 309 |
item_types = list(map(data_type, items)) |
| 310 |
key, value = convert_to_data_type(items) |
| 311 |
temp_dict[key] = value |
| 312 |
except ValueError: |
| 313 |
regex = ( |
| 314 |
r"(\d+)\s(.*)" |
| 315 |
if item_types[0] == int |
| 316 |
else "(" r".*)\s(\d+)" |
| 317 |
) |
| 318 |
obj = re.search(regex, line) |
| 319 |
if obj: |
| 320 |
items = obj.groups() |
| 321 |
key, value = convert_to_data_type(items) |
| 322 |
temp_dict[key] = value |
| 323 |
# check if next line is blank or new title (delimiter |
| 324 |
# test to fail) |
| 325 |
elif ( |
| 326 |
line.strip() == "" |
| 327 |
or len(re.split(delimiter, line.strip())) <= 1 |
| 328 |
): |
| 329 |
break |
| 330 |
self._insert_eval_data(temp_dict) |
| 331 |
self._data[master_key] = temp_dict |
| 332 |
return self._data |
| 333 |
|
| 334 |
def match_columns(self, event): |
| 335 |
if self._view is None: |
| 336 |
return False |
| 337 |
columns = self._view.COLUMNS.values() |
| 338 |
if len(columns) == 0: |
| 339 |
return False |
| 340 |
if True in [isinstance(i, list) for i in columns]: |
| 341 |
# we have multi line column header |
| 342 |
columns = [[i] if isinstance(i, str) else i for i in columns] |
| 343 |
max_title_len = reduce( |
| 344 |
lambda x, y: x if x > y else y, map(lambda x: len(x), columns) |
| 345 |
) |
| 346 |
for index, item in enumerate(columns): |
| 347 |
columns[index] = item + [None] * (max_title_len - len(item)) |
| 348 |
col_parser = reduce(lambda x, y: x & y, [pp.Literal(i[0]) for i in columns]) |
| 349 |
for line in self._lines: |
| 350 |
if self._parse_literal(line, col_parser): |
| 351 |
for index in range(1, max_title_len): |
| 352 |
col_parser = reduce( |
| 353 |
lambda x, y: x & y, |
| 354 |
[ |
| 355 |
pp.Literal(i[index]) |
| 356 |
for i in columns |
| 357 |
if i[index] is not None |
| 358 |
], |
| 359 |
) |
| 360 |
if self._parse_literal( |
| 361 |
self._lines[self._lines.index(line) + 1], col_parser |
| 362 |
): |
| 363 |
# removing next lines in header title, dont see any |
| 364 |
# use of these lines |
| 365 |
self._lines.pop(self._lines.index(line) + 1) |
| 366 |
else: |
| 367 |
return False |
| 368 |
current_index = self._lines.index(line) |
| 369 |
self._lines = self._lines[current_index:] |
| 370 |
return True |
| 371 |
else: |
| 372 |
continue |
| 373 |
else: |
| 374 |
col_parser = reduce(lambda x, y: x & y, [pp.Literal(i) for i in columns]) |
| 375 |
for line in self._lines: |
| 376 |
if self._parse_literal(line, col_parser): |
| 377 |
d = set(map(lambda x, y: x in y, columns, [line] * len(columns))) |
| 378 |
if d.pop(): |
| 379 |
current_index = self._lines.index(line) |
| 380 |
self._lines = self._lines[current_index:] |
| 381 |
return True |
| 382 |
return False |
| 383 |
|
| 384 |
def match_title(self, event): |
| 385 |
""" |
| 386 |
To check whether given title exists in string blob. |
| 387 |
|
| 388 |
Args: |
| 389 |
event: In case any data is supposed to be passed. |
| 390 |
|
| 391 |
Returns: Boolean value depending on matching of title |
| 392 |
|
| 393 |
""" |
| 394 |
title = self._table.TITLE or self._view.TITLE |
| 395 |
for line in self._lines: |
| 396 |
if title in line: |
| 397 |
current_index = self._lines.index(line) |
| 398 |
self._lines = self._lines[current_index:] |
| 399 |
return True |
| 400 |
return False |
| 401 |
|
| 402 |
def title_not_followed_by_columns(self, event): |
| 403 |
return not self.match_columns(event) |
| 404 |
|
| 405 |
def _parse_literal(self, line, col_parser): |
| 406 |
try: |
| 407 |
if col_parser.searchString(line): |
| 408 |
return True |
| 409 |
except pp.ParseException as ex: |
| 410 |
return False |
| 411 |
|
| 412 |
def check_header_bar(self, event): |
| 413 |
""" |
| 414 |
Remove redundant title bar line from lines. |
| 415 |
Args: |
| 416 |
event: |
| 417 |
|
| 418 |
Returns: Boolean depending on if the next line is a title bar or not. |
| 419 |
|
| 420 |
For example, here if we provide columns, we need to get rid of next line |
| 421 |
--------------------------------------- |
| 422 |
Module Name Active Errors |
| 423 |
--------------------------------------- |
| 424 |
1 PQ3 Chip 0 |
| 425 |
2 Host Loopback 0 |
| 426 |
|
| 427 |
""" |
| 428 |
line = self._lines[1] |
| 429 |
try: |
| 430 |
Identifiers.header_bar.parseString(line, parseAll=True) |
| 431 |
self._lines.pop(1) |
| 432 |
except pp.ParseException as ex: |
| 433 |
return False |
| 434 |
return True |
| 435 |
|
| 436 |
def parse_raw_columns(self, event): |
| 437 |
col_offsets = {} |
| 438 |
col_order = event.kwargs.get("col_order", OrderedDict()) |
| 439 |
line = self._lines[0] |
| 440 |
column = self._view.COLUMNS |
| 441 |
if True in [isinstance(i, list) for i in column.values()]: |
| 442 |
# just take first line of column title |
| 443 |
for k, v in column.items(): |
| 444 |
if isinstance(v, list): |
| 445 |
column[k] = v[0] |
| 446 |
if len(col_order) == 0: |
| 447 |
for key, val in column.items(): |
| 448 |
for result, start, end in pp.Literal(val).scanString(line): |
| 449 |
col_offsets[(start, end)] = result[0] |
| 450 |
user_defined_columns = copy.deepcopy(self._view.COLUMNS) |
| 451 |
for key in sorted(col_offsets.keys()): |
| 452 |
for x, y in self._view.COLUMNS.items(): |
| 453 |
if col_offsets[key] == user_defined_columns.get(x): |
| 454 |
col_order[key] = x |
| 455 |
user_defined_columns.pop(x) |
| 456 |
break |
| 457 |
key = self._get_key(event.kwargs.get("key", self._table.KEY)) |
| 458 |
items = re.split(r"\s\s+", self._lines[1].strip()) |
| 459 |
|
| 460 |
post_integer_data_types = event.kwargs.get("check", list(map(data_type, items))) |
| 461 |
index = event.kwargs.get("index", 1) |
| 462 |
# col_len = len(col_order) |
| 463 |
columns_list = list(col_order.values()) |
| 464 |
for index, line in enumerate(self._lines[index:], start=index): |
| 465 |
items = re.split(r"\s\s+", line.strip()) |
| 466 |
if len(items) >= len(columns_list): |
| 467 |
if len(items) > len(columns_list): |
| 468 |
if ( |
| 469 |
list(col_offsets.keys())[0][0] > 10 |
| 470 |
and self._table.KEY == "name" |
| 471 |
): |
| 472 |
columns_list.insert(0, self._table.KEY) |
| 473 |
else: |
| 474 |
items = items[: len(columns_list)] |
| 475 |
post_integer_data_types, pre_integer_data_types = ( |
| 476 |
list(map(data_type, items)), |
| 477 |
post_integer_data_types, |
| 478 |
) |
| 479 |
if post_integer_data_types == pre_integer_data_types: |
| 480 |
items = list( |
| 481 |
map(lambda data, typ: typ(data), items, post_integer_data_types) |
| 482 |
) |
| 483 |
tmp_dict = dict(zip(columns_list, items)) |
| 484 |
self._insert_data(key, tmp_dict, columns_list) |
| 485 |
else: |
| 486 |
break |
| 487 |
elif line.strip() == "": |
| 488 |
# first check if loop already reached at the end of command o/p |
| 489 |
if not index + 1 >= len(self._lines): |
| 490 |
self.check_next_row( |
| 491 |
check=post_integer_data_types, |
| 492 |
data=self._data, |
| 493 |
index=index, |
| 494 |
col_order=col_order, |
| 495 |
key=key, |
| 496 |
) |
| 497 |
return self._data |
| 498 |
|
| 499 |
def _insert_data(self, key, tmp_dict, columns_list): |
| 500 |
""" |
| 501 |
Insert data per row into main dictionary self._data |
| 502 |
|
| 503 |
Args: |
| 504 |
key: To be used as key to dictionary |
| 505 |
tmp_dict: Temporary dictionary to be populated |
| 506 |
columns_list: Columns defined by the users |
| 507 |
|
| 508 |
Returns: None, function just populates self._data |
| 509 |
|
| 510 |
""" |
| 511 |
self._insert_eval_data(tmp_dict) |
| 512 |
if isinstance(key, (tuple, list)): |
| 513 |
if self._view.FILTERS is not None: |
| 514 |
selected_dict = {} |
| 515 |
for select in self._view.FILTERS: |
| 516 |
if select in columns_list: |
| 517 |
selected_dict[select] = tmp_dict[select] |
| 518 |
if self._table.KEY_ITEMS is None: |
| 519 |
self._data[tuple(tmp_dict[i] for i in key)] = selected_dict |
| 520 |
elif tmp_dict[key] in self._table.KEY_ITEMS: |
| 521 |
self._data[tuple(tmp_dict[i] for i in key)] = selected_dict |
| 522 |
else: |
| 523 |
self._data[tuple(tmp_dict[i] for i in key)] = tmp_dict |
| 524 |
else: |
| 525 |
if self._view.FILTERS is not None: |
| 526 |
selected_dict = {} |
| 527 |
for select in self._view.FILTERS: |
| 528 |
if select in columns_list: |
| 529 |
selected_dict[select] = tmp_dict[select] |
| 530 |
if self._table.KEY_ITEMS is None: |
| 531 |
self._data[tmp_dict[key]] = selected_dict |
| 532 |
elif tmp_dict[key] in self._table.KEY_ITEMS: |
| 533 |
self._data[tmp_dict[key]] = selected_dict |
| 534 |
else: |
| 535 |
if self._table.KEY_ITEMS is None: |
| 536 |
if key not in tmp_dict: |
| 537 |
self._data.update(tmp_dict) |
| 538 |
else: |
| 539 |
self._data[tmp_dict[key]] = tmp_dict |
| 540 |
elif tmp_dict[key] in self._table.KEY_ITEMS: |
| 541 |
self._data[tmp_dict[key]] = tmp_dict |
| 542 |
|
| 543 |
def _get_key(self, key): |
| 544 |
""" |
| 545 |
Fetch the key from columns which will be used to define dictionary |
| 546 |
Args: |
| 547 |
key: user defined key input |
| 548 |
|
| 549 |
Returns: key to be used in dictionary. |
| 550 |
|
| 551 |
""" |
| 552 |
if isinstance(key, list): |
| 553 |
if set( |
| 554 |
[ |
| 555 |
i in self._view.COLUMNS or i in self._view.COLUMNS.values() |
| 556 |
for i in key |
| 557 |
] |
| 558 |
): |
| 559 |
key_temp = [] |
| 560 |
for i in key: |
| 561 |
if i not in self._view.COLUMNS and i in self._view.COLUMNS.values(): |
| 562 |
for user_provided, from_table in self._view.COLUMNS.items(): |
| 563 |
# as dict will be created with user_provided key |
| 564 |
if i == from_table or i == user_provided: |
| 565 |
key_temp.append(user_provided) |
| 566 |
break |
| 567 |
else: |
| 568 |
key_temp.append(i) |
| 569 |
key = tuple(key_temp) |
| 570 |
elif key not in self._view.COLUMNS and key in self._view.COLUMNS.values(): |
| 571 |
for user_provided, from_table in self._view.COLUMNS.items(): |
| 572 |
if key == from_table: |
| 573 |
key = user_provided |
| 574 |
key = key[0] if len(key) == 1 and isinstance(key, tuple) else key |
| 575 |
return key |
| 576 |
|
| 577 |
def prev_next_row_same_type(self, event): |
| 578 |
""" |
| 579 |
Checks if the consecutive two lines of similar types. |
| 580 |
|
| 581 |
Args: |
| 582 |
event: takes parameter from the API call |
| 583 |
|
| 584 |
Returns: Boolean, depending if two lines are of similar types. |
| 585 |
|
| 586 |
""" |
| 587 |
index = event.kwargs.get("index") |
| 588 |
post_integer_data_types = event.kwargs.get("check") |
| 589 |
line = self._lines[index] |
| 590 |
items = re.split(r"\s\s+", line.strip()) |
| 591 |
post_integer_data_types, pre_integer_data_types = ( |
| 592 |
list(map(data_type, items)), |
| 593 |
post_integer_data_types, |
| 594 |
) |
| 595 |
return post_integer_data_types == pre_integer_data_types |
| 596 |
|
| 597 |
def _get_pre_space_delimiter(self, line): |
| 598 |
""" |
| 599 |
Sometime all the data lines under a table is withing some space limit |
| 600 |
which gives a easy way to stop looking for lines if the delimiter is not |
| 601 |
followed. |
| 602 |
Args: |
| 603 |
line: should be first line after title |
| 604 |
|
| 605 |
Returns: decide how much space to be considered as delimiter |
| 606 |
|
| 607 |
For example, in below output, all data for FPCx has 2 space delimiter |
| 608 |
|
| 609 |
Statistics for port 1 connected to device FPC1: |
| 610 |
TX Packets 64 Octets 96106518 |
| 611 |
TX Packets 65-127 Octets 56224217 |
| 612 |
TX Packets 128-255 Octets 4550198 |
| 613 |
TX Packets 256-511 Octets 1841 |
| 614 |
TX Packets 512-1023 Octets 1354 |
| 615 |
Statistics for port 1 connected to device FPC2: |
| 616 |
TX Packets 64 Octets 345354435 |
| 617 |
TX Packets 65-127 Octets 34531 |
| 618 |
TX Packets 128-255 Octets 4351451 |
| 619 |
TX Packets 256-511 Octets 1345 |
| 620 |
TX Packets 512-1023 Octets 526513 |
| 621 |
""" |
| 622 |
pre_space_delimit = "" |
| 623 |
obj = re.search(r"(\s+).*", line) |
| 624 |
if obj: |
| 625 |
pre_space_delimit = obj.group(1) |
| 626 |
return pre_space_delimit |
| 627 |
|
| 628 |
def parse_title_data(self, event): |
| 629 |
""" |
| 630 |
title description in Table helps to get the starting point for starting |
| 631 |
search |
| 632 |
|
| 633 |
Args: |
| 634 |
event: In case trigger want to pass some data |
| 635 |
|
| 636 |
Returns: None, Just add corresponding key, value to existing dict |
| 637 |
|
| 638 |
Let say we have CLI "show xmchip 0 pt stats" output as: |
| 639 |
|
| 640 |
WAN PT statistics (Index 0) |
| 641 |
--------------------------- |
| 642 |
|
| 643 |
PCT entries used by all WI-1 streams : 0 |
| 644 |
PCT entries used by all WI-0 streams : 0 |
| 645 |
PCT entries used by all LI streams : 0 |
| 646 |
CPT entries used by all multicast packets : 0 |
| 647 |
CPT entries used by all WI-1 streams : 0 |
| 648 |
CPT entries used by all WI-0 streams : 0 |
| 649 |
CPT entries used by all LI streams : 0 |
| 650 |
|
| 651 |
Fabric PT statistics (Index 1) |
| 652 |
------------------------------ |
| 653 |
|
| 654 |
PCT entries used by all FI streams : 0 |
| 655 |
PCT entries used by all WI (Unused) streams : 0 |
| 656 |
PCT entries used by all LI streams : 0 |
| 657 |
CPT entries used by all multicast packets : 0 |
| 658 |
CPT entries used by all FI streams : 0 |
| 659 |
CPT entries used by all WI (Unused) streams : 0 |
| 660 |
CPT entries used by all LI streams : 0 |
| 661 |
|
| 662 |
With below table/view to parse the data |
| 663 |
--- |
| 664 |
XMChipStatsTable: |
| 665 |
command: show xmchip 0 pt stats |
| 666 |
target: fpc1 |
| 667 |
view: XMChipStatsView |
| 668 |
|
| 669 |
XMChipStatsView: |
| 670 |
fields: |
| 671 |
wan_pt_stats: _WANPTStatTable |
| 672 |
fabric_pt_stats: _FabricPTStatTable |
| 673 |
|
| 674 |
_WANPTStatTable: |
| 675 |
title: WAN PT statistics (Index 0) |
| 676 |
delimiter: ":" |
| 677 |
|
| 678 |
_FabricPTStatTable: |
| 679 |
title: Fabric PT statistics (Index 1) |
| 680 |
delimiter: ":" |
| 681 |
|
| 682 |
which returns: |
| 683 |
{'fabric_pt_stats': {'CPT entries used by all FI streams': 0, |
| 684 |
'CPT entries used by all LI streams': 0, |
| 685 |
'CPT entries used by all WI (Unused) streams': 0, |
| 686 |
'CPT entries used by all multicast packets': 0, |
| 687 |
'PCT entries used by all FI streams': 0, |
| 688 |
'PCT entries used by all LI streams': 0, |
| 689 |
'PCT entries used by all WI (Unused) streams': 0}, |
| 690 |
'wan_pt_stats': {'CPT entries used by all LI streams': 0, |
| 691 |
'CPT entries used by all WI-0 streams': 0, |
| 692 |
'CPT entries used by all WI-1 streams': 0, |
| 693 |
'CPT entries used by all multicast packets': 0, |
| 694 |
'PCT entries used by all LI streams': 0, |
| 695 |
'PCT entries used by all WI-0 streams': 0, |
| 696 |
'PCT entries used by all WI-1 streams': 0}} |
| 697 |
""" |
| 698 |
if self._view is not None and self._view.REGEX != {}: |
| 699 |
return self.regex_provided() |
| 700 |
# view have only fields, so contains only nested table |
| 701 |
if ( |
| 702 |
self._view is not None |
| 703 |
and self._view.FIELDS |
| 704 |
and not self._view.COLUMNS |
| 705 |
and not self._view.REGEX |
| 706 |
): |
| 707 |
return |
| 708 |
delimiter = self._table.DELIMITER or r"\s\s+" |
| 709 |
pre_space_delimit = self._get_pre_space_delimiter(self._lines[1]) |
| 710 |
for line in self._lines[1:]: |
| 711 |
if re.match(pre_space_delimit + r"\s+", line): |
| 712 |
break |
| 713 |
if line.startswith(pre_space_delimit): |
| 714 |
try: |
| 715 |
items = re.split(delimiter, line.strip()) |
| 716 |
item_types = list(map(data_type, items)) |
| 717 |
key, value = convert_to_data_type(items) |
| 718 |
if self._view is None: |
| 719 |
self._data[key] = value |
| 720 |
elif self._table.KEY_ITEMS is None: |
| 721 |
self._data[self._view.FIELDS.get(key, key)] = value |
| 722 |
elif key in self._table.KEY_ITEMS: |
| 723 |
self._data[self._view.FIELDS.get(key, key)] = value |
| 724 |
except ValueError: |
| 725 |
regex = ( |
| 726 |
r"(\d+)\s(.*)" if item_types[0] == int else "(" r".*)\s(\d+)" |
| 727 |
) |
| 728 |
obj = re.search(regex, line) |
| 729 |
if obj: |
| 730 |
items = obj.groups() |
| 731 |
key, value = convert_to_data_type(items) |
| 732 |
self._data[key] = value |
| 733 |
# check if next line is blank or new title (delimiter test to fail) |
| 734 |
elif line.strip() == "" or len(re.split(delimiter, line.strip())) <= 1: |
| 735 |
break |
| 736 |
return self._data |
| 737 |
|
| 738 |
def parse_using_regex(self, event): |
| 739 |
r""" |
| 740 |
All the regex should add up to match a line |
| 741 |
|
| 742 |
Args: |
| 743 |
event: In case trigger want to pass some data |
| 744 |
|
| 745 |
Returns: None, Just add corresponding key, value to existing dict |
| 746 |
|
| 747 |
Let say we have CLI "show system processes extensive" output as: |
| 748 |
|
| 749 |
PID USERNAME HR PRI NICE SIZE RES STATE C TIME WCPU COMMAND |
| 750 |
11 root 2 155 ki31 0K 32K RUN 0 3214.6 191.31% idle |
| 751 |
19542 root 2 22 0 808M 49872K select 1 90.9H 3.86% chas |
| 752 |
19679 root 1 33 0 723M 1208K select 0 839:37 0.49% python |
| 753 |
19451 root 1 20 0 720M 1052K select 1 60:37 0.20% eventd |
| 754 |
12 root 26 -60 - 0K 416K WAIT 1 635:29 0.00% intr |
| 755 |
|
| 756 |
With a regex table as below |
| 757 |
--- |
| 758 |
SystemProcExtTable: |
| 759 |
command: show system processes extensive |
| 760 |
key: cmd |
| 761 |
view: SystemProcExtView |
| 762 |
|
| 763 |
SystemProcExtView: |
| 764 |
regex: |
| 765 |
pid: '\d+' |
| 766 |
wcpu: '.*(\d+\.\d+)%' |
| 767 |
cmd: '\w+' |
| 768 |
|
| 769 |
which returns something like (data for representation only): |
| 770 |
{'alarm': {'cmd': 'alarm', 'pid': 20483, 'wcpu': '0.00'}, |
| 771 |
'alarmd': {'cmd': 'alarmd', 'pid': 20473, 'wcpu': '0.00'}, |
| 772 |
'appidd': {'cmd': 'appidd', 'pid': 19686, 'wcpu': '0.00'}, |
| 773 |
'apsd': {'cmd': 'apsd', 'pid': 20435, 'wcpu': '0.00'}, |
| 774 |
""" |
| 775 |
_regex = copy.deepcopy(self._view.REGEX) |
| 776 |
for key, val in _regex.items(): |
| 777 |
if val in Identifiers.__dict__: |
| 778 |
_regex[key] = Identifiers.__dict__[val] |
| 779 |
else: |
| 780 |
_regex[key] = pp.Regex(val, flags=re.IGNORECASE) |
| 781 |
|
| 782 |
_regex = reduce(lambda x, y: x + y, _regex.values()) |
| 783 |
for index, line in enumerate(self._lines): |
| 784 |
tmp_dict = {} |
| 785 |
# checking index as there can be blank line at position 0 and 2 |
| 786 |
if line.strip() == "": |
| 787 |
if index > 2: |
| 788 |
if self.is_row_column() or self.is_regex_data(): |
| 789 |
try: |
| 790 |
match = [] |
| 791 |
# check if line after new line matches condition |
| 792 |
# There can be data set where there are new line in between. |
| 793 |
for result, start, end in _regex.scanString( |
| 794 |
self._lines[index + 1] |
| 795 |
): |
| 796 |
match.extend(result) |
| 797 |
if match: |
| 798 |
continue |
| 799 |
else: |
| 800 |
break |
| 801 |
except IndexError: |
| 802 |
break |
| 803 |
else: |
| 804 |
continue |
| 805 |
for result, start, end in _regex.scanString(line): |
| 806 |
# write a different function for this |
| 807 |
for key, val in self._view.REGEX.items(): |
| 808 |
if val not in Identifiers.__dict__: |
| 809 |
obj = re.search( |
| 810 |
val, result[list(self._view.REGEX.keys()).index(key)], re.I |
| 811 |
) |
| 812 |
if obj and len(obj.groups()) >= 1: |
| 813 |
result[list(self._view.REGEX.keys()).index(key)] = ( |
| 814 |
obj.groups()[0] |
| 815 |
) |
| 816 |
items = convert_to_data_type(result) |
| 817 |
tmp_dict = dict(zip(self._view.REGEX.keys(), items)) |
| 818 |
if len(tmp_dict) > 0: |
| 819 |
self._insert_data( |
| 820 |
self._table.KEY, tmp_dict, list(self._view.REGEX.keys()) |
| 821 |
) |
| 822 |
|
| 823 |
def parse_using_item_and_regex(self, event): |
| 824 |
r""" |
| 825 |
when multiple map is provided for regex, they gets added to search each |
| 826 |
line. But when item is '*' each regex item is used to search given value |
| 827 |
regular expression in whole string blob. |
| 828 |
|
| 829 |
Args: |
| 830 |
event: In case trigger want to pass some data |
| 831 |
|
| 832 |
Returns: None, Just add corresponding key, value to existing dict |
| 833 |
|
| 834 |
Let say we have CLI "show xmchip 0 pt stats" output as: |
| 835 |
|
| 836 |
PCT entries used by all WI-1 streams : 21 |
| 837 |
PCT entries used by all WI-0 streams : 34 |
| 838 |
PCT entries used by all LI streams : 0 |
| 839 |
CPT entries used by all multicast packets : 0 |
| 840 |
CPT entries used by all WI-1 streams : 0 |
| 841 |
CPT entries used by all WI-0 streams : 0 |
| 842 |
CPT entries used by all LI streams : 0 |
| 843 |
|
| 844 |
--- |
| 845 |
XMChipStatsTable: |
| 846 |
command: show xmchip {{ instance }} pt stats |
| 847 |
args: |
| 848 |
instance: 0 |
| 849 |
target: fpc2 |
| 850 |
item: '*' |
| 851 |
view: XMChipStatsView |
| 852 |
|
| 853 |
XMChipStatsView: |
| 854 |
regex: |
| 855 |
pct_wi_1: 'PCT entries used by all WI-1 streams\s+:\s?(\d+)' |
| 856 |
pct_wi_0: 'PCT entries used by all WI-0 streams\s+:\s?(\d+)' |
| 857 |
|
| 858 |
which returns: |
| 859 |
{'pct_wi_1': 0, 'pct_wi_0': 0} |
| 860 |
""" |
| 861 |
if self._table.ITEM == "*": |
| 862 |
self._raw = "\n".join(self._lines) |
| 863 |
for key, regex in self._view.REGEX.items(): |
| 864 |
obj = re.search(regex, self._raw) |
| 865 |
if obj: |
| 866 |
val = obj.groups()[0] if len(obj.groups()) >= 1 else obj.group() |
| 867 |
self._data[key] = data_type(val)(val) |
| 868 |
self._insert_eval_data(self._data) |
| 869 |
else: |
| 870 |
key = self._get_key(event.kwargs.get("key", self._table.KEY)) |
| 871 |
for line in re.finditer("%s .*" % self._table.ITEM, "\n".join(self._lines)): |
| 872 |
tmp_dict = {} |
| 873 |
for k, exp in self._view.REGEX.items(): |
| 874 |
obj = re.search(exp, line.group()) |
| 875 |
if obj: |
| 876 |
val = obj.groups()[0] if len(obj.groups()) >= 1 else obj.group() |
| 877 |
tmp_dict[k] = data_type(val)(val) |
| 878 |
self._insert_eval_data(tmp_dict) |
| 879 |
if key in tmp_dict: |
| 880 |
self._data[tmp_dict[key]] = tmp_dict |
| 881 |
return self._data |
| 882 |
|
| 883 |
def parse_using_delimiter(self, event): |
| 884 |
""" |
| 885 |
|
| 886 |
Args: |
| 887 |
event: In case trigger want to pass some data |
| 888 |
|
| 889 |
Returns: None, Just add corresponding key, value to existing dict |
| 890 |
|
| 891 |
For a given cli "show link stats" output: |
| 892 |
PPP LCP/NCP: 0 |
| 893 |
HDLC keepalives: 0 |
| 894 |
RSVP: 0 |
| 895 |
ISIS: 0 |
| 896 |
OSPF Hello: 541025 |
| 897 |
OAM: 0 |
| 898 |
BFD: 15 |
| 899 |
UBFD: 0 |
| 900 |
LMI: 0 |
| 901 |
LACP: 0 |
| 902 |
ETHOAM: 0 |
| 903 |
SYNCE: 0 |
| 904 |
PTP: 0 |
| 905 |
L2TP: 0 |
| 906 |
LNS-PPP: 0 |
| 907 |
ARP: 4307 |
| 908 |
ELMI: 0 |
| 909 |
VXLAN MRESOLVE: 0 |
| 910 |
Unknown protocol: 42 |
| 911 |
|
| 912 |
Lets say we can have table as |
| 913 |
--- |
| 914 |
FPCLinkStatTable: |
| 915 |
command: show link stats |
| 916 |
target: fpc1 |
| 917 |
delimiter: ":" |
| 918 |
|
| 919 |
which given return value as |
| 920 |
{'ARP': 4307, 'ELMI': 0, 'SYNCE': 0, 'ISIS': 0, 'BFD': 15, |
| 921 |
'PPP LCP/NCP': 0, 'OAM': 0, 'ETHOAM': 0, 'LACP': 0, 'LMI': 0, |
| 922 |
'Unknown protocol': 42, 'UBFD': 0, 'L2TP': 0, 'HDLC keepalives': 0, |
| 923 |
'LNS-PPP': 0, 'OSPF Hello': 541025, 'RSVP': 0, 'VXLAN MRESOLVE': 0, |
| 924 |
'PTP': 0} |
| 925 |
|
| 926 |
""" |
| 927 |
delimiter = self._table.DELIMITER or r"\s\s+" |
| 928 |
pre_space_delimit = "" |
| 929 |
if self._table.TITLE is None: |
| 930 |
for line in self._lines[1:]: |
| 931 |
if line.strip() == "SENT: Ukern command: %s" % self._table.GET_CMD: |
| 932 |
self._lines = self._lines[self._lines.index(line) + 1 :] |
| 933 |
break |
| 934 |
else: |
| 935 |
obj = re.search(r"^(\s+).*", self._lines[1]) |
| 936 |
if obj: |
| 937 |
pre_space_delimit = obj.group(1) |
| 938 |
for index, line in enumerate(self._lines[1:]): |
| 939 |
if line.strip() == "": |
| 940 |
if index > 2: |
| 941 |
break |
| 942 |
else: |
| 943 |
continue |
| 944 |
if line.startswith(pre_space_delimit): |
| 945 |
try: |
| 946 |
items = re.split(delimiter, line.strip()) |
| 947 |
key, value = convert_to_data_type(items) |
| 948 |
if self._table.KEY_ITEMS is None: |
| 949 |
self._data[key] = value |
| 950 |
elif key in self._table.KEY_ITEMS: |
| 951 |
self._data[key] = value |
| 952 |
except ValueError as ex: |
| 953 |
# create a class named ParseError |
| 954 |
raise Exception("Not able to parse line: %s" % line) |
| 955 |
else: |
| 956 |
break |
| 957 |
return self._data |
| 958 |
|
| 959 |
def parse_exists(self, event): |
| 960 |
""" |
| 961 |
|
| 962 |
Args: |
| 963 |
event: In case trigger want to pass some data |
| 964 |
|
| 965 |
Returns: None, Just add corresponding key, value to existing dict. Value |
| 966 |
here is a boolean |
| 967 |
|
| 968 |
--- |
| 969 |
HostlbStatusSummaryTable: |
| 970 |
command: show host_loopback status-summary |
| 971 |
target: Null |
| 972 |
view: HostlbStatusSummaryView |
| 973 |
|
| 974 |
HostlbStatusSummaryView: |
| 975 |
exists: |
| 976 |
no_detected_wedges: No detected wedges |
| 977 |
no_toolkit_errors: No toolkit errors |
| 978 |
|
| 979 |
should give something like |
| 980 |
{'no_detected_wedges': True, 'no_toolkit_errors': True} |
| 981 |
""" |
| 982 |
for key, search in self._view.EXISTS.items(): |
| 983 |
self._data[key] = re.search(search, self._raw, re.I | re.M) is not None |
| 984 |
|
| 985 |
def _insert_eval_data(self, tmp_dict): |
| 986 |
r""" |
| 987 |
|
| 988 |
Args: |
| 989 |
tmp_dict: dictionary of key value from a iteration of view |
| 990 |
|
| 991 |
Returns: if there is any eval expression in view, does the eval using |
| 992 |
tmp_dictionary. For example: |
| 993 |
|
| 994 |
--- |
| 995 |
XMChipStatsTable: |
| 996 |
command: show xmchip {{ instance }} pt stats |
| 997 |
args: |
| 998 |
instance: 0 |
| 999 |
target: fpc2 |
| 1000 |
item: '*' |
| 1001 |
view: XMChipStatsView |
| 1002 |
|
| 1003 |
XMChipStatsView: |
| 1004 |
regex: |
| 1005 |
pct_wi_1: 'PCT entries used by all WI-1 streams\s+:\s?(\d+)' |
| 1006 |
pct_wi_0: 'PCT entries used by all WI-0 streams\s+:\s?(\d+)' |
| 1007 |
eval: |
| 1008 |
total_pct: '{{ pct_wi_1 }} + {{ pct_wi_0 }}' |
| 1009 |
|
| 1010 |
which returns |
| 1011 |
{'pct_wi_1': 0, 'pct_wi_0': 0, 'total_pct': 0} |
| 1012 |
""" |
| 1013 |
if self._view and len(self._view.EVAL) > 0: |
| 1014 |
for name, expression in self._view.EVAL.items(): |
| 1015 |
variables = meta.find_undeclared_variables(expression) |
| 1016 |
t = Template(expression) |
| 1017 |
expression = t.render({k: tmp_dict.get(k) for k in variables}) |
| 1018 |
val = eval(expression) |
| 1019 |
tmp_dict[name] = val |