Debian Codegraph @

ansible_collections/community/general/plugins/callback/nrdp.py

raw
1 # Copyright (c) 2018 Remi Verchere <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Make coding more python3-ish
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 name: nrdp
10 type: notification
11 author: "Remi VERCHERE (@rverchere)"
12 short_description: Post task results to a Nagios server through nrdp
13 description:
14 - This callback send playbook result to Nagios.
15 - Nagios shall use NRDP to receive passive events.
16 - The passive check is sent to a dedicated host/service for Ansible.
17 options:
18 url:
19 description: URL of the nrdp server.
20 required: true
21 env:
22 - name: NRDP_URL
23 ini:
24 - section: callback_nrdp
25 key: url
26 type: string
27 validate_certs:
28 description: Validate the SSL certificate of the nrdp server. (Used for HTTPS URLs).
29 env:
30 - name: NRDP_VALIDATE_CERTS
31 ini:
32 - section: callback_nrdp
33 key: validate_nrdp_certs
34 - section: callback_nrdp
35 key: validate_certs
36 type: boolean
37 default: false
38 aliases: [validate_nrdp_certs]
39 token:
40 description: Token to be allowed to push nrdp events.
41 required: true
42 env:
43 - name: NRDP_TOKEN
44 ini:
45 - section: callback_nrdp
46 key: token
47 type: string
48 hostname:
49 description: Hostname where the passive check is linked to.
50 required: true
51 env:
52 - name: NRDP_HOSTNAME
53 ini:
54 - section: callback_nrdp
55 key: hostname
56 type: string
57 servicename:
58 description: Service where the passive check is linked to.
59 required: true
60 env:
61 - name: NRDP_SERVICENAME
62 ini:
63 - section: callback_nrdp
64 key: servicename
65 type: string
66 """
67
68 from urllib.parse import urlencode
69
70 from ansible.module_utils.common.text.converters import to_bytes
71 from ansible.module_utils.urls import open_url
72 from ansible.plugins.callback import CallbackBase
73
74
75 class CallbackModule(CallbackBase):
76 """
77 send ansible-playbook to Nagios server using nrdp protocol
78 """
79
80 CALLBACK_VERSION = 2.0
81 CALLBACK_TYPE = "notification"
82 CALLBACK_NAME = "community.general.nrdp"
83 CALLBACK_NEEDS_WHITELIST = True
84
85 # Nagios states
86 OK = 0
87 WARNING = 1
88 CRITICAL = 2
89 UNKNOWN = 3
90
91 def __init__(self):
92 super().__init__()
93
94 self.printed_playbook = False
95 self.playbook_name = None
96 self.play = None
97
98 def set_options(self, task_keys=None, var_options=None, direct=None):
99 super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
100
101 self.url = self.get_option("url")
102 if not self.url.endswith("/"):
103 self.url += "/"
104 self.token = self.get_option("token")
105 self.hostname = self.get_option("hostname")
106 self.servicename = self.get_option("servicename")
107 self.validate_nrdp_certs = self.get_option("validate_certs")
108
109 if (self.url or self.token or self.hostname or self.servicename) is None:
110 self._display.warning(
111 "NRDP callback wants the NRDP_URL,"
112 " NRDP_TOKEN, NRDP_HOSTNAME,"
113 " NRDP_SERVICENAME"
114 " environment variables'."
115 " The NRDP callback plugin is disabled."
116 )
117 self.disabled = True
118
119 def _send_nrdp(self, state, msg):
120 """
121 nrpd service check send XMLDATA like this:
122 <?xml version='1.0'?>
123 <checkresults>
124 <checkresult type='service'>
125 <hostname>somehost</hostname>
126 <servicename>someservice</servicename>
127 <state>1</state>
128 <output>WARNING: Danger Will Robinson!|perfdata</output>
129 </checkresult>
130 </checkresults>
131 """
132 xmldata = "<?xml version='1.0'?>\n"
133 xmldata += "<checkresults>\n"
134 xmldata += "<checkresult type='service'>\n"
135 xmldata += f"<hostname>{self.hostname}</hostname>\n"
136 xmldata += f"<servicename>{self.servicename}</servicename>\n"
137 xmldata += f"<state>{state}</state>\n"
138 xmldata += f"<output>{msg}</output>\n"
139 xmldata += "</checkresult>\n"
140 xmldata += "</checkresults>\n"
141
142 body = {"cmd": "submitcheck", "token": self.token, "XMLDATA": to_bytes(xmldata)}
143
144 try:
145 response = open_url(self.url, data=urlencode(body), method="POST", validate_certs=self.validate_nrdp_certs)
146 return response.read()
147 except Exception as ex:
148 self._display.warning(f"NRDP callback cannot send result {ex}")
149
150 def v2_playbook_on_play_start(self, play):
151 """
152 Display Playbook and play start messages
153 """
154 self.play = play
155
156 def v2_playbook_on_stats(self, stats):
157 """
158 Display info about playbook statistics
159 """
160 name = self.play
161 gstats = ""
162 hosts = sorted(stats.processed.keys())
163 critical = warning = 0
164 for host in hosts:
165 stat = stats.summarize(host)
166 gstats += (
167 f"'{host}_ok'={stat['ok']} '{host}_changed'={stat['changed']}"
168 f" '{host}_unreachable'={stat['unreachable']} '{host}_failed'={stat['failures']} "
169 )
170 # Critical when failed tasks or unreachable host
171 critical += stat["failures"]
172 critical += stat["unreachable"]
173 # Warning when changed tasks
174 warning += stat["changed"]
175
176 msg = f"{name} | {gstats}"
177 if critical:
178 # Send Critical
179 self._send_nrdp(self.CRITICAL, msg)
180 elif warning:
181 # Send Warning
182 self._send_nrdp(self.WARNING, msg)
183 else:
184 # Send OK
185 self._send_nrdp(self.OK, msg)