Debian Codegraph @

ansible_collections/netapp_eseries/santricity/plugins/module_utils/santricity.py

raw
1 # (c) 2024, NetApp, Inc
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import absolute_import, division, print_function
5 __metaclass__ = type
6
7 import json
8 import random
9 import mimetypes
10
11 from pprint import pformat
12 from ansible.module_utils import six
13 from ansible.module_utils.basic import AnsibleModule
14 from ansible.module_utils.six.moves.urllib.error import HTTPError
15 from ansible.module_utils.urls import open_url
16 from ansible.module_utils.api import basic_auth_argument_spec
17 from ansible.module_utils._text import to_native
18 try:
19 from ansible.module_utils.ansible_release import __version__ as ansible_version
20 except ImportError:
21 ansible_version = 'unknown'
22
23 try:
24 from urlparse import urlparse
25 except ImportError:
26 from urllib.parse import urlparse
27
28
29 def eseries_host_argument_spec():
30 """Retrieve a base argument specification common to all NetApp E-Series modules"""
31 argument_spec = basic_auth_argument_spec()
32 argument_spec.update(dict(
33 api_username=dict(type="str", required=True),
34 api_password=dict(type="str", required=True, no_log=True),
35 api_url=dict(type="str", required=True),
36 ssid=dict(type="str", required=False, default="1"),
37 validate_certs=dict(type="bool", required=False, default=True)
38 ))
39 return argument_spec
40
41
42 def eseries_proxy_argument_spec():
43 """Retrieve a base argument specification common to all NetApp E-Series modules for proxy specific tasks"""
44 argument_spec = basic_auth_argument_spec()
45 argument_spec.update(dict(
46 api_username=dict(type="str", required=True),
47 api_password=dict(type="str", required=True, no_log=True),
48 api_url=dict(type="str", required=True),
49 validate_certs=dict(type="bool", required=False, default=True)
50 ))
51 return argument_spec
52
53
54 class NetAppESeriesModule(object):
55 """Base class for all NetApp E-Series modules.
56
57 Provides a set of common methods for NetApp E-Series modules, including version checking, mode (proxy, embedded)
58 verification, http requests, secure http redirection for embedded web services, and logging setup.
59
60 Be sure to add the following lines in the module's documentation section:
61 extends_documentation_fragment:
62 - santricity
63
64 :param dict(dict) ansible_options: dictionary of ansible option definitions
65 :param str web_services_version: minimally required web services rest api version (default value: "02.00.0000.0000")
66 :param bool supports_check_mode: whether the module will support the check_mode capabilities (default=False)
67 :param list(list) mutually_exclusive: list containing list(s) of mutually exclusive options (optional)
68 :param list(list) required_if: list containing list(s) containing the option, the option value, and then a list of
69 required options. (optional)
70 :param list(list) required_one_of: list containing list(s) of options for which at least one is required. (optional)
71 :param list(list) required_together: list containing list(s) of options that are required together. (optional)
72 :param bool log_requests: controls whether to log each request (default: True)
73 :param bool proxy_specific_task: controls whether ssid is a default option (default: False)
74 """
75 DEFAULT_TIMEOUT = 300
76 DEFAULT_SECURE_PORT = "8443"
77 DEFAULT_BASE_PATH = "devmgr/"
78 DEFAULT_REST_API_PATH = "devmgr/v2/"
79 DEFAULT_REST_API_ABOUT_PATH = "devmgr/utils/about"
80 DEFAULT_HEADERS = {"Content-Type": "application/json", "Accept": "application/json",
81 "netapp-client-type": "Ansible-%s" % ansible_version}
82 HTTP_AGENT = "Ansible / %s" % ansible_version
83 SIZE_UNIT_MAP = dict(bytes=1, b=1, kb=1024, mb=1024**2, gb=1024**3, tb=1024**4,
84 pb=1024**5, eb=1024**6, zb=1024**7, yb=1024**8)
85
86 HOST_TYPE_INDEXES = {"aix mpio": 9, "avt 4m": 5, "hp-ux": 15, "linux atto": 24, "linux dm-mp": 28, "linux pathmanager": 25, "solaris 10 or earlier": 2,
87 "solaris 11 or later": 17, "svc": 18, "ontap": 26, "mac": 22, "vmware": 10, "windows": 1, "windows atto": 23, "windows clustered": 8}
88
89 def __init__(self, ansible_options, web_services_version=None, supports_check_mode=False,
90 mutually_exclusive=None, required_if=None, required_one_of=None, required_together=None,
91 log_requests=True, proxy_specific_task=False):
92
93 if proxy_specific_task:
94 argument_spec = eseries_proxy_argument_spec()
95 else:
96 argument_spec = eseries_host_argument_spec()
97
98 argument_spec.update(ansible_options)
99
100 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=supports_check_mode,
101 mutually_exclusive=mutually_exclusive, required_if=required_if,
102 required_one_of=required_one_of, required_together=required_together)
103
104 args = self.module.params
105 self.web_services_version = web_services_version if web_services_version else "02.00.0000.0000"
106
107 if proxy_specific_task:
108 self.ssid = "0"
109 else:
110 self.ssid = args["ssid"]
111 self.url = args["api_url"]
112 self.log_requests = log_requests
113 self.creds = dict(url_username=args["api_username"],
114 url_password=args["api_password"],
115 validate_certs=args["validate_certs"])
116
117 if not self.url.endswith("/"):
118 self.url += "/"
119
120 self.is_proxy_used_cache = None
121 self.is_embedded_available_cache = None
122 self.is_web_services_valid_cache = None
123
124 def _check_ssid(self):
125 """Verify storage system identifier exist on the proxy and, if not, then update to match storage system name."""
126 try:
127 rc, data = self._request(url=self.url + self.DEFAULT_REST_API_ABOUT_PATH, **self.creds)
128
129 if data["runningAsProxy"]:
130 if self.ssid.lower() not in ["proxy", "0"]:
131 try:
132 rc, systems = self._request(url=self.url + self.DEFAULT_REST_API_PATH + "storage-systems", **self.creds)
133 alternates = []
134 for system in systems:
135 if system["id"] == self.ssid:
136 break
137 elif system["name"] == self.ssid:
138 alternates.append(system["id"])
139 else:
140 if len(alternates) == 1:
141 self.module.warn("Array Id does not exist on Web Services Proxy instance! "
142 "However, there is a storage system with a matching name. "
143 "Updating Identifier. Array Name: [%s], Array Id [%s]." % (self.ssid, alternates[0]))
144 self.ssid = alternates[0]
145 else:
146 self.module.fail_json(msg="Array identifier does not exist on Web Services Proxy "
147 "instance! Array ID [%s]." % self.ssid)
148
149 except Exception as error:
150 self.module.fail_json(msg="Failed to determine Web Services Proxy storage systems! "
151 "Array [%s]. Error [%s]" % (self.ssid, to_native(error)))
152 except Exception as error:
153 # Don't fail here, if the ssid is wrong then it will fail on the next request. Causes issues for
154 # na_santricity_auth module.
155 pass
156
157 def _check_web_services_version(self):
158 """Verify proxy or embedded web services meets minimum version required for module.
159
160 The minimum required web services version is evaluated against version supplied through the web services rest
161 api. AnsibleFailJson exception will be raised when the minimum is not met or exceeded.
162
163 This helper function will update the supplied api url if secure http is not used for embedded web services
164
165 :raise AnsibleFailJson: raised when the contacted api service does not meet the minimum required version.
166 """
167 if not self.is_web_services_valid_cache:
168
169 url_parts = urlparse(self.url)
170 if not url_parts.scheme or not url_parts.netloc:
171 self.module.fail_json(msg="Failed to provide valid API URL. "
172 "Example: https://192.168.1.100:8443/devmgr/v2. URL [%s]." % self.url)
173
174 if url_parts.scheme not in ["http", "https"]:
175 self.module.fail_json(msg="Protocol must be http or https. URL [%s]." % self.url)
176
177 self.url = "%s://%s/" % (url_parts.scheme, url_parts.netloc)
178 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
179 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, ignore_errors=True, force_basic_auth=False, **self.creds)
180
181 if rc != 200:
182 self.module.warn("Failed to retrieve web services about information! Retrying with secure ports. "
183 "Array Id [%s]." % self.ssid)
184 self.url = "https://%s:8443/" % url_parts.netloc.split(":")[0]
185 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
186 try:
187 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, **self.creds)
188 except Exception as error:
189 self.module.fail_json(msg="Failed to retrieve the webservices about information! Array Id [%s]. "
190 "Error [%s]." % (self.ssid, to_native(error)))
191
192 if len(data["version"].split(".")) == 4:
193 major, minor, other, revision = data["version"].split(".")
194 minimum_major, minimum_minor, other, minimum_revision = self.web_services_version.split(".")
195
196 if not (major > minimum_major or
197 (major == minimum_major and minor > minimum_minor) or
198 (major == minimum_major and minor == minimum_minor and revision >= minimum_revision)):
199 self.module.fail_json(msg="Web services version does not meet minimum version required. "
200 "Current version: [%s]."
201 " Version required: [%s]." % (data["version"], self.web_services_version))
202 self.module.log("Web services rest api version met the minimum required version.")
203 else:
204 self.module.warn("Web services rest api version unknown!")
205
206 self._check_ssid()
207 self.is_web_services_valid_cache = True
208
209 def is_web_services_version_met(self, version):
210 """Determines whether a particular web services version has been satisfied."""
211 split_version = version.split(".")
212 if len(split_version) != 4 or not split_version[0].isdigit() or not split_version[1].isdigit() or not split_version[3].isdigit():
213 self.module.fail_json(msg="Version is not a valid Web Services version. Version [%s]." % version)
214
215 url_parts = urlparse(self.url)
216 if not url_parts.scheme or not url_parts.netloc:
217 self.module.fail_json(msg="Failed to provide valid API URL. "
218 "Example: https://192.168.1.100:8443/devmgr/v2. URL [%s]." % self.url)
219
220 if url_parts.scheme not in ["http", "https"]:
221 self.module.fail_json(msg="Protocol must be http or https. URL [%s]." % self.url)
222
223 self.url = "%s://%s/" % (url_parts.scheme, url_parts.netloc)
224 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
225 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, ignore_errors=True, **self.creds)
226
227 if rc != 200:
228 self.module.warn("Failed to retrieve web services about information! Retrying with secure ports. "
229 "Array Id [%s]." % self.ssid)
230 self.url = "https://%s:8443/" % url_parts.netloc.split(":")[0]
231 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
232 try:
233 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, **self.creds)
234 except Exception as error:
235 self.module.fail_json(msg="Failed to retrieve the webservices about information! Array Id [%s]. "
236 "Error [%s]." % (self.ssid, to_native(error)))
237
238 if len(data["version"].split(".")) == 4:
239 major, minor, other, revision = data["version"].split(".")
240 minimum_major, minimum_minor, other, minimum_revision = split_version
241 if not (major > minimum_major or
242 (major == minimum_major and minor > minimum_minor) or
243 (major == minimum_major and minor == minimum_minor and revision >= minimum_revision)):
244 return False
245 else:
246 return False
247 return True
248
249 def is_embedded_available(self):
250 """Determine whether the storage array has embedded services available."""
251 self._check_web_services_version()
252
253 if self.is_embedded_available_cache is None:
254
255 if self.is_proxy():
256 if self.ssid == "0" or self.ssid.lower() == "proxy":
257 self.is_embedded_available_cache = False
258 else:
259 try:
260 rc, bundle = self.request("storage-systems/%s/graph/xpath-filter?query=/sa/saData/extendedSAData/codeVersions[codeModule='bundle']"
261 % self.ssid)
262 self.is_embedded_available_cache = False
263 if bundle:
264 self.is_embedded_available_cache = True
265 except Exception as error:
266 self.module.fail_json(msg="Failed to retrieve information about storage system [%s]. "
267 "Error [%s]." % (self.ssid, to_native(error)))
268 else: # Contacted using embedded web services
269 self.is_embedded_available_cache = True
270
271 self.module.log("embedded_available: [%s]" % ("True" if self.is_embedded_available_cache else "False"))
272 return self.is_embedded_available_cache
273
274 def is_embedded(self):
275 """Determine whether web services server is the embedded web services."""
276 return not self.is_proxy()
277
278 def is_proxy(self):
279 """Determine whether web services server is the proxy web services.
280
281 :raise AnsibleFailJson: raised when web services about endpoint failed to be contacted.
282 :return bool: whether contacted web services is running from storage array (embedded) or from a proxy.
283 """
284 self._check_web_services_version()
285
286 if self.is_proxy_used_cache is None:
287 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
288 try:
289 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, force_basic_auth=False, **self.creds)
290 self.is_proxy_used_cache = data["runningAsProxy"]
291
292 self.module.log("proxy: [%s]" % ("True" if self.is_proxy_used_cache else "False"))
293 except Exception as error:
294 self.module.fail_json(msg="Failed to retrieve the webservices about information! Array Id [%s]. "
295 "Error [%s]." % (self.ssid, to_native(error)))
296
297 return self.is_proxy_used_cache
298
299 def request(self, path, rest_api_path=DEFAULT_REST_API_PATH, rest_api_url=None, data=None, method='GET', headers=None, ignore_errors=False, timeout=None,
300 force_basic_auth=True, log_request=None, json_response=True):
301 """Issue an HTTP request to a url, retrieving an optional JSON response.
302
303 :param str path: web services rest api endpoint path (Example: storage-systems/1/graph).
304 Note that when the full url path is specified then that will be used without supplying the protocol,
305 hostname, port and rest path.
306 :param str rest_api_path: override the class DEFAULT_REST_API_PATH which is used to build the request URL.
307 :param str rest_api_url: override the class url member which contains the base url for web services.
308 :param data: data required for the request (data may be json or any python structured data)
309 :param str method: request method such as GET, POST, DELETE.
310 :param dict headers: dictionary containing request headers.
311 :param bool ignore_errors: forces the request to ignore any raised exceptions.
312 :param int timeout: duration of seconds before request finally times out.
313 :param bool force_basic_auth: Ensure that basic authentication is being used.
314 :param bool log_request: Log the request and response
315 :param bool json_response: Whether the response should be loaded as JSON, otherwise the response is return raw.
316 """
317 self._check_web_services_version()
318
319 if rest_api_url is None:
320 rest_api_url = self.url
321 if headers is None:
322 headers = self.DEFAULT_HEADERS
323 if timeout is None:
324 timeout = self.DEFAULT_TIMEOUT
325 if log_request is None:
326 log_request = self.log_requests
327
328 if not isinstance(data, str) and "Content-Type" in headers and headers["Content-Type"] == "application/json":
329 data = json.dumps(data)
330
331 if path.startswith("/"):
332 path = path[1:]
333 request_url = rest_api_url + rest_api_path + path
334
335 if log_request:
336 self.module.log(pformat(dict(url=request_url, data=data, method=method, headers=headers)))
337
338 response = self._request(url=request_url, data=data, method=method, headers=headers, last_mod_time=None,
339 timeout=timeout, http_agent=self.HTTP_AGENT, force_basic_auth=force_basic_auth,
340 ignore_errors=ignore_errors, json_response=json_response, **self.creds)
341 if log_request:
342 self.module.log(pformat(response))
343
344 return response
345
346 @staticmethod
347 def _request(url, data=None, headers=None, method='GET', use_proxy=True, force=False, last_mod_time=None,
348 timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None,
349 force_basic_auth=True, ignore_errors=False, json_response=True):
350 """Issue an HTTP request to a url, retrieving an optional JSON response."""
351
352 if headers is None:
353 headers = {"Content-Type": "application/json", "Accept": "application/json"}
354 headers.update({"netapp-client-type": "Ansible-%s" % ansible_version})
355
356 if not http_agent:
357 http_agent = "Ansible / %s" % ansible_version
358
359 try:
360 r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force,
361 last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
362 url_username=url_username, url_password=url_password, http_agent=http_agent,
363 force_basic_auth=force_basic_auth)
364 rc = r.getcode()
365 response = r.read()
366 if json_response and response:
367 response = json.loads(response)
368
369 except HTTPError as error:
370 rc = error.code
371 response = error.fp.read()
372 try:
373 if json_response:
374 response = json.loads(response)
375 except Exception:
376 pass
377
378 if not ignore_errors:
379 raise Exception(rc, response)
380 except ValueError as error:
381 pass
382
383 return rc, response
384
385
386 def create_multipart_formdata(files, fields=None, send_8kb=False):
387 """Create the data for a multipart/form request.
388
389 :param list(list) files: list of lists each containing (name, filename, path).
390 :param list(list) fields: list of lists each containing (key, value).
391 :param bool send_8kb: only sends the first 8kb of the files (default: False).
392 """
393 boundary = "---------------------------" + "".join([str(random.randint(0, 9)) for x in range(27)])
394 data_parts = list()
395 data = None
396
397 if six.PY2: # Generate payload for Python 2
398 newline = "\r\n"
399 if fields is not None:
400 for key, value in fields:
401 data_parts.extend(["--%s" % boundary,
402 'Content-Disposition: form-data; name="%s"' % key,
403 "",
404 value])
405
406 for name, filename, path in files:
407 with open(path, "rb") as fh:
408 value = fh.read(8192) if send_8kb else fh.read()
409
410 data_parts.extend(["--%s" % boundary,
411 'Content-Disposition: form-data; name="%s"; filename="%s"' % (name, filename),
412 "Content-Type: %s" % (mimetypes.guess_type(path)[0] or "application/octet-stream"),
413 "",
414 value])
415 data_parts.extend(["--%s--" % boundary, ""])
416 data = newline.join(data_parts)
417
418 else:
419 newline = six.b("\r\n")
420 if fields is not None:
421 for key, value in fields:
422 data_parts.extend([six.b("--%s" % boundary),
423 six.b('Content-Disposition: form-data; name="%s"' % key),
424 six.b(""),
425 six.b(value)])
426
427 for name, filename, path in files:
428 with open(path, "rb") as fh:
429 value = fh.read(8192) if send_8kb else fh.read()
430
431 data_parts.extend([six.b("--%s" % boundary),
432 six.b('Content-Disposition: form-data; name="%s"; filename="%s"' % (name, filename)),
433 six.b("Content-Type: %s" % (mimetypes.guess_type(path)[0] or "application/octet-stream")),
434 six.b(""),
435 value])
436 data_parts.extend([six.b("--%s--" % boundary), b""])
437 data = newline.join(data_parts)
438
439 headers = {
440 "Content-Type": "multipart/form-data; boundary=%s" % boundary,
441 "Content-Length": str(len(data))}
442
443 return headers, data
444
445
446 def request(url, data=None, headers=None, method='GET', use_proxy=True,
447 force=False, last_mod_time=None, timeout=10, validate_certs=True,
448 url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False):
449 """Issue an HTTP request to a url, retrieving an optional JSON response."""
450
451 if headers is None:
452 headers = {"Content-Type": "application/json", "Accept": "application/json"}
453 headers.update({"netapp-client-type": "Ansible-%s" % ansible_version})
454
455 if not http_agent:
456 http_agent = "Ansible / %s" % ansible_version
457
458 try:
459 r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy,
460 force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
461 url_username=url_username, url_password=url_password, http_agent=http_agent,
462 force_basic_auth=force_basic_auth)
463 except HTTPError as err:
464 r = err.fp
465
466 try:
467 raw_data = r.read()
468 if raw_data:
469 data = json.loads(raw_data)
470 else:
471 raw_data = None
472 except Exception:
473 if ignore_errors:
474 pass
475 else:
476 raise Exception(raw_data)
477
478 resp_code = r.getcode()
479
480 if resp_code >= 400 and not ignore_errors:
481 raise Exception(resp_code, data)
482 else:
483 return resp_code, data