Debian Codegraph @

ansible_collections/community/grafana/plugins/callback/grafana_annotations.py

raw
1 # -*- coding: utf-8 -*-
2 # This file is part of Ansible
3 #
4 # Ansible is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # Ansible is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
16
17 from __future__ import absolute_import, division, print_function
18
19 __metaclass__ = type
20
21 DOCUMENTATION = """
22 name: grafana_annotations
23 type: notification
24 short_description: send ansible events as annotations on charts to grafana over http api.
25 author: "Rémi REY (@rrey)"
26 description:
27 - This callback will report start, failed and stats events to Grafana as annotations (https://grafana.com)
28 requirements:
29 - whitelisting in configuration
30 options:
31 grafana_url:
32 description: Grafana annotations api URL
33 required: true
34 env:
35 - name: GRAFANA_URL
36 ini:
37 - section: callback_grafana_annotations
38 key: grafana_url
39 type: string
40 validate_certs:
41 description: validate the SSL certificate of the Grafana server. (For HTTPS url)
42 env:
43 - name: GRAFANA_VALIDATE_CERT
44 ini:
45 - section: callback_grafana_annotations
46 key: validate_grafana_certs
47 - section: callback_grafana_annotations
48 key: validate_certs
49 default: true
50 type: bool
51 aliases: [ validate_grafana_certs ]
52 http_agent:
53 description: The HTTP 'User-agent' value to set in HTTP requets.
54 env:
55 - name: HTTP_AGENT
56 ini:
57 - section: callback_grafana_annotations
58 key: http_agent
59 default: 'Ansible (grafana_annotations callback)'
60 type: string
61 grafana_api_key:
62 description: Grafana API key, allowing to authenticate when posting on the HTTP API.
63 If not provided, grafana_login and grafana_password will
64 be required.
65 env:
66 - name: GRAFANA_API_KEY
67 ini:
68 - section: callback_grafana_annotations
69 key: grafana_api_key
70 type: string
71 grafana_user:
72 description: Grafana user used for authentication. Ignored if grafana_api_key is provided.
73 env:
74 - name: GRAFANA_USER
75 ini:
76 - section: callback_grafana_annotations
77 key: grafana_user
78 default: ansible
79 type: string
80 grafana_password:
81 description: Grafana password used for authentication. Ignored if grafana_api_key is provided.
82 env:
83 - name: GRAFANA_PASSWORD
84 ini:
85 - section: callback_grafana_annotations
86 key: grafana_password
87 default: ansible
88 type: string
89 grafana_dashboard_id:
90 description: The grafana dashboard id where the annotation shall be created.
91 env:
92 - name: GRAFANA_DASHBOARD_ID
93 ini:
94 - section: callback_grafana_annotations
95 key: grafana_dashboard_id
96 type: integer
97 grafana_panel_ids:
98 description: The grafana panel ids where the annotation shall be created.
99 Give a single integer or a comma-separated list of integers.
100 env:
101 - name: GRAFANA_PANEL_IDS
102 ini:
103 - section: callback_grafana_annotations
104 key: grafana_panel_ids
105 default: []
106 type: list
107 elements: integer
108 """
109
110 import json
111 import socket
112 import getpass
113 from datetime import datetime
114
115 from ansible.module_utils._text import to_text
116 from ansible.module_utils.urls import open_url
117 from ansible.plugins.callback import CallbackBase
118
119
120 PLAYBOOK_START_TXT = """\
121 Started playbook {playbook}
122
123 From '{hostname}'
124 By user '{username}'
125 """
126
127 PLAYBOOK_ERROR_TXT = """\
128 Playbook {playbook} Failure !
129
130 From '{hostname}'
131 By user '{username}'
132
133 '{task}' failed on {host}
134
135 debug: {result}
136 """
137
138 PLAYBOOK_STATS_TXT = """\
139 Playbook {playbook}
140 Duration: {duration}
141 Status: {status}
142
143 From '{hostname}'
144 By user '{username}'
145
146 Result:
147 {summary}
148 """
149
150
151 def to_millis(dt):
152 return int(dt.strftime("%s")) * 1000
153
154
155 class CallbackModule(CallbackBase):
156 """
157 ansible grafana callback plugin
158 ansible.cfg:
159 callback_plugins = <path_to_callback_plugins_folder>
160 callback_whitelist = grafana_annotations
161 and put the plugin in <path_to_callback_plugins_folder>
162 """
163
164 CALLBACK_VERSION = 2.0
165 CALLBACK_TYPE = "aggregate"
166 CALLBACK_NAME = "community.grafana.grafana_annotations"
167 CALLBACK_NEEDS_WHITELIST = True
168
169 def __init__(self, display=None):
170 super(CallbackModule, self).__init__(display=display)
171
172 self.headers = {"Content-Type": "application/json"}
173 self.force_basic_auth = False
174 self.hostname = socket.gethostname()
175 self.username = getpass.getuser()
176 self.start_time = datetime.now()
177 self.errors = 0
178
179 def set_options(self, task_keys=None, var_options=None, direct=None):
180 super(CallbackModule, self).set_options(
181 task_keys=task_keys, var_options=var_options, direct=direct
182 )
183
184 self.grafana_api_key = self.get_option("grafana_api_key")
185 self.grafana_url = self.get_option("grafana_url")
186 self.validate_grafana_certs = self.get_option("validate_certs")
187 self.http_agent = self.get_option("http_agent")
188 self.grafana_user = self.get_option("grafana_user")
189 self.grafana_password = self.get_option("grafana_password")
190 self.dashboard_id = self.get_option("grafana_dashboard_id")
191 self.panel_ids = self.get_option("grafana_panel_ids")
192
193 if self.grafana_api_key:
194 self.headers["Authorization"] = "Bearer %s" % self.grafana_api_key
195 else:
196 self.force_basic_auth = True
197
198 if self.grafana_url is None:
199 self.disabled = True
200 self._display.warning(
201 "Grafana URL was not provided. The "
202 "Grafana URL can be provided using "
203 "the `GRAFANA_URL` environment variable."
204 )
205 self._display.debug("Grafana URL: %s" % self.grafana_url)
206
207 def v2_playbook_on_start(self, playbook):
208 self.playbook = playbook._file_name
209 text = PLAYBOOK_START_TXT.format(
210 playbook=self.playbook, hostname=self.hostname, username=self.username
211 )
212 data = {
213 "time": to_millis(self.start_time),
214 "text": text,
215 "tags": ["ansible", "ansible_event_start", self.playbook, self.hostname],
216 }
217 self._send_annotation(data)
218
219 def v2_playbook_on_stats(self, stats):
220 end_time = datetime.now()
221 duration = end_time - self.start_time
222 summarize_stat = {}
223 for host in stats.processed.keys():
224 summarize_stat[host] = stats.summarize(host)
225
226 status = "FAILED"
227 if self.errors == 0:
228 status = "OK"
229
230 text = PLAYBOOK_STATS_TXT.format(
231 playbook=self.playbook,
232 hostname=self.hostname,
233 duration=duration.total_seconds(),
234 status=status,
235 username=self.username,
236 summary=json.dumps(summarize_stat),
237 )
238
239 data = {
240 "time": to_millis(self.start_time),
241 "timeEnd": to_millis(end_time),
242 "isRegion": True,
243 "text": text,
244 "tags": ["ansible", "ansible_report", self.playbook, self.hostname],
245 }
246 self._send_annotations(data)
247
248 def v2_runner_on_failed(self, result, ignore_errors=False, **kwargs):
249 text = PLAYBOOK_ERROR_TXT.format(
250 playbook=self.playbook,
251 hostname=self.hostname,
252 username=self.username,
253 task=result._task,
254 host=result._host.name,
255 result=self._dump_results(result._result),
256 )
257 if ignore_errors:
258 return
259 data = {
260 "time": to_millis(datetime.now()),
261 "text": text,
262 "tags": ["ansible", "ansible_event_failure", self.playbook, self.hostname],
263 }
264 self.errors += 1
265 self._send_annotations(data)
266
267 def _send_annotations(self, data):
268 if self.dashboard_id:
269 data["dashboardId"] = int(self.dashboard_id)
270 if self.panel_ids:
271 for panel_id in self.panel_ids:
272 data["panelId"] = int(panel_id)
273 self._send_annotation(data)
274 else:
275 self._send_annotation(data)
276
277 def _send_annotation(self, annotation):
278 try:
279 open_url(
280 self.grafana_url,
281 data=json.dumps(annotation),
282 headers=self.headers,
283 method="POST",
284 validate_certs=self.validate_grafana_certs,
285 url_username=self.grafana_user,
286 url_password=self.grafana_password,
287 http_agent=self.http_agent,
288 force_basic_auth=self.force_basic_auth,
289 )
290 except Exception as e:
291 self._display.error("Could not submit message to Grafana: %s" % to_text(e))