Debian Codegraph @

ansible_collections/pcg/alpaca_operator/plugins/module_utils/_alpaca_api.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Contributors to the Ansible project
4 # Apache License, Version 2.0 (see LICENSE or https://www.apache.org/licenses/LICENSE-2.0)
5
6
7 # This module is for internal use only within the pcg.alpaca_operator collection.
8 # Python versions supported: 3.8+
9
10 from __future__ import (absolute_import, division, print_function)
11
12 __metaclass__ = type
13
14 import json as json_module
15
16 from ansible.module_utils.urls import open_url
17
18
19 def api_call(method, url, headers=None, json=None, verify=True, module=None, fail_msg=None):
20 """Make API call and return response data"""
21 try:
22 data = None
23 if json is not None:
24 data = json_module.dumps(json).encode('utf-8')
25 if headers is None:
26 headers = {}
27 else:
28 headers = dict(headers) # Create a copy to avoid modifying the original
29 headers['Content-Type'] = 'application/json'
30
31 response = open_url(
32 url,
33 method=method,
34 headers=headers,
35 data=data,
36 validate_certs=verify,
37 http_agent='ansible-alpaca-operator'
38 )
39
40 status_code = response.getcode()
41 content = response.read()
42 text = content.decode('utf-8') if isinstance(content, bytes) else content
43
44 if status_code >= 400:
45 if module and fail_msg:
46 module.fail_json(msg="{0}: {1}".format(fail_msg, text))
47 raise Exception("HTTP {0}: {1}".format(status_code, text))
48
49 # Parse JSON if content exists, otherwise return empty dict
50 try:
51 json_result = json_module.loads(text) if text else {}
52 except ValueError:
53 json_result = {}
54
55 class ResponseDict(dict):
56 """Dictionary-like object with json() method and attribute access for compatibility"""
57 def __init__(self, status_code, text, json_data):
58 # Only initialize dict with json_data if it's a dict, otherwise store as attribute
59 if isinstance(json_data, dict):
60 super(ResponseDict, self).__init__(json_data)
61 else:
62 super(ResponseDict, self).__init__()
63 self._status_code = status_code
64 self._text = text
65 self._json_data = json_data
66
67 def json(self):
68 """Return the parsed JSON data (can be dict, list, or other types)"""
69 return self._json_data
70
71 def __getattr__(self, name):
72 """Allow attribute access to status_code, text, and dictionary keys"""
73 if name == 'status_code':
74 return self._status_code
75 elif name == 'text':
76 return self._text
77 try:
78 return self[name]
79 except KeyError:
80 raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, name))
81
82 result = ResponseDict(status_code, text, json_result)
83 return result
84
85 except Exception as e:
86 if module:
87 error_msg = "{0}: {1}".format(fail_msg or 'API request failed.', str(e))
88 module.fail_json(msg=error_msg)
89 raise
90
91
92 def get_token(api_url, username, password, verify):
93 """Get API token"""
94 payload = {"username": username, "password": password}
95 response = api_call("POST", "{0}/auth/login".format(api_url), json=payload, verify=verify)
96 return response.json()["token"]
97
98
99 def lookup_resource(api_url, headers, resource, key, value, verify):
100 """Find resource by the given key and value"""
101 response = api_call("GET", "{0}/{1}".format(api_url, resource), headers=headers, verify=verify)
102 for resource in response.json():
103 if resource.get(key) == value:
104 return resource
105 return None
106
107
108 def lookup_processId(api_url, headers, key, value, verify):
109 """Find processId by the given key and value"""
110 response = api_call("GET", "{0}/processes/tree".format(api_url), headers=headers, verify=verify)
111 for type in response.json():
112 for process in type.get('processes', []):
113 if str(process.get(key)) == str(value):
114 return process.get('id')
115 return None
116
117
118 def get_api_connection_argument_spec():
119 """Return the argument spec for api_connection parameter"""
120 return dict(
121 type='dict',
122 required=True,
123 options=dict(
124 host=dict(type='str', required=False, default='localhost'),
125 port=dict(type='int', required=False, default='8443'),
126 protocol=dict(type='str', required=False, default='https', choices=['http', 'https']),
127 username=dict(type='str', required=True, no_log=True),
128 password=dict(type='str', required=True, no_log=True),
129 tls_verify=dict(type='bool', required=False, default=True)
130 )
131 )