Debian Codegraph @

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

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c) 2017, Sumit Kumar <[email protected]>
8 # Copyright (c) 2017, Michael Price <[email protected]>
9 # All rights reserved.
10 #
11 # Redistribution and use in source and binary forms, with or without modification,
12 # are permitted provided that the following conditions are met:
13 #
14 # * Redistributions of source code must retain the above copyright
15 # notice, this list of conditions and the following disclaimer.
16 # * Redistributions in binary form must reproduce the above copyright notice,
17 # this list of conditions and the following disclaimer in the documentation
18 # and/or other materials provided with the distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
28 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 from __future__ import absolute_import, division, print_function
30 __metaclass__ = type
31
32 import json
33 import os
34 import random
35 import mimetypes
36
37 from pprint import pformat
38 from ansible.module_utils import six
39 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
40 from ansible.module_utils.six.moves.urllib.error import HTTPError
41 from ansible.module_utils.urls import open_url
42 from ansible.module_utils.api import basic_auth_argument_spec
43 from ansible.module_utils._text import to_native
44
45 try:
46 from ansible.module_utils.ansible_release import __version__ as ansible_version
47 except ImportError:
48 ansible_version = 'unknown'
49
50 try:
51 from netapp_lib.api.zapi import zapi
52 HAS_NETAPP_LIB = True
53 except ImportError:
54 HAS_NETAPP_LIB = False
55
56 try:
57 import requests
58 HAS_REQUESTS = True
59 except ImportError:
60 HAS_REQUESTS = False
61
62 import ssl
63 try:
64 from urlparse import urlparse
65 except ImportError:
66 from urllib.parse import urlparse
67
68
69 HAS_SF_SDK = False
70 SF_BYTE_MAP = dict(
71 # Management GUI displays 1024 ** 3 as 1.1 GB, thus use 1000.
72 bytes=1,
73 b=1,
74 kb=1000,
75 mb=1000 ** 2,
76 gb=1000 ** 3,
77 tb=1000 ** 4,
78 pb=1000 ** 5,
79 eb=1000 ** 6,
80 zb=1000 ** 7,
81 yb=1000 ** 8
82 )
83
84 POW2_BYTE_MAP = dict(
85 # Here, 1 kb = 1024
86 bytes=1,
87 b=1,
88 kb=1024,
89 mb=1024 ** 2,
90 gb=1024 ** 3,
91 tb=1024 ** 4,
92 pb=1024 ** 5,
93 eb=1024 ** 6,
94 zb=1024 ** 7,
95 yb=1024 ** 8
96 )
97
98 try:
99 from solidfire.factory import ElementFactory
100
101 HAS_SF_SDK = True
102 except Exception:
103 HAS_SF_SDK = False
104
105
106 def has_netapp_lib():
107 return HAS_NETAPP_LIB
108
109
110 def has_sf_sdk():
111 return HAS_SF_SDK
112
113
114 def na_ontap_host_argument_spec():
115
116 return dict(
117 hostname=dict(required=True, type='str'),
118 username=dict(required=True, type='str', aliases=['user']),
119 password=dict(required=True, type='str', aliases=['pass'], no_log=True),
120 https=dict(required=False, type='bool', default=False),
121 validate_certs=dict(required=False, type='bool', default=True),
122 http_port=dict(required=False, type='int'),
123 ontapi=dict(required=False, type='int'),
124 use_rest=dict(required=False, type='str', default='Auto', choices=['Never', 'Always', 'Auto'])
125 )
126
127
128 def ontap_sf_host_argument_spec():
129
130 return dict(
131 hostname=dict(required=True, type='str'),
132 username=dict(required=True, type='str', aliases=['user']),
133 password=dict(required=True, type='str', aliases=['pass'], no_log=True)
134 )
135
136
137 def aws_cvs_host_argument_spec():
138
139 return dict(
140 api_url=dict(required=True, type='str'),
141 validate_certs=dict(required=False, type='bool', default=True),
142 api_key=dict(required=True, type='str'),
143 secret_key=dict(required=True, type='str')
144 )
145
146
147 def create_sf_connection(module, port=None):
148 hostname = module.params['hostname']
149 username = module.params['username']
150 password = module.params['password']
151
152 if HAS_SF_SDK and hostname and username and password:
153 try:
154 return_val = ElementFactory.create(hostname, username, password, port=port)
155 return return_val
156 except Exception:
157 raise Exception("Unable to create SF connection")
158 else:
159 module.fail_json(msg="the python SolidFire SDK module is required")
160
161
162 def setup_na_ontap_zapi(module, vserver=None):
163 hostname = module.params['hostname']
164 username = module.params['username']
165 password = module.params['password']
166 https = module.params['https']
167 validate_certs = module.params['validate_certs']
168 port = module.params['http_port']
169 version = module.params['ontapi']
170
171 if HAS_NETAPP_LIB:
172 # set up zapi
173 server = zapi.NaServer(hostname)
174 server.set_username(username)
175 server.set_password(password)
176 if vserver:
177 server.set_vserver(vserver)
178 if version:
179 minor = version
180 else:
181 minor = 110
182 server.set_api_version(major=1, minor=minor)
183 # default is HTTP
184 if https:
185 if port is None:
186 port = 443
187 transport_type = 'HTTPS'
188 # HACK to bypass certificate verification
189 if validate_certs is False:
190 if not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
191 ssl._create_default_https_context = ssl._create_unverified_context
192 else:
193 if port is None:
194 port = 80
195 transport_type = 'HTTP'
196 server.set_transport_type(transport_type)
197 server.set_port(port)
198 server.set_server_type('FILER')
199 return server
200 else:
201 module.fail_json(msg="the python NetApp-Lib module is required")
202
203
204 def setup_ontap_zapi(module, vserver=None):
205 hostname = module.params['hostname']
206 username = module.params['username']
207 password = module.params['password']
208
209 if HAS_NETAPP_LIB:
210 # set up zapi
211 server = zapi.NaServer(hostname)
212 server.set_username(username)
213 server.set_password(password)
214 if vserver:
215 server.set_vserver(vserver)
216 # Todo : Replace hard-coded values with configurable parameters.
217 server.set_api_version(major=1, minor=110)
218 server.set_port(80)
219 server.set_server_type('FILER')
220 server.set_transport_type('HTTP')
221 return server
222 else:
223 module.fail_json(msg="the python NetApp-Lib module is required")
224
225
226 def eseries_host_argument_spec():
227 """Retrieve a base argument specification common to all NetApp E-Series modules"""
228 argument_spec = basic_auth_argument_spec()
229 argument_spec.update(dict(
230 api_username=dict(type='str', required=True),
231 api_password=dict(type='str', required=True, no_log=True),
232 api_url=dict(type='str', required=True),
233 ssid=dict(type='str', required=False, default='1'),
234 validate_certs=dict(type='bool', required=False, default=True)
235 ))
236 return argument_spec
237
238
239 class NetAppESeriesModule(object):
240 """Base class for all NetApp E-Series modules.
241
242 Provides a set of common methods for NetApp E-Series modules, including version checking, mode (proxy, embedded)
243 verification, http requests, secure http redirection for embedded web services, and logging setup.
244
245 Be sure to add the following lines in the module's documentation section:
246 extends_documentation_fragment:
247 - netapp.eseries
248
249 :param dict(dict) ansible_options: dictionary of ansible option definitions
250 :param str web_services_version: minimally required web services rest api version (default value: "02.00.0000.0000")
251 :param bool supports_check_mode: whether the module will support the check_mode capabilities (default=False)
252 :param list(list) mutually_exclusive: list containing list(s) of mutually exclusive options (optional)
253 :param list(list) required_if: list containing list(s) containing the option, the option value, and then
254 a list of required options. (optional)
255 :param list(list) required_one_of: list containing list(s) of options for which at least one is required. (optional)
256 :param list(list) required_together: list containing list(s) of options that are required together. (optional)
257 :param bool log_requests: controls whether to log each request (default: True)
258 """
259 DEFAULT_TIMEOUT = 60
260 DEFAULT_SECURE_PORT = "8443"
261 DEFAULT_REST_API_PATH = "devmgr/v2/"
262 DEFAULT_REST_API_ABOUT_PATH = "devmgr/utils/about"
263 DEFAULT_HEADERS = {"Content-Type": "application/json", "Accept": "application/json",
264 "netapp-client-type": "Ansible-%s" % ansible_version}
265 HTTP_AGENT = "Ansible / %s" % ansible_version
266 SIZE_UNIT_MAP = dict(bytes=1, b=1, kb=1024, mb=1024**2, gb=1024**3, tb=1024**4,
267 pb=1024**5, eb=1024**6, zb=1024**7, yb=1024**8)
268
269 def __init__(self, ansible_options, web_services_version=None, supports_check_mode=False,
270 mutually_exclusive=None, required_if=None, required_one_of=None, required_together=None,
271 log_requests=True):
272 argument_spec = eseries_host_argument_spec()
273 argument_spec.update(ansible_options)
274
275 self.module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=supports_check_mode,
276 mutually_exclusive=mutually_exclusive, required_if=required_if,
277 required_one_of=required_one_of, required_together=required_together)
278
279 args = self.module.params
280 self.web_services_version = web_services_version if web_services_version else "02.00.0000.0000"
281 self.ssid = args["ssid"]
282 self.url = args["api_url"]
283 self.log_requests = log_requests
284 self.creds = dict(url_username=args["api_username"],
285 url_password=args["api_password"],
286 validate_certs=args["validate_certs"])
287
288 if not self.url.endswith("/"):
289 self.url += "/"
290
291 self.is_embedded_mode = None
292 self.is_web_services_valid_cache = None
293
294 def _check_web_services_version(self):
295 """Verify proxy or embedded web services meets minimum version required for module.
296
297 The minimum required web services version is evaluated against version supplied through the web services rest
298 api. AnsibleFailJson exception will be raised when the minimum is not met or exceeded.
299
300 This helper function will update the supplied api url if secure http is not used for embedded web services
301
302 :raise AnsibleFailJson: raised when the contacted api service does not meet the minimum required version.
303 """
304 if not self.is_web_services_valid_cache:
305
306 url_parts = urlparse(self.url)
307 if not url_parts.scheme or not url_parts.netloc:
308 self.module.fail_json(msg="Failed to provide valid API URL. Example: https://192.168.1.100:8443/devmgr/v2. URL [%s]." % self.url)
309
310 if url_parts.scheme not in ["http", "https"]:
311 self.module.fail_json(msg="Protocol must be http or https. URL [%s]." % self.url)
312
313 self.url = "%s://%s/" % (url_parts.scheme, url_parts.netloc)
314 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
315 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, ignore_errors=True, **self.creds)
316
317 if rc != 200:
318 self.module.warn("Failed to retrieve web services about information! Retrying with secure ports. Array Id [%s]." % self.ssid)
319 self.url = "https://%s:8443/" % url_parts.netloc.split(":")[0]
320 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
321 try:
322 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, **self.creds)
323 except Exception as error:
324 self.module.fail_json(msg="Failed to retrieve the webservices about information! Array Id [%s]. Error [%s]."
325 % (self.ssid, to_native(error)))
326
327 major, minor, other, revision = data["version"].split(".")
328 minimum_major, minimum_minor, other, minimum_revision = self.web_services_version.split(".")
329
330 if not (major > minimum_major or
331 (major == minimum_major and minor > minimum_minor) or
332 (major == minimum_major and minor == minimum_minor and revision >= minimum_revision)):
333 self.module.fail_json(msg="Web services version does not meet minimum version required. Current version: [%s]."
334 " Version required: [%s]." % (data["version"], self.web_services_version))
335
336 self.module.log("Web services rest api version met the minimum required version.")
337 self.is_web_services_valid_cache = True
338
339 def is_embedded(self):
340 """Determine whether web services server is the embedded web services.
341
342 If web services about endpoint fails based on an URLError then the request will be attempted again using
343 secure http.
344
345 :raise AnsibleFailJson: raised when web services about endpoint failed to be contacted.
346 :return bool: whether contacted web services is running from storage array (embedded) or from a proxy.
347 """
348 self._check_web_services_version()
349
350 if self.is_embedded_mode is None:
351 about_url = self.url + self.DEFAULT_REST_API_ABOUT_PATH
352 try:
353 rc, data = request(about_url, timeout=self.DEFAULT_TIMEOUT, headers=self.DEFAULT_HEADERS, **self.creds)
354 self.is_embedded_mode = not data["runningAsProxy"]
355 except Exception as error:
356 self.module.fail_json(msg="Failed to retrieve the webservices about information! Array Id [%s]. Error [%s]."
357 % (self.ssid, to_native(error)))
358
359 return self.is_embedded_mode
360
361 def request(self, path, data=None, method='GET', headers=None, ignore_errors=False):
362 """Issue an HTTP request to a url, retrieving an optional JSON response.
363
364 :param str path: web services rest api endpoint path (Example: storage-systems/1/graph). Note that when the
365 full url path is specified then that will be used without supplying the protocol, hostname, port and rest path.
366 :param data: data required for the request (data may be json or any python structured data)
367 :param str method: request method such as GET, POST, DELETE.
368 :param dict headers: dictionary containing request headers.
369 :param bool ignore_errors: forces the request to ignore any raised exceptions.
370 """
371 self._check_web_services_version()
372
373 if headers is None:
374 headers = self.DEFAULT_HEADERS
375
376 if not isinstance(data, str) and headers["Content-Type"] == "application/json":
377 data = json.dumps(data)
378
379 if path.startswith("/"):
380 path = path[1:]
381 request_url = self.url + self.DEFAULT_REST_API_PATH + path
382
383 if self.log_requests is True:
384 self.module.log(pformat(dict(url=request_url, data=data, method=method)))
385
386 return request(url=request_url, data=data, method=method, headers=headers, use_proxy=True, force=False, last_mod_time=None,
387 timeout=self.DEFAULT_TIMEOUT, http_agent=self.HTTP_AGENT, force_basic_auth=True, ignore_errors=ignore_errors, **self.creds)
388
389
390 def create_multipart_formdata(files, fields=None, send_8kb=False):
391 """Create the data for a multipart/form request.
392
393 :param list(list) files: list of lists each containing (name, filename, path).
394 :param list(list) fields: list of lists each containing (key, value).
395 :param bool send_8kb: only sends the first 8kb of the files (default: False).
396 """
397 boundary = "---------------------------" + "".join([str(random.randint(0, 9)) for x in range(27)])
398 data_parts = list()
399 data = None
400
401 if six.PY2: # Generate payload for Python 2
402 newline = "\r\n"
403 if fields is not None:
404 for key, value in fields:
405 data_parts.extend(["--%s" % boundary,
406 'Content-Disposition: form-data; name="%s"' % key,
407 "",
408 value])
409
410 for name, filename, path in files:
411 with open(path, "rb") as fh:
412 value = fh.read(8192) if send_8kb else fh.read()
413
414 data_parts.extend(["--%s" % boundary,
415 'Content-Disposition: form-data; name="%s"; filename="%s"' % (name, filename),
416 "Content-Type: %s" % (mimetypes.guess_type(path)[0] or "application/octet-stream"),
417 "",
418 value])
419 data_parts.extend(["--%s--" % boundary, ""])
420 data = newline.join(data_parts)
421
422 else:
423 newline = six.b("\r\n")
424 if fields is not None:
425 for key, value in fields:
426 data_parts.extend([six.b("--%s" % boundary),
427 six.b('Content-Disposition: form-data; name="%s"' % key),
428 six.b(""),
429 six.b(value)])
430
431 for name, filename, path in files:
432 with open(path, "rb") as fh:
433 value = fh.read(8192) if send_8kb else fh.read()
434
435 data_parts.extend([six.b("--%s" % boundary),
436 six.b('Content-Disposition: form-data; name="%s"; filename="%s"' % (name, filename)),
437 six.b("Content-Type: %s" % (mimetypes.guess_type(path)[0] or "application/octet-stream")),
438 six.b(""),
439 value])
440 data_parts.extend([six.b("--%s--" % boundary), b""])
441 data = newline.join(data_parts)
442
443 headers = {
444 "Content-Type": "multipart/form-data; boundary=%s" % boundary,
445 "Content-Length": str(len(data))}
446
447 return headers, data
448
449
450 def request(url, data=None, headers=None, method='GET', use_proxy=True,
451 force=False, last_mod_time=None, timeout=10, validate_certs=True,
452 url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False):
453 """Issue an HTTP request to a url, retrieving an optional JSON response."""
454
455 if headers is None:
456 headers = {"Content-Type": "application/json", "Accept": "application/json"}
457 headers.update({"netapp-client-type": "Ansible-%s" % ansible_version})
458
459 if not http_agent:
460 http_agent = "Ansible / %s" % ansible_version
461
462 try:
463 r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy,
464 force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
465 url_username=url_username, url_password=url_password, http_agent=http_agent,
466 force_basic_auth=force_basic_auth)
467 except HTTPError as err:
468 r = err.fp
469
470 try:
471 raw_data = r.read()
472 if raw_data:
473 data = json.loads(raw_data)
474 else:
475 raw_data = None
476 except Exception:
477 if ignore_errors:
478 pass
479 else:
480 raise Exception(raw_data)
481
482 resp_code = r.getcode()
483
484 if resp_code >= 400 and not ignore_errors:
485 raise Exception(resp_code, data)
486 else:
487 return resp_code, data
488
489
490 def ems_log_event(source, server, name="Ansible", id="12345", version=ansible_version,
491 category="Information", event="setup", autosupport="false"):
492 ems_log = zapi.NaElement('ems-autosupport-log')
493 # Host name invoking the API.
494 ems_log.add_new_child("computer-name", name)
495 # ID of event. A user defined event-id, range [0..2^32-2].
496 ems_log.add_new_child("event-id", id)
497 # Name of the application invoking the API.
498 ems_log.add_new_child("event-source", source)
499 # Version of application invoking the API.
500 ems_log.add_new_child("app-version", version)
501 # Application defined category of the event.
502 ems_log.add_new_child("category", category)
503 # Description of event to log. An application defined message to log.
504 ems_log.add_new_child("event-description", event)
505 ems_log.add_new_child("log-level", "6")
506 ems_log.add_new_child("auto-support", autosupport)
507 server.invoke_successfully(ems_log, True)
508
509
510 def get_cserver_zapi(server):
511 vserver_info = zapi.NaElement('vserver-get-iter')
512 query_details = zapi.NaElement.create_node_with_children('vserver-info', **{'vserver-type': 'admin'})
513 query = zapi.NaElement('query')
514 query.add_child_elem(query_details)
515 vserver_info.add_child_elem(query)
516 result = server.invoke_successfully(vserver_info,
517 enable_tunneling=False)
518 attribute_list = result.get_child_by_name('attributes-list')
519 vserver_list = attribute_list.get_child_by_name('vserver-info')
520 return vserver_list.get_child_content('vserver-name')
521
522
523 def get_cserver(connection, is_rest=False):
524 if not is_rest:
525 return get_cserver_zapi(connection)
526
527 params = {'fields': 'type'}
528 api = "private/cli/vserver"
529 json, error = connection.get(api, params)
530 if json is None or error is not None:
531 # exit if there is an error or no data
532 return None
533 vservers = json.get('records')
534 if vservers is not None:
535 for vserver in vservers:
536 if vserver['type'] == 'admin': # cluster admin
537 return vserver['vserver']
538 if len(vservers) == 1: # assume vserver admin
539 return vservers[0]['vserver']
540
541 return None
542
543
544 class OntapRestAPI(object):
545 def __init__(self, module, timeout=60):
546 self.module = module
547 self.username = self.module.params['username']
548 self.password = self.module.params['password']
549 self.hostname = self.module.params['hostname']
550 self.use_rest = self.module.params['use_rest']
551 self.verify = self.module.params['validate_certs']
552 self.timeout = timeout
553 self.url = 'https://' + self.hostname + '/api/'
554 self.errors = list()
555 self.debug_logs = list()
556 self.check_required_library()
557
558 def check_required_library(self):
559 if not HAS_REQUESTS:
560 self.module.fail_json(msg=missing_required_lib('requests'))
561
562 def send_request(self, method, api, params, json=None, return_status_code=False):
563 ''' send http request and process reponse, including error conditions '''
564 url = self.url + api
565 status_code = None
566 content = None
567 json_dict = None
568 json_error = None
569 error_details = None
570
571 def get_json(response):
572 ''' extract json, and error message if present '''
573 try:
574 json = response.json()
575 except ValueError:
576 return None, None
577 error = json.get('error')
578 return json, error
579
580 try:
581 response = requests.request(method, url, verify=self.verify, auth=(self.username, self.password), params=params, timeout=self.timeout, json=json)
582 content = response.content # for debug purposes
583 status_code = response.status_code
584 # If the response was successful, no Exception will be raised
585 response.raise_for_status()
586 json_dict, json_error = get_json(response)
587 except requests.exceptions.HTTPError as err:
588 __, json_error = get_json(response)
589 if json_error is None:
590 self.log_error(status_code, 'HTTP error: %s' % err)
591 error_details = str(err)
592 # If an error was reported in the json payload, it is handled below
593 except requests.exceptions.ConnectionError as err:
594 self.log_error(status_code, 'Connection error: %s' % err)
595 error_details = str(err)
596 except Exception as err:
597 self.log_error(status_code, 'Other error: %s' % err)
598 error_details = str(err)
599 if json_error is not None:
600 self.log_error(status_code, 'Endpoint error: %d: %s' % (status_code, json_error))
601 error_details = json_error
602 self.log_debug(status_code, content)
603 if return_status_code:
604 return status_code, error_details
605 return json_dict, error_details
606
607 def get(self, api, params):
608 method = 'GET'
609 return self.send_request(method, api, params)
610
611 def post(self, api, data, params=None):
612 method = 'POST'
613 return self.send_request(method, api, params, json=data)
614
615 def patch(self, api, data, params=None):
616 method = 'PATCH'
617 return self.send_request(method, api, params, json=data)
618
619 def delete(self, api, data, params=None):
620 method = 'DELETE'
621 return self.send_request(method, api, params, json=data)
622
623 def _is_rest(self, used_unsupported_rest_properties=None):
624 if self.use_rest == "Always":
625 if used_unsupported_rest_properties:
626 error = "REST API currently does not support '%s'" % \
627 ', '.join(used_unsupported_rest_properties)
628 return True, error
629 else:
630 return True, None
631 if self.use_rest == 'Never' or used_unsupported_rest_properties:
632 # force ZAPI if requested or if some parameter requires it
633 return False, None
634 method = 'HEAD'
635 api = 'cluster/software'
636 status_code, __ = self.send_request(method, api, params=None, return_status_code=True)
637 if status_code == 200:
638 return True, None
639 return False, None
640
641 def is_rest(self, used_unsupported_rest_properties=None):
642 ''' only return error if there is a reason to '''
643 use_rest, error = self._is_rest(used_unsupported_rest_properties)
644 if used_unsupported_rest_properties is None:
645 return use_rest
646 return use_rest, error
647
648 def log_error(self, status_code, message):
649 self.errors.append(message)
650 self.debug_logs.append((status_code, message))
651
652 def log_debug(self, status_code, content):
653 self.debug_logs.append((status_code, content))
654
655
656 class AwsCvsRestAPI(object):
657 def __init__(self, module, timeout=60):
658 self.module = module
659 self.api_key = self.module.params['api_key']
660 self.secret_key = self.module.params['secret_key']
661 self.api_url = self.module.params['api_url']
662 self.verify = self.module.params['validate_certs']
663 self.timeout = timeout
664 self.url = 'https://' + self.api_url + '/v1/'
665 self.check_required_library()
666
667 def check_required_library(self):
668 if not HAS_REQUESTS:
669 self.module.fail_json(msg=missing_required_lib('requests'))
670
671 def send_request(self, method, api, params, json=None):
672 ''' send http request and process reponse, including error conditions '''
673 url = self.url + api
674 status_code = None
675 content = None
676 json_dict = None
677 json_error = None
678 error_details = None
679 headers = {
680 'Content-type': "application/json",
681 'api-key': self.api_key,
682 'secret-key': self.secret_key,
683 'Cache-Control': "no-cache",
684 }
685
686 def get_json(response):
687 ''' extract json, and error message if present '''
688 try:
689 json = response.json()
690
691 except ValueError:
692 return None, None
693 success_code = [200, 201, 202]
694 if response.status_code not in success_code:
695 error = json.get('message')
696 else:
697 error = None
698 return json, error
699 try:
700 response = requests.request(method, url, headers=headers, timeout=self.timeout, json=json)
701 status_code = response.status_code
702 # If the response was successful, no Exception will be raised
703 json_dict, json_error = get_json(response)
704 except requests.exceptions.HTTPError as err:
705 __, json_error = get_json(response)
706 if json_error is None:
707 error_details = str(err)
708 except requests.exceptions.ConnectionError as err:
709 error_details = str(err)
710 except Exception as err:
711 error_details = str(err)
712 if json_error is not None:
713 error_details = json_error
714
715 return json_dict, error_details
716
717 # If an error was reported in the json payload, it is handled below
718 def get(self, api, params=None):
719 method = 'GET'
720 return self.send_request(method, api, params)
721
722 def post(self, api, data, params=None):
723 method = 'POST'
724 return self.send_request(method, api, params, json=data)
725
726 def patch(self, api, data, params=None):
727 method = 'PATCH'
728 return self.send_request(method, api, params, json=data)
729
730 def put(self, api, data, params=None):
731 method = 'PUT'
732 return self.send_request(method, api, params, json=data)
733
734 def delete(self, api, data, params=None):
735 method = 'DELETE'
736 return self.send_request(method, api, params, json=data)
737
738 def get_state(self, jobId):
739 """ Method to get the state of the job """
740 method = 'GET'
741 response, status_code = self.get('Jobs/%s' % jobId)
742 while str(response['state']) not in 'done':
743 response, status_code = self.get('Jobs/%s' % jobId)
744 return 'done'