Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_igmp_interface.py

raw
1 #!/usr/bin/python
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18 from __future__ import absolute_import, division, print_function
19
20
21 __metaclass__ = type
22
23
24 DOCUMENTATION = """
25 module: nxos_igmp_interface
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Manages IGMP interface configuration.
29 description:
30 - Manages IGMP interface configuration settings.
31 version_added: 1.0.0
32 author:
33 - Jason Edelman (@jedelman8)
34 - Gabriele Gerbino (@GGabriele)
35 notes:
36 - Tested against NXOSv 7.3.(0)D1(1) on VIRL
37 - Unsupported for Cisco MDS
38 - When C(state=default), supported params will be reset to a default state. These
39 include C(version), C(startup_query_interval), C(startup_query_count), C(robustness),
40 C(querier_timeout), C(query_mrt), C(query_interval), C(last_member_qrt), C(last_member_query_count),
41 C(group_timeout), C(report_llg), and C(immediate_leave).
42 - When C(state=absent), all configs for C(oif_ps), and C(oif_routemap) will be removed.
43 - PIM must be enabled to use this module.
44 - This module is for Layer 3 interfaces.
45 - Route-map check not performed (same as CLI) check when configuring route-map with
46 'static-oif'
47 - If restart is set to true with other params set, the restart will happen last, i.e.
48 after the configuration takes place. However, 'restart' itself is not idempotent
49 as it is an action and not configuration.
50 options:
51 interface:
52 description:
53 - The full interface name for IGMP configuration. e.g. I(Ethernet1/2).
54 required: true
55 type: str
56 version:
57 description:
58 - IGMP version. It can be 2 or 3 or keyword 'default'.
59 choices:
60 - '2'
61 - '3'
62 - default
63 type: str
64 startup_query_interval:
65 description:
66 - Query interval used when the IGMP process starts up. The range is from 1 to
67 18000 or keyword 'default'. The default is 31.
68 type: str
69 startup_query_count:
70 description:
71 - Query count used when the IGMP process starts up. The range is from 1 to 10
72 or keyword 'default'. The default is 2.
73 type: str
74 robustness:
75 description:
76 - Sets the robustness variable. Values can range from 1 to 7 or keyword 'default'.
77 The default is 2.
78 type: str
79 querier_timeout:
80 description:
81 - Sets the querier timeout that the software uses when deciding to take over as
82 the querier. Values can range from 1 to 65535 seconds or keyword 'default'.
83 The default is 255 seconds.
84 type: str
85 query_mrt:
86 description:
87 - Sets the response time advertised in IGMP queries. Values can range from 1 to
88 25 seconds or keyword 'default'. The default is 10 seconds.
89 type: str
90 query_interval:
91 description:
92 - Sets the frequency at which the software sends IGMP host query messages. Values
93 can range from 1 to 18000 seconds or keyword 'default'. The default is 125 seconds.
94 type: str
95 last_member_qrt:
96 description:
97 - Sets the query interval waited after sending membership reports before the software
98 deletes the group state. Values can range from 1 to 25 seconds or keyword 'default'.
99 The default is 1 second.
100 type: str
101 last_member_query_count:
102 description:
103 - Sets the number of times that the software sends an IGMP query in response to
104 a host leave message. Values can range from 1 to 5 or keyword 'default'. The
105 default is 2.
106 type: str
107 group_timeout:
108 description:
109 - Sets the group membership timeout for IGMPv2. Values can range from 3 to 65,535
110 seconds or keyword 'default'. The default is 260 seconds.
111 type: str
112 report_llg:
113 description:
114 - Configures report-link-local-groups. Enables sending reports for groups in 224.0.0.0/24.
115 Reports are always sent for nonlink local groups. By default, reports are not
116 sent for link local groups.
117 type: bool
118 immediate_leave:
119 description:
120 - Enables the device to remove the group entry from the multicast routing table
121 immediately upon receiving a leave message for the group. Use this command to
122 minimize the leave latency of IGMPv2 group memberships on a given IGMP interface
123 because the device does not send group-specific queries. The default is disabled.
124 type: bool
125 oif_routemap:
126 description:
127 - Configure a routemap for static outgoing interface (OIF) or keyword 'default'.
128 type: str
129 oif_ps:
130 description:
131 - Configure prefixes and sources for static outgoing interface (OIF). This is
132 a list of dict where each dict has source and prefix defined or just prefix
133 if source is not needed. The specified values will be configured on the device
134 and if any previous prefix/sources exist, they will be removed. Keyword 'default'
135 is also accepted which removes all existing prefix/sources.
136 type: raw
137 restart:
138 description:
139 - Restart IGMP. This is NOT idempotent as this is action only.
140 type: bool
141 default: false
142 state:
143 description:
144 - Manages desired state of the resource.
145 default: present
146 choices:
147 - present
148 - absent
149 - default
150 type: str
151 """
152 EXAMPLES = """
153 - cisco.nxos.nxos_igmp_interface:
154 interface: ethernet1/32
155 startup_query_interval: 30
156 oif_ps:
157 - {prefix: 238.2.2.6}
158 - {source: 192.168.0.1, prefix: 238.2.2.5}
159 state: present
160 """
161 RETURN = """
162 proposed:
163 description: k/v pairs of parameters passed into module
164 returned: always
165 type: dict
166 sample: {"startup_query_count": "30",
167 "oif_ps": [{'prefix': '238.2.2.6'}, {'source': '192.168.0.1', 'prefix': '238.2.2.5'}]}
168 existing:
169 description: k/v pairs of existing igmp_interface configuration
170 returned: always
171 type: dict
172 sample: {"startup_query_count": "2", "oif_ps": []}
173 end_state:
174 description: k/v pairs of igmp interface configuration after module execution
175 returned: always
176 type: dict
177 sample: {"startup_query_count": "30",
178 "oif_ps": [{'prefix': '238.2.2.6'}, {'source': '192.168.0.1', 'prefix': '238.2.2.5'}]}
179 updates:
180 description: commands sent to the device
181 returned: always
182 type: list
183 sample: ["interface Ethernet1/32", "ip igmp startup-query-count 30",
184 "ip igmp static-oif 238.2.2.6", "ip igmp static-oif 238.2.2.5 source 192.168.0.1"]
185 changed:
186 description: check to see if a change was made on the device
187 returned: always
188 type: bool
189 sample: true
190 """
191
192 import re
193
194 from ansible.module_utils.basic import AnsibleModule
195
196 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import (
197 get_interface_type,
198 load_config,
199 run_commands,
200 )
201
202
203 def execute_show_command(command, module, command_type="cli_show"):
204 if command_type == "cli_show_ascii":
205 cmds = [{"command": command, "output": "text"}]
206 else:
207 cmds = [{"command": command, "output": "json"}]
208
209 return run_commands(module, cmds)
210
211
212 def get_interface_mode(interface, intf_type, module):
213 command = "show interface {0}".format(interface)
214 interface = {}
215 mode = "unknown"
216
217 if intf_type in ["ethernet", "portchannel"]:
218 body = execute_show_command(command, module)[0]
219 interface_table = body["TABLE_interface"]["ROW_interface"]
220 mode = str(interface_table.get("eth_mode", "layer3"))
221 if mode == "access" or mode == "trunk":
222 mode = "layer2"
223 elif intf_type == "loopback" or intf_type == "svi":
224 mode = "layer3"
225 return mode
226
227
228 def apply_key_map(key_map, table):
229 new_dict = {}
230 for key, value in table.items():
231 new_key = key_map.get(key)
232 if new_key:
233 value = table.get(key)
234 if value:
235 new_dict[new_key] = value
236 else:
237 new_dict[new_key] = value
238 return new_dict
239
240
241 def flatten_list(command_lists):
242 flat_command_list = []
243 for command in command_lists:
244 if isinstance(command, list):
245 flat_command_list.extend(command)
246 else:
247 flat_command_list.append(command)
248 return flat_command_list
249
250
251 def get_igmp_interface(module, interface):
252 command = "show ip igmp interface {0}".format(interface)
253 igmp = {}
254
255 key_map = {
256 "IGMPVersion": "version",
257 "ConfiguredStartupQueryInterval": "startup_query_interval",
258 "StartupQueryCount": "startup_query_count",
259 "RobustnessVariable": "robustness",
260 "ConfiguredQuerierTimeout": "querier_timeout",
261 "ConfiguredMaxResponseTime": "query_mrt",
262 "ConfiguredQueryInterval": "query_interval",
263 "LastMemberMTR": "last_member_qrt",
264 "LastMemberQueryCount": "last_member_query_count",
265 "ConfiguredGroupTimeout": "group_timeout",
266 }
267
268 body = execute_show_command(command, module)[0]
269
270 if body:
271 if "not running" in body:
272 return igmp
273 resource = body["TABLE_vrf"]["ROW_vrf"]["TABLE_if"]["ROW_if"]
274 igmp = apply_key_map(key_map, resource)
275 report_llg = str(resource["ReportingForLinkLocal"]).lower()
276 if report_llg == "true":
277 igmp["report_llg"] = True
278 elif report_llg == "false":
279 igmp["report_llg"] = False
280
281 immediate_leave = str(resource["ImmediateLeave"]).lower() # returns en or dis
282 if re.search(r"^en|^true|^enabled", immediate_leave):
283 igmp["immediate_leave"] = True
284 elif re.search(r"^dis|^false|^disabled", immediate_leave):
285 igmp["immediate_leave"] = False
286
287 # the next block of code is used to retrieve anything with:
288 # ip igmp static-oif *** i.e.. could be route-map ROUTEMAP
289 # or PREFIX source <ip>, etc.
290 command = "show run interface {0} | inc oif".format(interface)
291
292 body = execute_show_command(command, module, command_type="cli_show_ascii")[0]
293
294 staticoif = []
295 if body:
296 split_body = body.split("\n")
297 route_map_regex = r".*ip igmp static-oif route-map\s+(?P<route_map>\S+).*"
298 prefix_source_regex = (
299 r".*ip igmp static-oif\s+(?P<prefix>"
300 r"((\d+.){3}\d+))(\ssource\s"
301 r"(?P<source>\S+))?.*"
302 )
303
304 for line in split_body:
305 temp = {}
306 try:
307 match_route_map = re.match(route_map_regex, line, re.DOTALL)
308 route_map = match_route_map.groupdict()["route_map"]
309 except AttributeError:
310 route_map = ""
311
312 try:
313 match_prefix_source = re.match(prefix_source_regex, line, re.DOTALL)
314 prefix_source_group = match_prefix_source.groupdict()
315 prefix = prefix_source_group["prefix"]
316 source = prefix_source_group["source"]
317 except AttributeError:
318 prefix = ""
319 source = ""
320
321 if route_map:
322 temp["route_map"] = route_map
323 if prefix:
324 temp["prefix"] = prefix
325 if source:
326 temp["source"] = source
327 if temp:
328 staticoif.append(temp)
329
330 igmp["oif_routemap"] = None
331 igmp["oif_prefix_source"] = []
332
333 if staticoif:
334 if len(staticoif) == 1 and staticoif[0].get("route_map"):
335 igmp["oif_routemap"] = staticoif[0]["route_map"]
336 else:
337 igmp["oif_prefix_source"] = staticoif
338
339 return igmp
340
341
342 def config_igmp_interface(delta, existing, existing_oif_prefix_source):
343 CMDS = {
344 "version": "ip igmp version {0}",
345 "startup_query_interval": "ip igmp startup-query-interval {0}",
346 "startup_query_count": "ip igmp startup-query-count {0}",
347 "robustness": "ip igmp robustness-variable {0}",
348 "querier_timeout": "ip igmp querier-timeout {0}",
349 "query_mrt": "ip igmp query-max-response-time {0}",
350 "query_interval": "ip igmp query-interval {0}",
351 "last_member_qrt": "ip igmp last-member-query-response-time {0}",
352 "last_member_query_count": "ip igmp last-member-query-count {0}",
353 "group_timeout": "ip igmp group-timeout {0}",
354 "report_llg": "ip igmp report-link-local-groups",
355 "immediate_leave": "ip igmp immediate-leave",
356 "oif_prefix_source": "ip igmp static-oif {0} source {1} ",
357 "oif_routemap": "ip igmp static-oif route-map {0}",
358 "oif_prefix": "ip igmp static-oif {0}",
359 }
360
361 commands = []
362 command = None
363 def_vals = get_igmp_interface_defaults()
364
365 for key, value in delta.items():
366 if key == "oif_ps" and value != "default":
367 for each in value:
368 if each in existing_oif_prefix_source:
369 existing_oif_prefix_source.remove(each)
370 else:
371 # add new prefix/sources
372 pf = each["prefix"]
373 src = ""
374 if "source" in each.keys():
375 src = each["source"]
376 if src:
377 commands.append(CMDS.get("oif_prefix_source").format(pf, src))
378 else:
379 commands.append(CMDS.get("oif_prefix").format(pf))
380 if existing_oif_prefix_source:
381 for each in existing_oif_prefix_source:
382 # remove stale prefix/sources
383 pf = each["prefix"]
384 src = ""
385 if "source" in each.keys():
386 src = each["source"]
387 if src:
388 commands.append(
389 "no " + CMDS.get("oif_prefix_source").format(pf, src),
390 )
391 else:
392 commands.append("no " + CMDS.get("oif_prefix").format(pf))
393 elif key == "oif_routemap":
394 if value == "default":
395 if existing.get(key):
396 command = "no " + CMDS.get(key).format(existing.get(key))
397 else:
398 command = CMDS.get(key).format(value)
399 elif value:
400 if value == "default":
401 if def_vals.get(key) != existing.get(key):
402 command = CMDS.get(key).format(def_vals.get(key))
403 else:
404 command = CMDS.get(key).format(value)
405 elif not value:
406 command = "no {0}".format(CMDS.get(key).format(value))
407
408 if command:
409 if command not in commands:
410 commands.append(command)
411 command = None
412
413 return commands
414
415
416 def get_igmp_interface_defaults():
417 version = "2"
418 startup_query_interval = "31"
419 startup_query_count = "2"
420 robustness = "2"
421 querier_timeout = "255"
422 query_mrt = "10"
423 query_interval = "125"
424 last_member_qrt = "1"
425 last_member_query_count = "2"
426 group_timeout = "260"
427 report_llg = False
428 immediate_leave = False
429
430 args = dict(
431 version=version,
432 startup_query_interval=startup_query_interval,
433 startup_query_count=startup_query_count,
434 robustness=robustness,
435 querier_timeout=querier_timeout,
436 query_mrt=query_mrt,
437 query_interval=query_interval,
438 last_member_qrt=last_member_qrt,
439 last_member_query_count=last_member_query_count,
440 group_timeout=group_timeout,
441 report_llg=report_llg,
442 immediate_leave=immediate_leave,
443 )
444
445 default = dict((param, value) for (param, value) in args.items() if value is not None)
446
447 return default
448
449
450 def config_default_igmp_interface(existing, delta):
451 commands = []
452 proposed = get_igmp_interface_defaults()
453 delta = dict(set(proposed.items()).difference(existing.items()))
454 if delta:
455 command = config_igmp_interface(
456 delta,
457 existing,
458 existing_oif_prefix_source=None,
459 )
460
461 if command:
462 for each in command:
463 commands.append(each)
464
465 return commands
466
467
468 def config_remove_oif(existing, existing_oif_prefix_source):
469 commands = []
470 command = None
471 if existing.get("oif_routemap"):
472 commands.append(
473 "no ip igmp static-oif route-map {0}".format(existing.get("oif_routemap")),
474 )
475 elif existing_oif_prefix_source:
476 for each in existing_oif_prefix_source:
477 if each.get("prefix") and each.get("source"):
478 command = "no ip igmp static-oif {0} source {1} ".format(
479 each.get("prefix"),
480 each.get("source"),
481 )
482 elif each.get("prefix"):
483 command = "no ip igmp static-oif {0}".format(each.get("prefix"))
484 if command:
485 commands.append(command)
486 command = None
487
488 return commands
489
490
491 def main():
492 argument_spec = dict(
493 interface=dict(required=True, type="str"),
494 version=dict(required=False, type="str", choices=["2", "3", "default"]),
495 startup_query_interval=dict(required=False, type="str"),
496 startup_query_count=dict(required=False, type="str"),
497 robustness=dict(required=False, type="str"),
498 querier_timeout=dict(required=False, type="str"),
499 query_mrt=dict(required=False, type="str"),
500 query_interval=dict(required=False, type="str"),
501 last_member_qrt=dict(required=False, type="str"),
502 last_member_query_count=dict(required=False, type="str"),
503 group_timeout=dict(required=False, type="str"),
504 report_llg=dict(type="bool"),
505 immediate_leave=dict(type="bool"),
506 oif_routemap=dict(required=False, type="str"),
507 oif_ps=dict(required=False, type="raw"),
508 restart=dict(type="bool", default=False),
509 state=dict(choices=["present", "absent", "default"], default="present"),
510 )
511
512 mutually_exclusive = [("oif_ps", "oif_routemap")]
513
514 module = AnsibleModule(
515 argument_spec=argument_spec,
516 mutually_exclusive=mutually_exclusive,
517 supports_check_mode=True,
518 )
519
520 warnings = list()
521
522 state = module.params["state"]
523 interface = module.params["interface"]
524 oif_routemap = module.params["oif_routemap"]
525 oif_ps = module.params["oif_ps"]
526
527 intf_type = get_interface_type(interface)
528 if get_interface_mode(interface, intf_type, module) == "layer2":
529 module.fail_json(msg="this module only works on Layer 3 interfaces")
530
531 existing = get_igmp_interface(module, interface)
532 existing_copy = existing.copy()
533 end_state = existing_copy
534
535 if not existing.get("version"):
536 module.fail_json(msg="pim needs to be enabled on the interface")
537
538 existing_oif_prefix_source = existing.get("oif_prefix_source")
539 # not json serializable
540 existing.pop("oif_prefix_source")
541
542 if oif_routemap and existing_oif_prefix_source:
543 module.fail_json(
544 msg="Delete static-oif configurations on this "
545 "interface if you want to use a routemap",
546 )
547
548 if oif_ps and existing.get("oif_routemap"):
549 module.fail_json(
550 msg="Delete static-oif route-map configuration "
551 "on this interface if you want to config "
552 "static entries",
553 )
554
555 args = [
556 "version",
557 "startup_query_interval",
558 "startup_query_count",
559 "robustness",
560 "querier_timeout",
561 "query_mrt",
562 "query_interval",
563 "last_member_qrt",
564 "last_member_query_count",
565 "group_timeout",
566 "report_llg",
567 "immediate_leave",
568 "oif_routemap",
569 ]
570
571 changed = False
572 commands = []
573 proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args)
574
575 CANNOT_ABSENT = [
576 "version",
577 "startup_query_interval",
578 "startup_query_count",
579 "robustness",
580 "querier_timeout",
581 "query_mrt",
582 "query_interval",
583 "last_member_qrt",
584 "last_member_query_count",
585 "group_timeout",
586 "report_llg",
587 "immediate_leave",
588 ]
589
590 if state == "absent":
591 for each in CANNOT_ABSENT:
592 if each in proposed:
593 module.fail_json(
594 msg="only params: " "oif_ps, oif_routemap can be used when " "state=absent",
595 )
596
597 # delta check for all params except oif_ps
598 delta = dict(set(proposed.items()).difference(existing.items()))
599
600 if oif_ps:
601 if oif_ps == "default":
602 delta["oif_ps"] = []
603 else:
604 delta["oif_ps"] = oif_ps
605
606 if state == "present":
607 if delta:
608 command = config_igmp_interface(delta, existing, existing_oif_prefix_source)
609 if command:
610 commands.append(command)
611
612 elif state == "default":
613 command = config_default_igmp_interface(existing, delta)
614 if command:
615 commands.append(command)
616 elif state == "absent":
617 command = None
618 if existing.get("oif_routemap") or existing_oif_prefix_source:
619 command = config_remove_oif(existing, existing_oif_prefix_source)
620
621 if command:
622 commands.append(command)
623
624 command = config_default_igmp_interface(existing, delta)
625 if command:
626 commands.append(command)
627
628 cmds = []
629 results = {}
630 if commands:
631 commands.insert(0, ["interface {0}".format(interface)])
632 cmds = flatten_list(commands)
633
634 if module.check_mode:
635 module.exit_json(changed=True, commands=cmds)
636 else:
637 load_config(module, cmds)
638 changed = True
639 end_state = get_igmp_interface(module, interface)
640 if "configure" in cmds:
641 cmds.pop(0)
642
643 if module.params["restart"]:
644 cmd = {"command": "restart igmp", "output": "text"}
645 run_commands(module, cmd)
646
647 results["proposed"] = proposed
648 results["existing"] = existing_copy
649 results["updates"] = cmds
650 results["changed"] = changed
651 results["warnings"] = warnings
652 results["end_state"] = end_state
653
654 module.exit_json(**results)
655
656
657 if __name__ == "__main__":
658 main()