Debian Codegraph @

ansible_collections/community/ciscosmb/plugins/modules/facts.py

raw
1 #!/usr/bin/python
2
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import absolute_import, division, print_function
6
7 __metaclass__ = type
8
9 DOCUMENTATION = """
10 ---
11 module: facts
12 author: "Petr Klima (@qaxi)"
13 short_description: Collect facts from remote devices running Cisco SMB
14 description:
15 - Collects a base set of device facts from a remote device that
16 is running Cisco SMB. This module prepends all of the
17 base network fact keys with C(ansible_net_<fact>). The facts
18 module will always collect a base set of facts from the device
19 and can enable or disable collection of additional facts.
20 options:
21 gather_subset:
22 description:
23 - When supplied, this argument will restrict the facts collected
24 to a given subset. Possible values for this argument include
25 C(all), C(hardware), C(config) and C(interfaces). Can specify a list of
26 values to include a larger subset. Values can also be used
27 with an initial C(!) to specify that a specific subset should
28 not be collected.
29 required: false
30 type: list
31 elements: str
32 choices: [ 'default', 'all', 'hardware', 'config', 'interfaces', '!hardware', '!config', '!interfaces' ]
33 default: '!config'
34 notes:
35 - Supports C(check_mode).
36 """
37
38 EXAMPLES = """
39 - name: Collect all facts from the device
40 community.ciscosmb.facts:
41 gather_subset: all
42
43 - name: Collect only the config and default facts
44 community.ciscosmb.facts:
45 gather_subset:
46 - config
47
48 - name: Do not collect hardware facts
49 community.ciscosmb.facts:
50 gather_subset:
51 - "!hardware"
52 """
53
54 RETURN = """
55 ansible_net_gather_subset:
56 description: The list of fact subsets collected from the device.
57 returned: always
58 type: list
59
60 # default
61 ansible_net_model:
62 description: The model name returned from the device.
63 returned: always
64 type: str
65 ansible_net_serialnum:
66 description: The serial number of the remote device.
67 returned: always
68 type: str
69 ansible_net_version:
70 description: The operating system version running on the remote device.
71 returned: always
72 type: str
73 ansible_net_hostname:
74 description: The configured hostname of the device.
75 returned: always
76 type: str
77 ansible_net_uptime:
78 description: The uptime of the device.
79 returned: always
80 type: str
81 ansible_net_cpu_load:
82 description: Current CPU load.
83 returned: always
84 type: str
85 ansible_net_stacked_models:
86 description: The model names of each device in the stack.
87 returned: when multiple devices are configured in a stack
88 type: list
89 ansible_net_stacked_serialnums:
90 description: The serial numbers of each device in the stack.
91 returned: when multiple devices are configured in a stack
92 type: list
93
94 # hardware
95 ansible_net_spacefree_mb:
96 description: The available disk space on the remote device in MiB.
97 returned: when hardware is configured
98 type: dict
99 ansible_net_spacetotal_mb:
100 description: The total disk space on the remote device in MiB.
101 returned: when hardware is configured
102 type: dict
103 ansible_net_memfree_mb:
104 description: The available free memory on the remote device in MiB.
105 returned: when hardware is configured
106 type: int
107 ansible_net_memtotal_mb:
108 description: The total memory on the remote device in MiB.
109 returned: when hardware is configured
110 type: int
111
112 # config
113 ansible_net_config:
114 description: The current active config from the device.
115 returned: when config is configured
116 type: str
117
118 # interfaces
119 ansible_net_all_ipv4_addresses:
120 description: All IPv4 addresses configured on the device.
121 returned: when interfaces is configured
122 type: list
123 ansible_net_all_ipv6_addresses:
124 description: All IPv6 addresses configured on the device.
125 returned: when interfaces is configured
126 type: list
127 ansible_net_interfaces:
128 description: A hash of all interfaces running on the system.
129 returned: when interfaces is configured
130 type: dict
131 ansible_net_neighbors:
132 description: The list of neighbors from the remote device.
133 returned: when interfaces is configured
134 type: dict
135
136 """
137 import re
138
139 from ansible_collections.community.ciscosmb.plugins.module_utils.ciscosmb import (
140 run_commands,
141 ciscosmb_argument_spec,
142 interface_canonical_name,
143 ciscosmb_split_to_tables,
144 ciscosmb_parse_table,
145 ciscosmb_merge_dicts,
146 )
147 from ansible.module_utils.basic import AnsibleModule
148 from ansible.module_utils.six import iteritems
149
150
151 class FactsBase(object):
152
153 COMMANDS = list()
154
155 def __init__(self, module):
156 self.module = module
157 self.facts = dict()
158 self.responses = None
159
160 def populate(self):
161 self.responses = run_commands(
162 self.module, commands=self.COMMANDS, check_rc=False
163 )
164
165 def run(self, cmd):
166 return run_commands(self.module, commands=cmd, check_rc=False)
167
168
169 class Default(FactsBase):
170
171 COMMANDS = [
172 "show version",
173 "show system",
174 "show cpu utilization",
175 "show inventory",
176 ]
177
178 def populate(self):
179 super(Default, self).populate()
180
181 data = self.responses[0]
182 if data:
183 self.facts["version"] = self.parse_version(data)
184 self.facts["boot_version"] = self.parse_boot_version(data)
185
186 data = self.responses[1]
187 if data:
188 self.facts["uptime"] = self.parse_uptime(data)
189 self.facts["hostname"] = self.parse_hostname(data)
190
191 data = self.responses[2]
192 if data:
193 self.facts["cpu_load"] = self.parse_cpu_load(data)
194
195 data = self.responses[3]
196 if data:
197 modules = self.parse_inventory(data)
198 stacked_models = self.parse_stacked_models(modules)
199 if len(stacked_models) >= 2:
200 stacked_serialnums = self.parse_stacked_serialnums(modules)
201 self.facts["stacked_models"] = stacked_models
202 self.facts["stacked_serialnums"] = stacked_serialnums
203 self.facts["model"] = self.parse_model(modules)
204 self.facts["serialnum"] = self.parse_serialnum(modules)
205 self.facts["hw_version"] = self.parse_hw_version(modules)
206 self.facts["hw_modules"] = modules
207
208 # show version
209 def parse_version(self, data):
210 # Cisco SMB 300 and 500 - fw 1.x.x.x
211 match = re.search(r"^SW version\s*(\S+)\s*.*$", data, re.M)
212 if match:
213 return match.group(1)
214 # Cisco SMB 350 and 550 - fw 2.x.x.x
215 match = re.search(r"^ Version:\s*(\S+)\s*.*$", data, re.M)
216 if match:
217 return match.group(1)
218
219 def parse_boot_version(self, data):
220 match = re.search(r"Boot version\s*(\S+)\s*.*$", data, re.M)
221 if match:
222 return match.group(1)
223
224 # show system
225 def parse_uptime(self, data):
226 match = re.search(r"^System Up Time \S+:\s+(\S+)\s*$", data, re.M)
227 if match:
228 (dayhour, mins, sec) = match.group(1).split(":")
229 (day, hour) = dayhour.split(",")
230 # output in seconds
231 return (int(day) * 86400) + (int(hour) * 3600) + (int(mins) * 60) + int(sec)
232
233 def parse_hostname(self, data):
234 match = re.search(r"^System Name:\s*(\S+)\s*$", data, re.M)
235 if match:
236 return match.group(1)
237
238 # show cpu utilization
239 def parse_cpu_load(self, data):
240 match = re.search(r"one minute:\s+(\d+)%;\s*", data, re.M)
241 if match:
242 return match.group(1)
243
244 # show inventory
245 def parse_inventory(self, data):
246 # make 1 module 1 line
247 data = re.sub(r"\nPID", " PID", data)
248 # delete empty lines
249 data = re.sub(r"^\n", "", data)
250 data = re.sub(r"\n\n", "", data)
251 data = re.sub(r"\n\s*\n", r"\n", data)
252
253 lines = data.splitlines()
254
255 modules = {}
256 for line in lines:
257 # remove extra chars
258 line = re.sub(r'"', r"", line)
259 line = re.sub(r"\s+", r" ", line)
260 # normalize lines
261 line = re.sub(r":\s", r'"', line)
262 line = re.sub(r'\s+DESCR"', r'"DESCR"', line)
263 line = re.sub(r'\s+PID"', r'"PID"', line)
264 line = re.sub(r'\s+VID"', r'"VID"', line)
265 line = re.sub(r'\s+SN"', r'"SN"', line)
266 line = re.sub(r"\s*$", r"", line)
267
268 match = re.search(
269 r'^NAME"(?P<name>[^"]+)"DESCR"(?P<descr>[^"]+)"PID"(?P<pid>[^"]+)"VID"(?P<vid>[^"]+)"SN"(?P<sn>\S+)\s*',
270 line,
271 )
272
273 if match:
274 modul = match.groupdict()
275 modules[modul["name"]] = modul
276
277 if modules:
278 return modules
279
280 def parse_stacked_models(self, data):
281 # every inventory has module with NAME: "1"
282 # stacks have modules 2 3 ... 8
283 models = []
284 for n in range(1, 9):
285 # index is string
286 if str(n) in data:
287 models.append(data[str(n)]["pid"])
288 return models
289
290 def parse_stacked_serialnums(self, data):
291 # every inventory has module with NAME: "1"
292 # stacks have modules 2 3 ... 8
293 sn = []
294 for n in range(1, 9):
295 # index is string
296 if str(n) in data:
297 sn.append(data[str(n)]["sn"])
298 return sn
299
300 def parse_model(self, data):
301 # every inventory has module with NAME: "1"
302 model = data["1"]["pid"]
303 if "stacked_models" in self.facts:
304 model = re.sub(r"-.*$", "", model)
305 model = "Stack " + model
306 return model
307
308 def parse_serialnum(self, data):
309 # every inventory has module with NAME: "1"
310 sn = data["1"]["sn"]
311 return sn
312
313 def parse_hw_version(self, data):
314 # every inventory has module with NAME: "1"
315 sn = data["1"]["vid"]
316 return sn
317
318
319 class Hardware(FactsBase):
320
321 COMMANDS = [
322 "dir",
323 ]
324
325 def populate(self):
326 super(Hardware, self).populate()
327 data = self.responses[0]
328 if data:
329 self.parse_filesystem_info(data)
330
331 def parse_filesystem_info(self, data):
332 match = re.search(r"Total size of (\S+): (\d+) bytes", data, re.M)
333
334 if match: # fw 1.x
335 self.facts["spacetotal_mb"] = round(int(match.group(2)) / 1024 / 1024, 1)
336 match = re.search(r"Free size of (\S+): (\d+) bytes", data, re.M)
337 self.facts["spacefree_mb"] = round(int(match.group(2)) / 1024 / 1024, 1)
338
339 else:
340 match = re.search(r"(\d+)K of (\d+)K are free", data, re.M)
341 if match: # fw 2.x, 3.x
342 self.facts["spacetotal_mb"] = round(int(match.group(2)) / 1024, 1)
343 self.facts["spacefree_mb"] = round(int(match.group(1)) / 1024, 1)
344
345
346 class Config(FactsBase):
347
348 COMMANDS = ["show running-config detailed"]
349
350 def populate(self):
351 super(Config, self).populate()
352 data = self.responses[0]
353 if data:
354 self.facts["config"] = data
355
356
357 class Interfaces(FactsBase):
358
359 COMMANDS = [
360 "show ports jumbo-frame",
361 "show ip interface",
362 "show ipv6 interface brief",
363 "show interfaces status",
364 "show interfaces configuration",
365 "show interfaces description",
366 "show lldp neighbors",
367 ]
368
369 DETAIL_RE = re.compile(
370 r"([\w\d\-]+)=\"?(\w{3}/\d{2}/\d{4}\s\d{2}:\d{2}:\d{2}|[\w\d\-\.:/]+)"
371 )
372 WRAPPED_LINE_RE = re.compile(r"^\s+(?!\d)")
373
374 def populate(self):
375 super(Interfaces, self).populate()
376
377 self.facts["interfaces"] = dict()
378 self.facts["all_ipv4_addresses"] = list()
379 self.facts["all_ipv6_addresses"] = list()
380 self.facts["neighbors"] = list()
381
382 data = self.responses[0]
383 if data:
384 self.populate_interfaces_mtu(data)
385
386 data = self.responses[1]
387 if data:
388 self.populate_addresses_ipv4(data)
389
390 data = self.responses[2]
391 if data:
392 self.populate_addresses_ipv6(data)
393
394 data = self.responses[3]
395 if data:
396 self.populate_interfaces_status(data)
397
398 data = self.responses[4]
399 if data:
400 self.populate_interfaces_configuration(data)
401
402 data = self.responses[5]
403 if data:
404 self.populate_interfaces_description(data)
405
406 data = self.responses[6]
407 if data:
408 self.populate_neighbors(data)
409
410 def _populate_interfaces_status_interface(self, interface_table):
411 interfaces = dict()
412
413 for key in interface_table:
414
415 i = interface_table[key]
416 interface = dict()
417 interface["state"] = i[6].lower()
418 interface["type"] = i[1]
419 interface["mtu"] = self._mtu
420 interface["duplex"] = i[2].lower()
421 interface["negotiation"] = i[4].lower()
422 interface["control"] = i[5].lower()
423 interface["presure"] = i[7].lower()
424 interface["mode"] = i[8].lower()
425
426 if i[6] == "Up":
427 interface["bandwidth"] = int(i[3]) * 1000 # to get speed in kb
428 interface["bandwith"] = interface["bandwidth"]
429 else:
430 interface["bandwidth"] = None
431 interface["bandwith"] = interface["bandwidth"]
432
433 for key in interface:
434 if interface[key] == "--":
435 interface[key] = None
436
437 interfaces[interface_canonical_name(i[0])] = interface
438 return interfaces
439
440 def _populate_interfaces_status_portchanel(self, interface_table):
441 interfaces = dict()
442
443 for key in interface_table:
444
445 interface = dict()
446 i = interface_table[key]
447 interface["state"] = i[6].lower()
448 interface["type"] = i[1]
449 interface["mtu"] = self._mtu
450 interface["duplex"] = i[2].lower()
451 interface["negotiation"] = i[4].lower()
452 interface["control"] = i[5].lower()
453
454 if i[6] == "Up":
455 interface["bandwidth"] = int(i[3]) * 1000 # to get speed in kb
456 interface["bandwith"] = interface["bandwidth"]
457 else:
458 interface["bandwidth"] = None
459 interface["bandwith"] = interface["bandwidth"]
460
461 for key in interface:
462 if interface[key] == "--":
463 interface[key] = None
464
465 interfaces[interface_canonical_name(i[0])] = interface
466
467 return interfaces
468
469 def populate_interfaces_status(self, data):
470 tables = ciscosmb_split_to_tables(data)
471
472 interface_table = ciscosmb_parse_table(tables[0])
473 portchanel_table = ciscosmb_parse_table(tables[1])
474
475 interfaces = self._populate_interfaces_status_interface(interface_table)
476 self.facts["interfaces"] = ciscosmb_merge_dicts(
477 self.facts["interfaces"], interfaces
478 )
479 interfaces = self._populate_interfaces_status_portchanel(portchanel_table)
480 self.facts["interfaces"] = ciscosmb_merge_dicts(
481 self.facts["interfaces"], interfaces
482 )
483
484 def _populate_interfaces_configuration_interface(self, interface_table):
485 interfaces = dict()
486
487 for key in interface_table:
488
489 i = interface_table[key]
490 interface = dict()
491 interface["admin_state"] = i[6].lower()
492 interface["mdix"] = i[8].lower()
493
494 interfaces[interface_canonical_name(i[0])] = interface
495 return interfaces
496
497 def _populate_interfaces_configuration_portchanel(self, interface_table):
498 interfaces = dict()
499
500 for key in interface_table:
501
502 interface = dict()
503 i = interface_table[key]
504
505 interface["admin_state"] = i[5].lower()
506
507 interfaces[interface_canonical_name(i[0])] = interface
508
509 return interfaces
510
511 def populate_interfaces_configuration(self, data):
512 tables = ciscosmb_split_to_tables(data)
513
514 interface_table = ciscosmb_parse_table(tables[0])
515 portchanel_table = ciscosmb_parse_table(tables[1])
516
517 interfaces = self._populate_interfaces_configuration_interface(interface_table)
518 self.facts["interfaces"] = ciscosmb_merge_dicts(
519 self.facts["interfaces"], interfaces
520 )
521 interfaces = self._populate_interfaces_configuration_portchanel(
522 portchanel_table
523 )
524 self.facts["interfaces"] = ciscosmb_merge_dicts(
525 self.facts["interfaces"], interfaces
526 )
527
528 def _populate_interfaces_description_interface(self, interface_table):
529 interfaces = dict()
530
531 for key in interface_table:
532
533 i = interface_table[key]
534 interface = dict()
535 interface["description"] = i[1]
536
537 if interface["description"] == "":
538 interface["description"] = None
539
540 interfaces[interface_canonical_name(i[0])] = interface
541 return interfaces
542
543 def _populate_interfaces_description_portchanel(self, interface_table):
544 interfaces = dict()
545
546 for key in interface_table:
547
548 interface = dict()
549 i = interface_table[key]
550
551 interface["description"] = i[1]
552
553 if interface["description"] == "":
554 interface["description"] = None
555
556 interfaces[interface_canonical_name(i[0])] = interface
557
558 return interfaces
559
560 def populate_interfaces_description(self, data):
561 tables = ciscosmb_split_to_tables(data)
562
563 interface_table = ciscosmb_parse_table(tables[0], False)
564 portchanel_table = ciscosmb_parse_table(tables[1], False)
565
566 interfaces = self._populate_interfaces_description_interface(interface_table)
567 self.facts["interfaces"] = ciscosmb_merge_dicts(
568 self.facts["interfaces"], interfaces
569 )
570 interfaces = self._populate_interfaces_description_portchanel(portchanel_table)
571 self.facts["interfaces"] = ciscosmb_merge_dicts(
572 self.facts["interfaces"], interfaces
573 )
574
575 def _populate_address_ipv4(self, ip_table):
576 ips = list()
577
578 for key in ip_table:
579 cidr = ip_table[key][0]
580
581 interface = interface_canonical_name(ip_table[key][1])
582 ip, mask = cidr.split("/")
583
584 ips.append(ip)
585
586 # add ips to interface
587 self._new_interface(interface)
588 if "ipv4" not in self.facts["interfaces"][interface]:
589 self.facts["interfaces"][interface]["ipv4"] = list()
590
591 self.facts["interfaces"][interface]["ipv4"].append(
592 dict(address=ip, subnet=mask)
593 )
594
595 return ips
596
597 def populate_addresses_ipv4(self, data):
598 tables = ciscosmb_split_to_tables(data)
599 ip_table = ciscosmb_parse_table(tables[0])
600
601 ips = self._populate_address_ipv4(ip_table)
602 self.facts["all_ipv4_addresses"] = ips
603
604 def _populate_address_ipv6(self, ip_table):
605 ips = list()
606
607 for key in ip_table:
608 ip = ip_table[key][3]
609 interface = interface_canonical_name(ip_table[key][0])
610
611 ips.append(ip)
612
613 # add ips to interface
614 self._new_interface(interface)
615 if "ipv6" not in self.facts["interfaces"][interface]:
616 self.facts["interfaces"][interface]["ipv6"] = list()
617
618 self.facts["interfaces"][interface]["ipv6"].append(dict(address=ip))
619
620 return ips
621
622 def _new_interface(self, interface):
623
624 if interface in self.facts["interfaces"]:
625 return
626 else:
627 self.facts["interfaces"][interface] = dict()
628 self.facts["interfaces"][interface]["mtu"] = self._mtu
629 self.facts["interfaces"][interface]["admin_state"] = "up"
630 self.facts["interfaces"][interface]["description"] = None
631 self.facts["interfaces"][interface]["state"] = "up"
632 self.facts["interfaces"][interface]["bandwidth"] = None
633 self.facts["interfaces"][interface]["bandwith"] = None
634 self.facts["interfaces"][interface]["duplex"] = None
635 self.facts["interfaces"][interface]["negotiation"] = None
636 self.facts["interfaces"][interface]["control"] = None
637 return
638
639 def populate_addresses_ipv6(self, data):
640 tables = ciscosmb_split_to_tables(data)
641
642 ip_table = ciscosmb_parse_table(tables[0])
643 ips = self._populate_address_ipv6(ip_table)
644 self.facts["all_ipv6_addresses"] = ips
645
646 def populate_interfaces_mtu(self, data):
647 # by documentation SG350
648 match = re.search(r"Jumbo frames are enabled", data, re.M)
649 if match:
650 mtu = 9000
651 else:
652 mtu = 1518
653
654 self._mtu = mtu
655
656 def populate_neighbors(self, data):
657 tables = ciscosmb_split_to_tables(data)
658
659 neighbor_table = ciscosmb_parse_table(
660 tables[0],
661 allow_empty_fields=[3, 4]
662 )
663
664 neighbors = dict()
665 for key in neighbor_table:
666 neighbor = neighbor_table[key]
667
668 ifcname = interface_canonical_name(neighbor[0])
669
670 host = neighbor[3]
671 port = neighbor[2]
672
673 hostport = {"host": host, "port": port}
674
675 if ifcname not in neighbors:
676 neighbors[ifcname] = list()
677
678 neighbors[ifcname].append(hostport)
679
680 self.facts["neighbors"] = neighbors
681
682
683 FACT_SUBSETS = dict(
684 default=Default,
685 hardware=Hardware,
686 interfaces=Interfaces,
687 config=Config,
688 )
689
690 VALID_SUBSETS = frozenset(FACT_SUBSETS.keys())
691
692 warnings = list()
693
694
695 def main():
696 """main entry point for module execution"""
697 argument_spec = dict(
698 gather_subset=dict(
699 default=["!config"],
700 type="list",
701 elements="str",
702 choices=[
703 "all",
704 "default",
705 "hardware",
706 "interfaces",
707 "config",
708 "!hardware",
709 "!interfaces",
710 "!config",
711 ],
712 )
713 )
714
715 argument_spec.update(ciscosmb_argument_spec)
716
717 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
718
719 gather_subset = module.params["gather_subset"]
720
721 runable_subsets = set()
722 exclude_subsets = set()
723
724 for subset in gather_subset:
725 if subset == "all":
726 runable_subsets.update(VALID_SUBSETS)
727 continue
728
729 if subset.startswith("!"):
730 subset = subset[1:]
731 if subset == "all":
732 exclude_subsets.update(VALID_SUBSETS)
733 continue
734 exclude = True
735 else:
736 exclude = False
737
738 if subset not in VALID_SUBSETS:
739 module.fail_json(msg="Bad subset: %s" % subset)
740
741 if exclude:
742 exclude_subsets.add(subset)
743 else:
744 runable_subsets.add(subset)
745
746 if not runable_subsets:
747 runable_subsets.update(VALID_SUBSETS)
748
749 runable_subsets.difference_update(exclude_subsets)
750 runable_subsets.add("default")
751
752 facts = dict()
753 facts["gather_subset"] = list(runable_subsets)
754
755 instances = list()
756 for key in runable_subsets:
757 instances.append(FACT_SUBSETS[key](module))
758
759 for inst in instances:
760 inst.populate()
761 facts.update(inst.facts)
762
763 ansible_facts = dict()
764 for key, value in iteritems(facts):
765 key = "ansible_net_%s" % key
766 ansible_facts[key] = value
767
768 module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
769
770
771 if __name__ == "__main__":
772 main()