Debian Codegraph @

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

raw
1 # Copyright (c) 2015, Logentries.com, Jimmy Tang <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 author: Unknown (!UNKNOWN)
9 name: logentries
10 type: notification
11 short_description: Sends events to Logentries
12 description:
13 - This callback plugin generates JSON objects and send them to Logentries using TCP for auditing/debugging purposes.
14 requirements:
15 - whitelisting in configuration
16 - certifi (Python library)
17 - flatdict (Python library), if you want to use the O(flatten) option
18 options:
19 api:
20 description: URI to the Logentries API.
21 type: str
22 env:
23 - name: LOGENTRIES_API
24 default: data.logentries.com
25 ini:
26 - section: callback_logentries
27 key: api
28 port:
29 description: HTTP port to use when connecting to the API.
30 type: int
31 env:
32 - name: LOGENTRIES_PORT
33 default: 80
34 ini:
35 - section: callback_logentries
36 key: port
37 tls_port:
38 description: Port to use when connecting to the API when TLS is enabled.
39 type: int
40 env:
41 - name: LOGENTRIES_TLS_PORT
42 default: 443
43 ini:
44 - section: callback_logentries
45 key: tls_port
46 token:
47 description: The logentries C(TCP token).
48 type: str
49 env:
50 - name: LOGENTRIES_ANSIBLE_TOKEN
51 required: true
52 ini:
53 - section: callback_logentries
54 key: token
55 use_tls:
56 description:
57 - Toggle to decide whether to use TLS to encrypt the communications with the API server.
58 env:
59 - name: LOGENTRIES_USE_TLS
60 default: false
61 type: boolean
62 ini:
63 - section: callback_logentries
64 key: use_tls
65 flatten:
66 description: Flatten complex data structures into a single dictionary with complex keys.
67 type: boolean
68 default: false
69 env:
70 - name: LOGENTRIES_FLATTEN
71 ini:
72 - section: callback_logentries
73 key: flatten
74 """
75
76 EXAMPLES = r"""
77 examples: >-
78 To enable, add this to your ansible.cfg file in the defaults block
79
80 [defaults]
81 callback_whitelist = community.general.logentries
82
83 Either set the environment variables
84 export LOGENTRIES_API=data.logentries.com
85 export LOGENTRIES_PORT=10000
86 export LOGENTRIES_ANSIBLE_TOKEN=dd21fc88-f00a-43ff-b977-e3a4233c53af
87
88 Or in the main Ansible config file
89 [callback_logentries]
90 api = data.logentries.com
91 port = 10000
92 tls_port = 20000
93 use_tls = true
94 token = dd21fc88-f00a-43ff-b977-e3a4233c53af
95 flatten = false
96 """
97
98 import os
99 import random
100 import socket
101 import time
102 import uuid
103
104 try:
105 import certifi
106
107 HAS_CERTIFI = True
108 except ImportError:
109 HAS_CERTIFI = False
110
111 try:
112 import flatdict
113
114 HAS_FLATDICT = True
115 except ImportError:
116 HAS_FLATDICT = False
117
118 from ansible.module_utils.common.text.converters import to_bytes, to_text
119 from ansible.plugins.callback import CallbackBase
120
121 # Todo:
122 # * Better formatting of output before sending out to logentries data/api nodes.
123
124
125 class PlainTextSocketAppender:
126 def __init__(self, display, LE_API="data.logentries.com", LE_PORT=80, LE_TLS_PORT=443):
127 self.LE_API = LE_API
128 self.LE_PORT = LE_PORT
129 self.LE_TLS_PORT = LE_TLS_PORT
130 self.MIN_DELAY = 0.1
131 self.MAX_DELAY = 10
132 # Error message displayed when an incorrect Token has been detected
133 self.INVALID_TOKEN = "\n\nIt appears the LOGENTRIES_TOKEN parameter you entered is incorrect!\n\n"
134 # Unicode Line separator character \u2028
135 self.LINE_SEP = "\u2028"
136
137 self._display = display
138 self._conn = None
139
140 def open_connection(self):
141 self._conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
142 self._conn.connect((self.LE_API, self.LE_PORT))
143
144 def reopen_connection(self):
145 self.close_connection()
146
147 root_delay = self.MIN_DELAY
148 while True:
149 try:
150 self.open_connection()
151 return
152 except Exception as e:
153 self._display.vvvv(f"Unable to connect to Logentries: {e}")
154
155 root_delay *= 2
156 if root_delay > self.MAX_DELAY:
157 root_delay = self.MAX_DELAY
158
159 wait_for = root_delay + random.uniform(0, root_delay)
160
161 try:
162 self._display.vvvv(f"sleeping {wait_for} before retry")
163 time.sleep(wait_for)
164 except KeyboardInterrupt:
165 raise
166
167 def close_connection(self):
168 if self._conn is not None:
169 self._conn.close()
170
171 def put(self, data):
172 # Replace newlines with Unicode line separator
173 # for multi-line events
174 data = to_text(data, errors="surrogate_or_strict")
175 multiline = data.replace("\n", self.LINE_SEP)
176 multiline += "\n"
177 # Send data, reconnect if needed
178 while True:
179 try:
180 self._conn.send(to_bytes(multiline, errors="surrogate_or_strict"))
181 except OSError:
182 self.reopen_connection()
183 continue
184 break
185
186 self.close_connection()
187
188
189 try:
190 import ssl
191
192 HAS_SSL = True
193 except ImportError: # for systems without TLS support.
194 SocketAppender = PlainTextSocketAppender
195 HAS_SSL = False
196 else:
197
198 class TLSSocketAppender(PlainTextSocketAppender):
199 def open_connection(self):
200 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
201 context = ssl.create_default_context(
202 purpose=ssl.Purpose.SERVER_AUTH,
203 cafile=certifi.where(),
204 )
205 sock = context.wrap_socket(
206 sock=sock,
207 do_handshake_on_connect=True,
208 suppress_ragged_eofs=True,
209 )
210 sock.connect((self.LE_API, self.LE_TLS_PORT))
211 self._conn = sock
212
213 SocketAppender = TLSSocketAppender # type: ignore
214
215
216 class CallbackModule(CallbackBase):
217 CALLBACK_VERSION = 2.0
218 CALLBACK_TYPE = "notification"
219 CALLBACK_NAME = "community.general.logentries"
220 CALLBACK_NEEDS_WHITELIST = True
221
222 def __init__(self):
223 # TODO: allow for alternate posting methods (REST/UDP/agent/etc)
224 super().__init__()
225
226 # verify dependencies
227 if not HAS_SSL:
228 self._display.warning("Unable to import ssl module. Will send over port 80.")
229
230 if not HAS_CERTIFI:
231 self.disabled = True
232 self._display.warning(
233 "The `certifi` python module is not installed.\nDisabling the Logentries callback plugin."
234 )
235
236 self.le_jobid = str(uuid.uuid4())
237
238 # FIXME: make configurable, move to options
239 self.timeout = 10
240
241 def set_options(self, task_keys=None, var_options=None, direct=None):
242 super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
243
244 # get options
245 try:
246 self.api_url = self.get_option("api")
247 self.api_port = self.get_option("port")
248 self.api_tls_port = self.get_option("tls_port")
249 self.use_tls = self.get_option("use_tls")
250 self.flatten = self.get_option("flatten")
251 except KeyError as e:
252 self._display.warning(f"Missing option for Logentries callback plugin: {e}")
253 self.disabled = True
254
255 try:
256 self.token = self.get_option("token")
257 except KeyError:
258 self._display.warning(
259 "Logentries token was not provided, this is required for this callback to operate, disabling"
260 )
261 self.disabled = True
262
263 if self.flatten and not HAS_FLATDICT:
264 self.disabled = True
265 self._display.warning(
266 "You have chosen to flatten and the `flatdict` python module is not installed.\nDisabling the Logentries callback plugin."
267 )
268
269 self._initialize_connections()
270
271 def _initialize_connections(self):
272 if not self.disabled:
273 if self.use_tls:
274 self._display.vvvv(f"Connecting to {self.api_url}:{self.api_tls_port} with TLS")
275 self._appender = TLSSocketAppender(
276 display=self._display, LE_API=self.api_url, LE_TLS_PORT=self.api_tls_port
277 )
278 else:
279 self._display.vvvv(f"Connecting to {self.api_url}:{self.api_port}")
280 self._appender = PlainTextSocketAppender(
281 display=self._display, LE_API=self.api_url, LE_PORT=self.api_port
282 )
283 self._appender.reopen_connection()
284
285 def emit_formatted(self, record):
286 if self.flatten:
287 results = flatdict.FlatDict(record)
288 self.emit(self._dump_results(results))
289 else:
290 self.emit(self._dump_results(record))
291
292 def emit(self, record):
293 msg = record.rstrip("\n")
294 msg = f"{self.token} {msg}"
295 self._appender.put(msg)
296 self._display.vvvv("Sent event to logentries")
297
298 def _set_info(self, host, res):
299 return {"le_jobid": self.le_jobid, "hostname": host, "results": res}
300
301 def runner_on_ok(self, host, res):
302 results = self._set_info(host, res)
303 results["status"] = "OK"
304 self.emit_formatted(results)
305
306 def runner_on_failed(self, host, res, ignore_errors=False):
307 results = self._set_info(host, res)
308 results["status"] = "FAILED"
309 self.emit_formatted(results)
310
311 def runner_on_skipped(self, host, item=None):
312 results = self._set_info(host, item)
313 del results["results"]
314 results["status"] = "SKIPPED"
315 self.emit_formatted(results)
316
317 def runner_on_unreachable(self, host, res):
318 results = self._set_info(host, res)
319 results["status"] = "UNREACHABLE"
320 self.emit_formatted(results)
321
322 def runner_on_async_failed(self, host, res, jid):
323 results = self._set_info(host, res)
324 results["jid"] = jid
325 results["status"] = "ASYNC_FAILED"
326 self.emit_formatted(results)
327
328 def v2_playbook_on_play_start(self, play):
329 results = {}
330 results["le_jobid"] = self.le_jobid
331 results["started_by"] = os.getlogin()
332 if play.name:
333 results["play"] = play.name
334 results["hosts"] = play.hosts
335 self.emit_formatted(results)
336
337 def playbook_on_stats(self, stats):
338 """close connection"""
339 self._appender.close_connection()