Debian Codegraph @

ansible_collections/theforeman/foreman/plugins/callback/foreman.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # (c) 2015, 2016 Daniel Lobato <[email protected]>
3 # (c) 2016 Guido Günther <[email protected]>
4 # (c) 2017 Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 # pylint: disable=super-with-arguments
8
9 from __future__ import (absolute_import, division, print_function)
10 __metaclass__ = type
11
12 DOCUMENTATION = '''
13 name: foreman
14 type: notification
15 short_description: Sends events to Foreman
16 description:
17 - This callback will report facts and task events to Foreman
18 requirements:
19 - whitelisting in configuration
20 - requests (python library)
21 options:
22 report_type:
23 description:
24 - "endpoint type for reports: foreman or proxy"
25 env:
26 - name: FOREMAN_REPORT_TYPE
27 default: foreman
28 ini:
29 - section: callback_foreman
30 key: report_type
31 url:
32 description:
33 - URL of the Foreman server.
34 env:
35 - name: FOREMAN_URL
36 - name: FOREMAN_SERVER_URL
37 - name: FOREMAN_SERVER
38 required: true
39 ini:
40 - section: callback_foreman
41 key: url
42 proxy_url:
43 description:
44 - URL of the Foreman Smart Proxy server.
45 env:
46 - name: FOREMAN_PROXY_URL
47 ini:
48 - section: callback_foreman
49 key: proxy_url
50 client_cert:
51 description:
52 - X509 certificate to authenticate to Foreman if https is used
53 env:
54 - name: FOREMAN_SSL_CERT
55 default: /etc/foreman/client_cert.pem
56 ini:
57 - section: callback_foreman
58 key: ssl_cert
59 - section: callback_foreman
60 key: client_cert
61 aliases: [ ssl_cert ]
62 client_key:
63 description:
64 - the corresponding private key
65 env:
66 - name: FOREMAN_SSL_KEY
67 default: /etc/foreman/client_key.pem
68 ini:
69 - section: callback_foreman
70 key: ssl_key
71 - section: callback_foreman
72 key: client_key
73 aliases: [ ssl_key ]
74 verify_certs:
75 description:
76 - Toggle to decide whether to verify the Foreman certificate.
77 - It can be set to '1' to verify SSL certificates using the installed CAs or to a path pointing to a CA bundle.
78 - Set to '0' to disable certificate checking.
79 env:
80 - name: FOREMAN_SSL_VERIFY
81 default: 1
82 ini:
83 - section: callback_foreman
84 key: verify_certs
85 dir_store:
86 description:
87 - When set, callback does not perform HTTP calls but stores results in a given directory.
88 - For each report, new file in the form of SEQ_NO-hostname.json is created.
89 - For each facts, new file in the form of SEQ_NO-hostname.json is created.
90 - The value must be a valid directory.
91 - This is meant for debugging and testing purposes.
92 - When set to blank (default) this functionality is turned off.
93 env:
94 - name: FOREMAN_DIR_STORE
95 default: ''
96 ini:
97 - section: callback_foreman
98 key: dir_store
99 disable_callback:
100 description:
101 - Toggle to make the callback plugin disable itself even if it is loaded.
102 - It can be set to '1' to prevent the plugin from being used even if it gets loaded.
103 env:
104 - name: FOREMAN_CALLBACK_DISABLE
105 default: 0
106 '''
107
108 import os
109 from datetime import datetime
110 from collections import defaultdict
111 import json
112 import time
113
114 try:
115 import requests
116 HAS_REQUESTS = True
117 except ImportError:
118 HAS_REQUESTS = False
119
120 from ansible.module_utils.common.json import AnsibleJSONEncoder
121 from ansible.module_utils.common.text.converters import to_text
122 from ansible.module_utils.parsing.convert_bool import boolean as to_bool
123 from ansible.plugins.callback import CallbackBase
124
125
126 def build_log_foreman(data_list):
127 """
128 Transform the internal log structure to one accepted by Foreman's
129 config_report API.
130 """
131 for data in data_list:
132 result = data.pop('result')
133 task = data.pop('task')
134 result['failed'] = data.get('failed')
135 result['module'] = task.get('action')
136 if data.get('failed'):
137 level = 'err'
138 elif result.get('changed'):
139 level = 'notice'
140 else:
141 level = 'info'
142
143 yield {
144 "log": {
145 'sources': {
146 'source': task.get('name'),
147 },
148 'messages': {
149 'message': json.dumps(result, sort_keys=True, cls=AnsibleNoVaultJSONEncoder),
150 },
151 'level': level,
152 }
153 }
154
155
156 def get_time():
157 """
158 Return the time for measuring duration. Prefers monotonic time but
159 falls back to the regular time on older Python versions.
160 """
161 try:
162 return time.monotonic()
163 except AttributeError:
164 return time.time()
165
166
167 def get_now():
168 """
169 Return the current timestamp as a string to be sent over the network.
170 The time is always in UTC *with* timezone information, so that Ruby
171 DateTime can easily parse it.
172 """
173 return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S+00:00")
174
175
176 class AnsibleNoVaultJSONEncoder(AnsibleJSONEncoder):
177 def default(self, o):
178 if getattr(o, '__ENCRYPTED__', False):
179 value = 'ENCRYPTED_VAULT_VALUE_NOT_REPORTED'
180 else:
181 value = super(AnsibleNoVaultJSONEncoder, self).default(o)
182 return value
183
184
185 class CallbackModule(CallbackBase):
186 CALLBACK_VERSION = 2.0
187 CALLBACK_TYPE = 'notification'
188 CALLBACK_NAME = 'theforeman.foreman.foreman'
189 CALLBACK_NEEDS_WHITELIST = True
190
191 def __init__(self):
192 super(CallbackModule, self).__init__()
193 self.items = defaultdict(list)
194 self.facts = defaultdict(dict)
195 self.start_time = get_time()
196
197 def set_options(self, task_keys=None, var_options=None, direct=None):
198
199 super(CallbackModule, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
200
201 if self.get_option('disable_callback'):
202 self._disable_plugin('Callback disabled by environment.')
203
204 self.report_type = self.get_option('report_type')
205 self.foreman_url = self.get_option('url')
206 self.proxy_url = self.get_option('proxy_url')
207 ssl_cert = self.get_option('client_cert')
208 ssl_key = self.get_option('client_key')
209 self.dir_store = self.get_option('dir_store')
210
211 if not HAS_REQUESTS:
212 self._disable_plugin(u'The `requests` python module is not installed')
213
214 self.session = requests.Session()
215 if self.foreman_url.startswith('https://'):
216 if not os.path.exists(ssl_cert):
217 self._disable_plugin(u'FOREMAN_SSL_CERT %s not found.' % ssl_cert)
218
219 if not os.path.exists(ssl_key):
220 self._disable_plugin(u'FOREMAN_SSL_KEY %s not found.' % ssl_key)
221
222 self.session.verify = self._ssl_verify(str(self.get_option('verify_certs')))
223 self.session.cert = (ssl_cert, ssl_key)
224
225 def _disable_plugin(self, msg):
226 self.disabled = True
227 if msg:
228 self._display.warning(msg + u' Disabling the Foreman callback plugin.')
229 else:
230 self._display.warning(u'Disabling the Foreman callback plugin.')
231
232 def _ssl_verify(self, option):
233 try:
234 verify = to_bool(option)
235 except TypeError:
236 verify = option
237
238 if verify is False: # is only set to bool if try block succeeds
239 requests.packages.urllib3.disable_warnings()
240 self._display.warning(
241 u"SSL verification of %s disabled" % self.foreman_url,
242 )
243
244 return verify
245
246 def _send_data(self, data_type, report_type, host, data):
247 if data_type == 'facts':
248 url = self.foreman_url + '/api/v2/hosts/facts'
249 elif data_type == 'report' and report_type == 'foreman':
250 url = self.foreman_url + '/api/v2/config_reports'
251 elif data_type == 'report' and report_type == 'proxy':
252 url = self.proxy_url + '/reports/ansible'
253 else:
254 self._display.warning(u'Unknown report_type: {rt}'.format(rt=report_type))
255
256 json_data = json.dumps(data, indent=2, sort_keys=True, cls=AnsibleNoVaultJSONEncoder)
257
258 if len(self.dir_store) > 0:
259 filename = u'{host}-{dt}.json'.format(host=to_text(host), dt=data_type)
260 filename = os.path.join(self.dir_store, filename)
261 with open(filename, 'w') as f:
262 f.write(json_data)
263 else:
264 try:
265 headers = {'content-type': 'application/json'}
266 response = self.session.post(url=url, data=json_data, headers=headers)
267 response.raise_for_status()
268 except requests.exceptions.RequestException as err:
269 self._display.warning(u'Sending data to Foreman at {url} failed for {host}: {err}'.format(
270 host=to_text(host), err=to_text(err), url=to_text(self.foreman_url)))
271
272 def send_facts(self):
273 """
274 Sends facts to Foreman, to be parsed by foreman_ansible fact
275 parser. The default fact importer should import these facts
276 properly.
277 """
278 # proxy parses facts from report directly
279 if self.report_type == "proxy":
280 return
281
282 for host, facts in self.facts.items():
283 facts = {
284 "name": host,
285 "facts": {
286 "ansible_facts": facts,
287 "_type": "ansible",
288 "_timestamp": get_now(),
289 },
290 }
291
292 self._send_data('facts', 'foreman', host, facts)
293
294 def send_reports_proxy_host_report(self, stats):
295 """
296 Send reports to Foreman Smart Proxy running Host Reports
297 plugin. The format is native Ansible report without any
298 changes.
299 """
300 for host in stats.processed.keys():
301 report = {
302 "host": host,
303 "reported_at": get_now(),
304 "metrics": {
305 "time": {
306 "total": int(get_time() - self.start_time)
307 }
308 },
309 "summary": stats.summarize(host),
310 "results": self.items[host],
311 "check_mode": self.check_mode,
312 }
313
314 self._send_data('report', 'proxy', host, report)
315 self.items[host] = []
316
317 def send_reports_foreman(self, stats):
318 """
319 Send reports to Foreman to be parsed by its config report
320 importer. The data is in a format that Foreman can handle
321 without writing another report importer.
322 """
323 for host in stats.processed.keys():
324 total = stats.summarize(host)
325 report = {
326 "config_report": {
327 "host": host,
328 "reported_at": get_now(),
329 "metrics": {
330 "time": {
331 "total": int(get_time() - self.start_time)
332 }
333 },
334 "status": {
335 "applied": total['changed'],
336 "failed": total['failures'] + total['unreachable'],
337 "skipped": total['skipped'],
338 },
339 "logs": list(build_log_foreman(self.items[host])),
340 "reporter": "ansible",
341 "check_mode": self.check_mode,
342 }
343 }
344 if self.check_mode:
345 report['config_report']['status']['pending'] = total['changed']
346 report['config_report']['status']['applied'] = 0
347
348 self._send_data('report', 'foreman', host, report)
349 self.items[host] = []
350
351 def send_reports(self, stats):
352 if self.report_type == "foreman":
353 self.send_reports_foreman(stats)
354 elif self.report_type == "proxy":
355 self.send_reports_proxy_host_report(stats)
356 else:
357 self._display.warning(u'Unknown foreman endpoint type: {type}'.format(type=self.report_type))
358
359 def drop_nones(self, d):
360 """Recursively drop Nones or empty dicts/arrays in dict d and return a new dict"""
361 dd = {}
362 for k, v in d.items():
363 if isinstance(v, dict) and v:
364 dd[k] = self.drop_nones(v)
365 elif isinstance(v, list) and len(v) == 1 and v[0] == {}:
366 pass
367 elif isinstance(v, (list, set, tuple)) and v:
368 dd[k] = type(v)(self.drop_nones(vv) if isinstance(vv, dict) else vv
369 for vv in v)
370 elif not isinstance(v, (dict, list, set, tuple)) and v is not None:
371 dd[k] = v
372 return dd
373
374 def append_result(self, result, failed=False):
375 result_info = result._result
376 if hasattr(result._task, 'serialize'):
377 task_info = result._task.serialize()
378 else:
379 task_info = result._task.dump_attrs()
380 task_info['args'] = None
381 value = {}
382 value['result'] = result_info
383 value['task'] = task_info
384 value['failed'] = failed
385 if self.report_type == "proxy":
386 value = self.drop_nones(value)
387 host = result._host.get_name()
388 self.items[host].append(value)
389 self.check_mode = result._task.check_mode
390 if 'ansible_facts' in result_info:
391 self.facts[host].update(result_info['ansible_facts'])
392
393 # Ansible callback API
394 def v2_runner_on_failed(self, result, ignore_errors=False):
395 self.append_result(result, True)
396
397 def v2_runner_on_unreachable(self, result):
398 self.append_result(result, True)
399
400 def v2_runner_on_async_ok(self, result):
401 self.append_result(result)
402
403 def v2_runner_on_async_failed(self, result):
404 self.append_result(result, True)
405
406 def v2_playbook_on_stats(self, stats):
407 self.send_facts()
408 self.send_reports(stats)
409
410 def v2_runner_on_ok(self, result):
411 self.append_result(result)