Debian Codegraph @

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

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Dell OpenManage Ansible Modules
4 # Version 9.12.3
5 # Copyright (C) 2019-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 import re
35 from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError
36 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
37 from ansible.module_utils.six.moves.urllib.parse import urlencode
38 from ansible.module_utils.common.parameters import env_fallback
39 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import config_ipv6
40 from ansible.module_utils.basic import AnsibleModule
41
42 redfish_auth_params = {
43 "baseuri": {"required": True, "type": "str"},
44 "username": {"required": True, "type": "str", "fallback": (env_fallback, ['IDRAC_USERNAME'])},
45 "password": {"required": True, "type": "str", "no_log": True, "fallback": (env_fallback, ['IDRAC_PASSWORD'])},
46 "validate_certs": {"type": "bool", "default": True},
47 "ca_path": {"type": "path"},
48 "timeout": {"type": "int", "default": 30},
49 }
50
51 SESSION_RESOURCE_COLLECTION = {
52 "SESSION": "/redfish/v1/SessionService/Sessions",
53 "SESSION_ID": "/redfish/v1/SessionService/Sessions/{Id}",
54 }
55
56 HOST_UNRESOLVED_MSG = "Unable to resolve hostname or IP {0}."
57 MANAGER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1"
58 GET_IDRAC_MANAGER_ATTRIBUTES_9_10 = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellAttributes/iDRAC.Embedded.1"
59
60
61 class OpenURLResponse(object):
62 """Handles HTTPResponse"""
63
64 def __init__(self, resp):
65 self.body = None
66 self.resp = resp
67 if self.resp:
68 self.body = self.resp.read()
69
70 @property
71 def json_data(self):
72 try:
73 return json.loads(self.body)
74 except ValueError:
75 raise ValueError("Unable to parse json")
76
77 @property
78 def success(self):
79 status = self.status_code
80 return status >= 200 & status <= 299
81
82 @property
83 def headers(self):
84 return self.resp.headers
85
86 @property
87 def status_code(self):
88 return self.resp.getcode()
89
90 @property
91 def reason(self):
92 return self.resp.reason
93
94
95 class Redfish(object):
96 """Handles iDRAC Redfish API requests"""
97
98 def __init__(self, module_params=None, req_session=False):
99 self.module_params = module_params
100 self.hostname = self.module_params["baseuri"]
101 self.username = self.module_params["username"]
102 self.password = self.module_params["password"]
103 self.x_auth_token = self.module_params.get("x_auth_token")
104 self.validate_certs = self.module_params.get("validate_certs", True)
105 self.ca_path = self.module_params.get("ca_path")
106 self.timeout = self.module_params.get("timeout", 30)
107 self.use_proxy = self.module_params.get("use_proxy", True)
108 self.req_session = req_session
109 self.session_id = None
110 self.protocol = 'https'
111 self.root_uri = '/redfish/v1/'
112 self._headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
113 self.hostname = config_ipv6(self.hostname)
114
115 def _get_base_url(self):
116 """builds base url"""
117 return '{0}://{1}'.format(self.protocol, self.hostname)
118
119 def _url_common_args_spec(self, method, api_timeout, headers=None):
120 """Creates an argument common spec"""
121 req_header = self._headers
122 if headers:
123 req_header.update(headers)
124 if api_timeout is None:
125 api_timeout = self.timeout
126 if self.ca_path is None:
127 self.ca_path = self._get_omam_ca_env()
128 url_kwargs = {
129 "method": method,
130 "validate_certs": self.validate_certs,
131 "ca_path": self.ca_path,
132 "use_proxy": self.use_proxy,
133 "headers": req_header,
134 "timeout": api_timeout,
135 "follow_redirects": 'all',
136 }
137 return url_kwargs
138
139 def _build_url(self, path, query_param=None):
140 """builds complete url"""
141 url = path
142 base_uri = self._get_base_url()
143 if path:
144 url = base_uri + path
145 if query_param:
146 url += "?{0}".format(urlencode(query_param))
147 return url
148
149 def _args_without_session(self, path, method, api_timeout, headers=None):
150 """Creates an argument spec in case of basic authentication"""
151 req_header = self._headers
152 if headers:
153 req_header.update(headers)
154 url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers)
155 if not (path == SESSION_RESOURCE_COLLECTION["SESSION"] and method == 'POST'):
156 url_kwargs["url_username"] = self.username
157 url_kwargs["url_password"] = self.password
158 url_kwargs["force_basic_auth"] = True
159 return url_kwargs
160
161 def _args_with_session(self, method, api_timeout, headers=None):
162 """Creates an argument spec, in case of authentication with session"""
163 url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers)
164 url_kwargs["force_basic_auth"] = False
165 return url_kwargs
166
167 def invoke_request(self, method, path, data=None, query_param=None, headers=None,
168 api_timeout=None, dump=True):
169 """
170 Sends a request through open_url
171 Returns :class:`OpenURLResponse` object.
172 :arg method: HTTP verb to use for the request
173 :arg path: path to request without query parameter
174 :arg data: (optional) Payload to send with the request
175 :arg query_param: (optional) Dictionary of query parameter to send with request
176 :arg headers: (optional) Dictionary of HTTP Headers to send with the
177 request
178 :arg api_timeout: (optional) How long to wait for the server to send
179 data before giving up
180 :arg dump: (Optional) boolean value for dumping payload data.
181 :returns: OpenURLResponse
182 """
183 try:
184 if 'X-Auth-Token' in self._headers:
185 url_kwargs = self._args_with_session(method, api_timeout, headers=headers)
186 else:
187 url_kwargs = self._args_without_session(path, method, api_timeout, headers=headers)
188 if data and dump:
189 data = json.dumps(data)
190 url = self._build_url(path, query_param=query_param)
191 resp = open_url(url, data=data, **url_kwargs)
192 resp_data = OpenURLResponse(resp)
193 except (HTTPError, URLError, SSLValidationError, ConnectionError) as err:
194 raise err
195 return resp_data
196
197 def __enter__(self):
198 """Creates sessions by passing it to header"""
199 if self.req_session and not self.x_auth_token:
200 payload = {'UserName': self.username,
201 'Password': self.password}
202 path = SESSION_RESOURCE_COLLECTION["SESSION"]
203 resp = self.invoke_request('POST', path, data=payload)
204 if resp and resp.success:
205 self.session_id = resp.json_data.get("Id")
206 self._headers["X-Auth-Token"] = resp.headers.get('X-Auth-Token')
207 else:
208 msg = "Could not create the session"
209 raise ConnectionError(msg)
210 elif self.x_auth_token is not None:
211 self._headers["X-Auth-Token"] = self.x_auth_token
212 return self
213
214 def __exit__(self, exc_type, exc_value, traceback):
215 """Deletes a session id, which is in use for request for redfish session"""
216 if self.session_id:
217 path = SESSION_RESOURCE_COLLECTION["SESSION_ID"].format(Id=self.session_id)
218 self.invoke_request('DELETE', path)
219 return False
220
221 @property
222 def get_server_generation(self):
223 """
224 This method fetches the connected server generation.
225 :return: 14, 4.11.11.11, iDRAC 9
226 """
227 firmware_version = None
228 response = self.invoke_request(method='GET', path=MANAGER_URI)
229 if response.status_code == 200:
230 generation = int(re.search(r"\d+(?=G)", response.json_data["Model"]).group())
231 firmware_version = response.json_data["FirmwareVersion"]
232 hw_model = ""
233 try:
234 hw_model_out = self.invoke_request(method='GET', path=GET_IDRAC_MANAGER_ATTRIBUTES_9_10)
235 if hw_model_out.status_code == 200:
236 hw_model = hw_model_out.json_data.get('Attributes', {}).get('Info.1.HWModel', "iDRAC 9")
237 except HTTPError:
238 hw_model = "iDRAC 8"
239 return generation, firmware_version, hw_model
240
241 def strip_substr_dict(self, odata_dict, chkstr='@odata.'):
242 cp = odata_dict.copy()
243 klist = cp.keys()
244 for k in klist:
245 if chkstr in str(k).lower():
246 odata_dict.pop(k)
247 return odata_dict
248
249 def _get_omam_ca_env(self):
250 """Check if the value is set in REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE or OMAM_CA_BUNDLE or returns None"""
251 return os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("CURL_CA_BUNDLE") or os.environ.get("OMAM_CA_BUNDLE")
252
253
254 class RedfishAnsibleModule(AnsibleModule):
255 def __init__(self, argument_spec, bypass_checks=False, no_log=False,
256 mutually_exclusive=None, required_together=None,
257 required_one_of=None, add_file_common_args=False,
258 supports_check_mode=False, required_if=None, required_by=None):
259 redfish_argument_spec = {
260 "baseuri": {"required": True, "type": "str"},
261 "username": {"required": False, "type": "str", "fallback": (env_fallback, ['IDRAC_USERNAME'])},
262 "password": {"required": False, "type": "str", "no_log": True, "fallback": (env_fallback, ['IDRAC_PASSWORD'])},
263 "x_auth_token": {"required": False, "type": "str", "no_log": True, "fallback": (env_fallback, ['IDRAC_X_AUTH_TOKEN'])},
264 "validate_certs": {"type": "bool", "default": True},
265 "ca_path": {"type": "path"},
266 "timeout": {"type": "int", "default": 30},
267 }
268 argument_spec.update(redfish_argument_spec)
269
270 auth_mutually_exclusive = [("username", "x_auth_token"), ("password", "x_auth_token")]
271 auth_required_one_of = [("username", "x_auth_token")]
272 auth_required_together = [("username", "password")]
273
274 if mutually_exclusive is None:
275 mutually_exclusive = []
276 mutually_exclusive.extend(auth_mutually_exclusive)
277 if required_one_of is None:
278 required_one_of = []
279 required_one_of.extend(auth_required_one_of)
280 if required_together is None:
281 required_together = []
282 required_together.extend(auth_required_together)
283 if required_by is None:
284 required_by = {}
285
286 super().__init__(argument_spec, bypass_checks, no_log,
287 mutually_exclusive, required_together,
288 required_one_of, add_file_common_args,
289 supports_check_mode, required_if, required_by)