| 1 |
# Copyright (c) 2018, Samir Musali <[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 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
author: Unknown (!UNKNOWN) |
| 9 |
name: logdna |
| 10 |
type: notification |
| 11 |
short_description: Sends playbook logs to LogDNA |
| 12 |
description: |
| 13 |
- This callback reports logs from playbook actions, tasks, and events to LogDNA (U(https://app.logdna.com)). |
| 14 |
requirements: |
| 15 |
- LogDNA Python Library (U(https://github.com/logdna/python)) |
| 16 |
- whitelisting in configuration |
| 17 |
options: |
| 18 |
conf_key: |
| 19 |
required: true |
| 20 |
description: LogDNA Ingestion Key. |
| 21 |
type: string |
| 22 |
env: |
| 23 |
- name: LOGDNA_INGESTION_KEY |
| 24 |
ini: |
| 25 |
- section: callback_logdna |
| 26 |
key: conf_key |
| 27 |
plugin_ignore_errors: |
| 28 |
required: false |
| 29 |
description: Whether to ignore errors on failing or not. |
| 30 |
type: boolean |
| 31 |
env: |
| 32 |
- name: ANSIBLE_IGNORE_ERRORS |
| 33 |
ini: |
| 34 |
- section: callback_logdna |
| 35 |
key: plugin_ignore_errors |
| 36 |
default: false |
| 37 |
conf_hostname: |
| 38 |
required: false |
| 39 |
description: Alternative Host Name; the current host name by default. |
| 40 |
type: string |
| 41 |
env: |
| 42 |
- name: LOGDNA_HOSTNAME |
| 43 |
ini: |
| 44 |
- section: callback_logdna |
| 45 |
key: conf_hostname |
| 46 |
conf_tags: |
| 47 |
required: false |
| 48 |
description: Tags. |
| 49 |
type: string |
| 50 |
env: |
| 51 |
- name: LOGDNA_TAGS |
| 52 |
ini: |
| 53 |
- section: callback_logdna |
| 54 |
key: conf_tags |
| 55 |
default: ansible |
| 56 |
""" |
| 57 |
|
| 58 |
import json |
| 59 |
import logging |
| 60 |
import socket |
| 61 |
from uuid import getnode |
| 62 |
|
| 63 |
from ansible.parsing.ajson import AnsibleJSONEncoder |
| 64 |
from ansible.plugins.callback import CallbackBase |
| 65 |
|
| 66 |
try: |
| 67 |
from logdna import LogDNAHandler |
| 68 |
|
| 69 |
HAS_LOGDNA = True |
| 70 |
except ImportError: |
| 71 |
HAS_LOGDNA = False |
| 72 |
|
| 73 |
|
| 74 |
# Getting MAC Address of system: |
| 75 |
def get_mac(): |
| 76 |
mac = f"{getnode():012x}" |
| 77 |
return ":".join(map(lambda index: mac[index : index + 2], range(int(len(mac) / 2)))) |
| 78 |
|
| 79 |
|
| 80 |
# Getting hostname of system: |
| 81 |
def get_hostname(): |
| 82 |
return str(socket.gethostname()).split(".local", 1)[0] |
| 83 |
|
| 84 |
|
| 85 |
# Getting IP of system: |
| 86 |
def get_ip(): |
| 87 |
try: |
| 88 |
return socket.gethostbyname(get_hostname()) |
| 89 |
except Exception: |
| 90 |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 91 |
try: |
| 92 |
s.connect(("10.255.255.255", 1)) |
| 93 |
IP = s.getsockname()[0] |
| 94 |
except Exception: |
| 95 |
IP = "127.0.0.1" |
| 96 |
finally: |
| 97 |
s.close() |
| 98 |
return IP |
| 99 |
|
| 100 |
|
| 101 |
# Is it JSON? |
| 102 |
def isJSONable(obj): |
| 103 |
try: |
| 104 |
json.dumps(obj, sort_keys=True, cls=AnsibleJSONEncoder) |
| 105 |
return True |
| 106 |
except Exception: |
| 107 |
return False |
| 108 |
|
| 109 |
|
| 110 |
# LogDNA Callback Module: |
| 111 |
class CallbackModule(CallbackBase): |
| 112 |
CALLBACK_VERSION = 0.1 |
| 113 |
CALLBACK_TYPE = "notification" |
| 114 |
CALLBACK_NAME = "community.general.logdna" |
| 115 |
CALLBACK_NEEDS_WHITELIST = True |
| 116 |
|
| 117 |
def __init__(self, display=None): |
| 118 |
super().__init__(display=display) |
| 119 |
|
| 120 |
self.disabled = True |
| 121 |
self.playbook_name = None |
| 122 |
self.playbook = None |
| 123 |
self.conf_key = None |
| 124 |
self.plugin_ignore_errors = None |
| 125 |
self.conf_hostname = None |
| 126 |
self.conf_tags = None |
| 127 |
|
| 128 |
def set_options(self, task_keys=None, var_options=None, direct=None): |
| 129 |
super().set_options(task_keys=task_keys, var_options=var_options, direct=direct) |
| 130 |
|
| 131 |
self.conf_key = self.get_option("conf_key") |
| 132 |
self.plugin_ignore_errors = self.get_option("plugin_ignore_errors") |
| 133 |
self.conf_hostname = self.get_option("conf_hostname") |
| 134 |
self.conf_tags = self.get_option("conf_tags") |
| 135 |
self.mac = get_mac() |
| 136 |
self.ip = get_ip() |
| 137 |
|
| 138 |
if self.conf_hostname is None: |
| 139 |
self.conf_hostname = get_hostname() |
| 140 |
|
| 141 |
self.conf_tags = self.conf_tags.split(",") |
| 142 |
|
| 143 |
if HAS_LOGDNA: |
| 144 |
self.log = logging.getLogger("logdna") |
| 145 |
self.log.setLevel(logging.INFO) |
| 146 |
self.options = {"hostname": self.conf_hostname, "mac": self.mac, "index_meta": True} |
| 147 |
self.log.addHandler(LogDNAHandler(self.conf_key, self.options)) |
| 148 |
self.disabled = False |
| 149 |
else: |
| 150 |
self.disabled = True |
| 151 |
self._display.warning("WARNING:\nPlease, install LogDNA Python Package: `pip install logdna`") |
| 152 |
|
| 153 |
def metaIndexing(self, meta): |
| 154 |
invalidKeys = [] |
| 155 |
ninvalidKeys = 0 |
| 156 |
for key, value in meta.items(): |
| 157 |
if not isJSONable(value): |
| 158 |
invalidKeys.append(key) |
| 159 |
ninvalidKeys += 1 |
| 160 |
if ninvalidKeys > 0: |
| 161 |
for key in invalidKeys: |
| 162 |
del meta[key] |
| 163 |
meta["__errors"] = f"These keys have been sanitized: {', '.join(invalidKeys)}" |
| 164 |
return meta |
| 165 |
|
| 166 |
def sanitizeJSON(self, data): |
| 167 |
try: |
| 168 |
return json.loads(json.dumps(data, sort_keys=True, cls=AnsibleJSONEncoder)) |
| 169 |
except Exception: |
| 170 |
return {"warnings": ["JSON Formatting Issue", json.dumps(data, sort_keys=True, cls=AnsibleJSONEncoder)]} |
| 171 |
|
| 172 |
def flush(self, log, options): |
| 173 |
if HAS_LOGDNA: |
| 174 |
self.log.info(json.dumps(log), options) |
| 175 |
|
| 176 |
def sendLog(self, host, category, logdata): |
| 177 |
options = {"app": "ansible", "meta": {"playbook": self.playbook_name, "host": host, "category": category}} |
| 178 |
logdata["info"].pop("invocation", None) |
| 179 |
warnings = logdata["info"].pop("warnings", None) |
| 180 |
if warnings is not None: |
| 181 |
self.flush({"warn": warnings}, options) |
| 182 |
self.flush(logdata, options) |
| 183 |
|
| 184 |
def v2_playbook_on_start(self, playbook): |
| 185 |
self.playbook = playbook |
| 186 |
self.playbook_name = playbook._file_name |
| 187 |
|
| 188 |
def v2_playbook_on_stats(self, stats): |
| 189 |
result = dict() |
| 190 |
for host in stats.processed.keys(): |
| 191 |
result[host] = stats.summarize(host) |
| 192 |
self.sendLog(self.conf_hostname, "STATS", {"info": self.sanitizeJSON(result)}) |
| 193 |
|
| 194 |
def runner_on_failed(self, host, res, ignore_errors=False): |
| 195 |
if self.plugin_ignore_errors: |
| 196 |
ignore_errors = self.plugin_ignore_errors |
| 197 |
self.sendLog(host, "FAILED", {"info": self.sanitizeJSON(res), "ignore_errors": ignore_errors}) |
| 198 |
|
| 199 |
def runner_on_ok(self, host, res): |
| 200 |
self.sendLog(host, "OK", {"info": self.sanitizeJSON(res)}) |
| 201 |
|
| 202 |
def runner_on_unreachable(self, host, res): |
| 203 |
self.sendLog(host, "UNREACHABLE", {"info": self.sanitizeJSON(res)}) |
| 204 |
|
| 205 |
def runner_on_async_failed(self, host, res, jid): |
| 206 |
self.sendLog(host, "ASYNC_FAILED", {"info": self.sanitizeJSON(res), "job_id": jid}) |
| 207 |
|
| 208 |
def runner_on_async_ok(self, host, res, jid): |
| 209 |
self.sendLog(host, "ASYNC_OK", {"info": self.sanitizeJSON(res), "job_id": jid}) |