Debian Codegraph @

ansible_collections/community/zabbix/plugins/module_utils/api_request.py

raw
1 # -*- coding: utf-8 -*-
2
3 # (c) 2021, Markus Fischbacher ([email protected])
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 # Quick Link to Zabbix API docs: https://www.zabbix.com/documentation/current/manual/api
7
8
9 from __future__ import absolute_import, division, print_function
10
11 __metaclass__ = type
12
13 from uuid import uuid4
14
15 from ssl import CertificateError
16 from ansible.module_utils.connection import ConnectionError
17 from ansible.module_utils.connection import Connection
18 from ansible.module_utils._text import to_text
19
20
21 class ZabbixApiRequest(object):
22
23 def __init__(self, module):
24 self.module = module
25 self.connection = Connection(self.module._socket_path)
26
27 def _httpapi_error_handle(self, payload=None):
28 try:
29 code, response = self.connection.send_request(data=payload)
30 except ConnectionError as e:
31 self.module.fail_json(msg="connection error occurred: {0}".format(e))
32 except CertificateError as e:
33 self.module.fail_json(msg="certificate error occurred: {0}".format(e))
34 except ValueError as e:
35 self.module.fail_json(msg="certificate not found: {0}".format(e))
36
37 if code == 404:
38 if to_text(u"Object not found") in to_text(response) or to_text(
39 u"Could not find object"
40 ) in to_text(response):
41 return {}
42
43 if not (code >= 200 and code < 300):
44 self.module.fail_json(
45 msg="Zabbix httpapi returned error {0} with message {1}".format(
46 code, response
47 )
48 )
49
50 return response
51
52 def api_version(self):
53 return self.connection.api_version()
54
55 @staticmethod
56 def payload_builder(method_, params, jsonrpc_version='2.0', reqid=str(uuid4()), **kwargs):
57 req = {'jsonrpc': jsonrpc_version, 'method': method_, 'id': reqid}
58 req['params'] = params
59 return req
60
61 def __getattr__(self, name):
62 return ZabbixApiSection(self, name)
63
64
65 class ZabbixApiSection(object):
66 parent = None
67 name = None
68
69 def __init__(self, parent, name):
70 self.name = name
71 self.parent = parent
72
73 def __getattr__(self, name):
74 def method(opts=None):
75 if self.name == "configuration" and name == "import_":
76 _method = "configuration.import"
77 else:
78 _method = "%s.%s" % (self.name, name)
79 if not opts:
80 opts = {}
81 payload = ZabbixApiRequest.payload_builder(_method, opts)
82 return self.parent._httpapi_error_handle(payload=payload)
83
84 return method