Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/module_utils/session_utils.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Dell OpenManage Ansible Modules
4 # Version 9.2.0
5 # Copyright (C) 2024-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
6
7 # Redistribution and use in source and binary forms, with or without modification,
8 # are permitted provided that the following conditions are met:
9
10 # * Redistributions of source code must retain the above copyright notice,
11 # this list of conditions and the following disclaimer.
12
13 # * Redistributions in binary form must reproduce the above copyright notice,
14 # this list of conditions and the following disclaimer in the documentation
15 # and/or other materials provided with the distribution.
16
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
25 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #
27
28
29 from __future__ import (absolute_import, division, print_function)
30 __metaclass__ = type
31
32 import json
33 import os
34 from ansible.module_utils.urls import open_url
35 from ansible.module_utils.six.moves.urllib.parse import urlencode
36 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import config_ipv6
37 from ansible.module_utils.urls import open_url
38 from abc import ABC, abstractmethod
39
40 HEADER_TYPE = "application/json"
41
42
43 class OpenURLResponse():
44 """
45 HTTP response handler class.
46 """
47 def __init__(self, resp):
48 """
49 Initializes a new instance of the class.
50
51 Args:
52 resp (Response): The response object to read the body from.
53
54 Initializes the following instance variables:
55 - body (bytes): The body of the response, or None if the response is None.
56 - resp (Response): The response object.
57
58 If the response is not None, the body is set to the content of the response.
59 """
60 self.body = None
61 self.resp = resp
62 if self.resp:
63 self.body = self.resp.read()
64
65 @property
66 def json_data(self):
67 """
68 Returns the JSON data parsed from the `body` attribute of the object.
69
70 :return: The parsed JSON data.
71 :raises ValueError: If the `body` attribute cannot be parsed as JSON.
72 """
73 try:
74 return json.loads(self.body)
75 except ValueError as exc:
76 raise ValueError("Unable to parse json") from exc
77
78 @property
79 def status_code(self):
80 """
81 Get the status code of the response.
82
83 Returns:
84 int: The status code of the response.
85 """
86 return self.resp.getcode()
87
88 @property
89 def success(self):
90 """
91 Returns a boolean indicating whether the status code of the response is within the range
92 of 200-299.
93
94 :return: True if the status code is within the range of 200-299, False otherwise.
95 :rtype: bool
96 """
97 status = self.status_code
98 return status >= 200 & status <= 299
99
100 @property
101 def headers(self):
102 """
103 Returns the headers of the response object.
104
105 :return: A dictionary containing the headers of the response object.
106 :rtype: dict
107 """
108 return self.resp.headers
109
110 @property
111 def reason(self):
112 """
113 Get the reason for the response.
114
115 Returns:
116 str: The reason for the response.
117 """
118 return self.resp.reason
119
120
121 class SessionAPI():
122 """
123 Main class for session operations.
124 """
125 def __init__(self, module_params):
126 """
127 Initializes the object with the given module parameters.
128
129 Args:
130 module_params (dict): A dictionary containing the module parameters.
131 - "hostname" (str): The IP address or hostname of the target system.
132 - "username" (str): The username for authentication.
133 - "password" (str): The password for authentication.
134 - "port" (int, optional): The port number. Defaults to None.
135 - "validate_certs" (bool, optional): Whether to validate SSL certificates. Defaults
136 to False.
137 - "ca_path" (str, optional): The path to the CA certificate file. Defaults to None.
138 - "timeout" (int, optional): The timeout value in seconds. Defaults to None.
139 - "use_proxy" (bool, optional): Whether to use a proxy. Defaults to True.
140
141 Returns:
142 None
143 """
144 self.ipaddress = module_params.get("hostname")
145 self.username = module_params.get("username")
146 self.password = module_params.get("password")
147 self.port = module_params.get("port")
148 self.validate_certs = module_params.get("validate_certs", False)
149 self.ca_path = module_params.get("ca_path")
150 self.timeout = module_params.get("timeout")
151 self.use_proxy = module_params.get("use_proxy", True)
152 self.protocol = 'https'
153 self.ipaddress = config_ipv6(self.ipaddress)
154 self.set_headers(module_params)
155
156 def set_headers(self, module_params):
157 """
158 Set the headers for the HTTP request based on the module parameters.
159
160 Parameters:
161 module_params (dict): The module parameters containing the state and auth_token.
162
163 Returns:
164 None
165
166 This function sets the headers for the HTTP request based on the state parameter in the
167 module_params.
168 If the state is "present", the headers will include 'Content-Type' and 'Accept' with values
169 'application/json'.
170 If the state is not "present", the headers will include 'Content-Type', 'Accept', and
171 'X-Auth-Token' with the value from the auth_token parameter in module_params.
172 """
173 if module_params.get("state") == "present":
174 self._headers = {
175 'Content-Type': HEADER_TYPE,
176 'Accept': HEADER_TYPE
177 }
178 else:
179 self._headers = {
180 'Content-Type': HEADER_TYPE,
181 'Accept': HEADER_TYPE,
182 'X-Auth-Token': module_params.get("x_auth_token")
183 }
184
185 def _get_url(self, uri):
186 """
187 Generate the full URL by combining the protocol, IP address, port, and URI.
188
189 Parameters:
190 uri (str): The URI to be appended to the URL.
191
192 Returns:
193 str: The full URL generated by combining the protocol, IP address, port, and URI.
194 """
195 return f"{self.protocol}://{self.ipaddress}:{self.port}{uri}"
196
197 def _build_url(self, path, query_param=None):
198 """
199 Builds a URL by concatenating the base URI with the given path and query parameters.
200
201 Args:
202 path (str): The path component of the URL.
203 query_param (dict, optional): A dictionary of query parameters to be appended to the
204 URL. Defaults to None.
205
206 Returns:
207 str: The fully constructed URL.
208
209 Raises:
210 None
211
212 Examples:
213 >>> session = SessionUtils()
214 >>> session._build_url("/api/endpoint", {"param1": "value1", "param2": "value2"})
215 "/api/endpoint?param1=value1&param2=value2"
216 """
217 url = path
218 base_uri = self._get_url(url)
219 if path:
220 url = base_uri
221 if query_param:
222 url += f"?{urlencode(query_param)}"
223 return url
224
225 def _url_common_args_spec(self, method, api_timeout, headers=None, url_kwargs=None):
226 """
227 Generates the common arguments for a URL request.
228
229 Args:
230 method (str): The HTTP method for the request.
231 api_timeout (int, optional): The timeout for the API request. If None, the default
232 timeout is used.
233 headers (dict, optional): Additional headers to include in the request.
234
235 Returns:
236 dict: A dictionary containing the common arguments for the URL request. The dictionary
237 has the following keys:
238 - method (str): The HTTP method for the request.
239 - validate_certs (bool): Whether to validate the SSL certificates.
240 - ca_path (str): The path to the CA certificate bundle.
241 - use_proxy (bool): Whether to use a proxy for the request.
242 - headers (dict): The headers to include in the request.
243 - timeout (int): The timeout for the request.
244 - follow_redirects (str): The policy for following redirects.
245
246 """
247 if api_timeout is None:
248 api_timeout = self.timeout
249 if self.ca_path is None:
250 self.ca_path = self._get_omam_ca_env()
251 req_header = self._headers
252 if headers:
253 req_header.update(headers)
254 url_params = {
255 "method": method,
256 "validate_certs": self.validate_certs,
257 "ca_path": self.ca_path,
258 "use_proxy": self.use_proxy,
259 "headers": req_header,
260 "timeout": api_timeout,
261 "follow_redirects": 'all'
262 }
263 if url_kwargs:
264 url_params.update(url_kwargs)
265 return url_params
266
267 def _args_session(self, method, api_timeout, headers=None, url_kwargs=None):
268 """
269 Returns a dictionary containing the arguments needed to establish a session.
270
271 :param path: A string representing the path of the API endpoint.
272 :param method: A string representing the HTTP method to be used.
273 :param api_timeout: An integer representing the timeout for the API request.
274 :param headers: An optional dictionary containing additional headers to be included in the
275 request.
276 :return: A dictionary containing the arguments needed to establish a session, including the
277 URL arguments, headers, and API timeout.
278 """
279 req_header = self._headers
280 if headers:
281 req_header.update(headers)
282 url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers, url_kwargs=url_kwargs)
283 return url_kwargs
284
285 def invoke_request(self, uri, method, data=None, query_param=None, headers=None,
286 api_timeout=None, dump=True, url_kwargs=None):
287 """
288 Invokes a request to the specified URI using the given method and optional parameters.
289
290 :param uri: The URI to send the request to.
291 :type uri: str
292 :param method: The HTTP method to use for the request.
293 :type method: str
294 :param data: The data to send with the request (default: None).
295 :type data: dict or None
296 :param query_param: The query parameters to include in the request URL (default: None).
297 :type query_param: dict or None
298 :param headers: The headers to include in the request (default: None).
299 :type headers: dict or None
300 :param api_timeout: The timeout for the request in seconds (default: None).
301 :type api_timeout: int or None
302 :param dump: Whether to dump the data to JSON before sending the request (default: True).
303 :type dump: bool
304 :return: The response data from the request.
305 :rtype: OpenURLResponse
306 """
307 url_kwargs = self._args_session(method, api_timeout, headers=headers, url_kwargs=url_kwargs)
308 if data and dump:
309 data = json.dumps(data)
310 url = self._build_url(uri, query_param=query_param)
311 resp = open_url(url, data=data, **url_kwargs)
312 resp_data = OpenURLResponse(resp)
313 return resp_data
314
315 def _get_omam_ca_env(self):
316 """
317 Returns the value of the environment variable REQUESTS_CA_BUNDLE, or if it is not set,
318 the value of the environment variable CURL_CA_BUNDLE, or if that is not set,
319 the value of the environment variable OMAM_CA_BUNDLE.
320
321 :return: The value of the environment variable, or None if none of the variables are set.
322 :rtype: str or None
323 """
324 return (os.environ.get("REQUESTS_CA_BUNDLE") or
325 os.environ.get("CURL_CA_BUNDLE") or
326 os.environ.get("OMAM_CA_BUNDLE"))
327
328
329 class Session(ABC):
330 """
331 Parent class for all session operations.
332 """
333 def __init__(self, module):
334 """
335 Initializes the object with the given instance and module parameters.
336
337 Args:
338 instance (object): The ome object.
339 module (object): The module object.
340
341 Returns:
342 None
343 """
344 self.instance = SessionAPI(module.params)
345 self.module = module
346
347 @abstractmethod
348 def create_session(self):
349 """
350 Abstract method to create a session.
351 Must be implemented by subclasses.
352
353 Args:
354 None
355
356 Returns:
357 None
358 """
359 pass
360
361 @abstractmethod
362 def delete_session(self):
363 """
364 Abstract method to delete a session.
365 Must be implemented by subclasses.
366
367 Args:
368 None
369
370 Returns:
371 None
372 """
373 pass