Debian Codegraph @

ansible_collections/splunk/es/plugins/httpapi/splunk.py

raw
1 # (c) 2019 Red Hat Inc.
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 DOCUMENTATION = """
5 ---
6 author: Ansible Security Team (@ansible-security)
7 name: splunk
8 short_description: HttpApi Plugin for Splunk
9 description:
10 - This HttpApi plugin provides methods to connect to Splunk over a
11 HTTP(S)-based api.
12 version_added: "1.0.0"
13 """
14
15 import json
16
17 from ansible.errors import AnsibleConnectionFailure
18 from ansible.module_utils.basic import to_text
19 from ansible.module_utils.connection import ConnectionError
20 from ansible.module_utils.six.moves.urllib.error import HTTPError
21 from ansible.plugins.httpapi import HttpApiBase
22
23
24 BASE_HEADERS = {"Content-Type": "application/json"}
25
26
27 class HttpApi(HttpApiBase):
28 def send_request(self, request_method, path, payload=None):
29 # payload = json.dumps(payload) if payload else '{}'
30
31 try:
32 self._display_request(request_method, path)
33 response, response_data = self.connection.send(
34 path,
35 payload,
36 method=request_method,
37 headers=BASE_HEADERS,
38 force_basic_auth=True,
39 )
40 value = self._get_response_value(response_data)
41
42 return response.getcode(), self._response_to_json(value)
43 except AnsibleConnectionFailure as e:
44 self.connection.queue_message(
45 "vvv",
46 "AnsibleConnectionFailure: %s" % e,
47 )
48 if to_text("Could not connect to") in to_text(e):
49 raise
50 if to_text("401") in to_text(e):
51 return 401, "Authentication failure"
52 else:
53 return 404, "Object not found"
54 except HTTPError as e:
55 error = json.loads(e.read())
56 return e.code, error
57
58 def _display_request(self, request_method, path):
59 self.connection.queue_message(
60 "vvvv",
61 "Web Services: %s %s/%s" % (request_method, self.connection._url, path),
62 )
63
64 def _get_response_value(self, response_data):
65 return to_text(response_data.getvalue())
66
67 def _response_to_json(self, response_text):
68 try:
69 return json.loads(response_text) if response_text else {}
70 # JSONDecodeError only available on Python 3.5+
71 except ValueError:
72 raise ConnectionError("Invalid JSON response: %s" % response_text)