Debian Codegraph @

ansible_collections/cisco/nxos/plugins/modules/nxos_ping.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_ping
26 extends_documentation_fragment:
27 - cisco.nxos.nxos
28 short_description: Tests reachability using ping from Nexus switch.
29 description:
30 - Tests reachability using ping from switch to a remote destination.
31 - For a general purpose network module, see the M(ansible.netcommon.net_ping) module.
32 - For Windows targets, use the M(ansible.windows.win_ping) module instead.
33 - For targets running Python, use the M(ansible.builtin.ping) module instead.
34 version_added: 1.0.0
35 author:
36 - Jason Edelman (@jedelman8)
37 - Gabriele Gerbino (@GGabriele)
38 options:
39 dest:
40 description:
41 - IP address or hostname (resolvable by switch) of remote node.
42 required: true
43 type: str
44 count:
45 description:
46 - Number of packets to send.
47 default: 5
48 type: int
49 source:
50 description:
51 - Source IP Address or hostname (resolvable by switch)
52 type: str
53 vrf:
54 description:
55 - Outgoing VRF.
56 type: str
57 df_bit:
58 description:
59 - Set the DF bit.
60 default: false
61 type: bool
62 size:
63 description:
64 - Size of packets to send.
65 type: int
66 state:
67 description:
68 - Determines if the expected result is success or fail.
69 choices:
70 - absent
71 - present
72 default: present
73 type: str
74 notes:
75 - Unsupported for Cisco MDS
76 - For a general purpose network module, see the M(ansible.netcommon.net_ping) module.
77 - For Windows targets, use the M(ansible.windows.win_ping) module instead.
78 - For targets running Python, use the M(ansible.builtin.ping) module instead.
79 """
80
81 EXAMPLES = """
82 - name: Test reachability to 8.8.8.8 using mgmt vrf
83 cisco.nxos.nxos_ping:
84 dest: 8.8.8.8
85 vrf: management
86 host: 68.170.147.165
87
88 - name: Test reachability to a few different public IPs using mgmt vrf
89 cisco.nxos.nxos_ping:
90 dest: "{{ item }}"
91 vrf: management
92 host: 68.170.147.165
93 with_items:
94 - 8.8.8.8
95 - 4.4.4.4
96 - 198.6.1.4
97
98 - name: Test reachability to 8.8.8.8 using mgmt vrf, size and df-bit
99 cisco.nxos.nxos_ping:
100 dest: 8.8.8.8
101 df_bit: true
102 size: 1400
103 vrf: management
104 """
105
106 RETURN = """
107 commands:
108 description: Show the command sent
109 returned: always
110 type: list
111 sample: ["ping 8.8.8.8 count 2 vrf management"]
112 rtt:
113 description: Show RTT stats
114 returned: always
115 type: dict
116 sample: {"avg": 6.264, "max": 6.564, "min": 5.978}
117 packets_rx:
118 description: Packets successfully received
119 returned: always
120 type: int
121 sample: 2
122 packets_tx:
123 description: Packets successfully transmitted
124 returned: always
125 type: int
126 sample: 2
127 packet_loss:
128 description: Percentage of packets lost
129 returned: always
130 type: str
131 sample: "0.00%"
132 """
133 from ansible.module_utils.basic import AnsibleModule
134
135 from ansible_collections.cisco.nxos.plugins.module_utils.network.nxos.nxos import run_commands
136
137
138 def get_summary(results_list, reference_point):
139 summary_string = results_list[reference_point + 1]
140 summary_list = summary_string.split(",")
141
142 summary = dict(
143 packets_tx=int(summary_list[0].split("packets")[0].strip()),
144 packets_rx=int(summary_list[1].split("packets")[0].strip()),
145 packet_loss=summary_list[2].split("packet")[0].strip(),
146 )
147
148 if "bytes from" not in results_list[reference_point - 2]:
149 ping_pass = False
150 else:
151 ping_pass = True
152
153 return summary, ping_pass
154
155
156 def get_rtt(results_list, packet_loss, location):
157 rtt = dict(min=None, avg=None, max=None)
158
159 if packet_loss != "100.00%":
160 rtt_string = results_list[location]
161 base = rtt_string.split("=")[1]
162 rtt_list = base.split("/")
163
164 rtt["min"] = float(rtt_list[0].lstrip())
165 rtt["avg"] = float(rtt_list[1])
166 rtt["max"] = float(rtt_list[2][:-3])
167
168 return rtt
169
170
171 def get_statistics_summary_line(response_as_list):
172 for each in response_as_list:
173 if "---" in each:
174 index = response_as_list.index(each)
175 return index
176
177
178 def get_ping_results(command, module):
179 cmd = {"command": command, "output": "text"}
180 ping = run_commands(module, [cmd])[0]
181
182 summary, rtt, ping_pass = None, None, None
183
184 if not ping:
185 module.fail_json(
186 msg="An unexpected error occurred. Check all params.",
187 command=command,
188 destination=module.params["dest"],
189 vrf=module.params["vrf"],
190 source=module.params["source"],
191 size=module.params["size"],
192 df_bit=module.params["df_bit"],
193 )
194
195 elif "can't bind to address" in ping:
196 module.fail_json(msg="Can't bind to source address.", command=command)
197 elif "bad context" in ping:
198 module.fail_json(
199 msg="Wrong VRF name inserted.",
200 command=command,
201 vrf=module.params["vrf"],
202 )
203 else:
204 splitted_ping = ping.split("\n")
205 reference_point = get_statistics_summary_line(splitted_ping)
206 summary, ping_pass = get_summary(splitted_ping, reference_point)
207 rtt = get_rtt(splitted_ping, summary["packet_loss"], reference_point + 2)
208
209 return (summary, rtt, ping_pass)
210
211
212 def main():
213 argument_spec = dict(
214 dest=dict(required=True),
215 count=dict(required=False, default=5, type="int"),
216 vrf=dict(required=False),
217 source=dict(required=False),
218 size=dict(required=False, type="int"),
219 df_bit=dict(required=False, default=False, type="bool"),
220 state=dict(required=False, choices=["present", "absent"], default="present"),
221 )
222
223 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
224
225 destination = module.params["dest"]
226 state = module.params["state"]
227 size = module.params["size"]
228 df_bit = module.params["df_bit"]
229
230 ping_command = "ping {0}".format(destination)
231 for command in ["count", "source", "vrf"]:
232 arg = module.params[command]
233 if arg:
234 ping_command += " {0} {1}".format(command, arg)
235
236 if size:
237 ping_command += " packet-size {0}".format(size)
238
239 if df_bit:
240 ping_command += " df-bit"
241
242 summary, rtt, ping_pass = get_ping_results(ping_command, module)
243
244 results = summary
245 results["rtt"] = rtt
246 results["commands"] = [ping_command]
247
248 if ping_pass and state == "absent":
249 module.fail_json(msg="Ping succeeded unexpectedly")
250 elif not ping_pass and state == "present":
251 module.fail_json(msg="Ping failed unexpectedly")
252
253 module.exit_json(**results)
254
255
256 if __name__ == "__main__":
257 main()