| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
from __future__ import (absolute_import, division, print_function) |
| 30 |
|
| 31 |
__metaclass__ = type |
| 32 |
|
| 33 |
import json |
| 34 |
import os |
| 35 |
from ansible.module_utils.urls import open_url |
| 36 |
from ansible.module_utils.six.moves.urllib.parse import urlencode |
| 37 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import config_ipv6 |
| 38 |
|
| 39 |
|
| 40 |
class OpenURLResponse(object): |
| 41 |
"""Handles HTTPResponse""" |
| 42 |
|
| 43 |
def __init__(self, response): |
| 44 |
""" |
| 45 |
Initializes a new instance of the class. |
| 46 |
|
| 47 |
Args: |
| 48 |
response (object): The response object to read the body from. |
| 49 |
|
| 50 |
Returns: |
| 51 |
None |
| 52 |
""" |
| 53 |
self.body = None |
| 54 |
self.resp = response |
| 55 |
if self.resp: |
| 56 |
self.body = self.resp.read() |
| 57 |
|
| 58 |
@property |
| 59 |
def json_data(self): |
| 60 |
""" |
| 61 |
Returns the JSON data parsed from the `body` attribute of the object. |
| 62 |
|
| 63 |
Returns: |
| 64 |
dict: The parsed JSON data. |
| 65 |
|
| 66 |
Raises: |
| 67 |
ValueError: If the `body` attribute cannot be parsed as JSON. |
| 68 |
""" |
| 69 |
try: |
| 70 |
return json.loads(self.body) |
| 71 |
except ValueError: |
| 72 |
raise ValueError("Unable to parse json") |
| 73 |
|
| 74 |
@property |
| 75 |
def status_code(self): |
| 76 |
return self.resp.getcode() |
| 77 |
|
| 78 |
@property |
| 79 |
def success(self): |
| 80 |
status = self.status_code |
| 81 |
return status >= 200 & status <= 299 |
| 82 |
|
| 83 |
@property |
| 84 |
def token_header(self): |
| 85 |
return self.resp.headers.get('X-Auth-Token') |
| 86 |
|
| 87 |
|
| 88 |
class RestAPI: |
| 89 |
def __init__(self, root_uri, module_params, req_session=False, |
| 90 |
protocol="https", basic_headers=None): |
| 91 |
self.hostname = config_ipv6(str(module_params.get("hostname", "")).strip('][')) |
| 92 |
self.username = module_params.get("username") |
| 93 |
self.password = module_params.get("password") |
| 94 |
self.port = module_params.get("port") |
| 95 |
self.validate_certs = module_params.get("validate_certs") |
| 96 |
self.ca_path = module_params.get("ca_path") |
| 97 |
self.timeout = module_params.get("timeout") |
| 98 |
self.req_session = req_session |
| 99 |
self.session_id = None |
| 100 |
self.protocol = protocol |
| 101 |
self.root_uri = root_uri |
| 102 |
self._headers = basic_headers or {} |
| 103 |
|
| 104 |
def __build_url(self, path, query_param=None): |
| 105 |
url = '{0}://{1}:{2}'.format(self.protocol, self.hostname, self.port) |
| 106 |
if path: |
| 107 |
url = '{0}{1}'.format(url, path) |
| 108 |
if query_param: |
| 109 |
url += "?{0}".format(urlencode(query_param).replace('+', '%20')) |
| 110 |
return url |
| 111 |
|
| 112 |
def _get_omam_ca_env(self): |
| 113 |
"""Check if the value is set in REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE or OMAM_CA_BUNDLE or returns None""" |
| 114 |
return os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("CURL_CA_BUNDLE") or os.environ.get("OMAM_CA_BUNDLE") |
| 115 |
|
| 116 |
def _url_common_args_spec(self, method, api_timeout=None, headers=None): |
| 117 |
"""Creates an argument common spec""" |
| 118 |
base_headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} |
| 119 |
self._headers.update(base_headers) |
| 120 |
if isinstance(headers, dict): |
| 121 |
self._headers.update(headers) |
| 122 |
return { |
| 123 |
"method": method, |
| 124 |
"validate_certs": self.validate_certs, |
| 125 |
"ca_path": self.ca_path or self._get_omam_ca_env(), |
| 126 |
"use_proxy": True, |
| 127 |
"headers": self._headers, |
| 128 |
"timeout": api_timeout or self.timeout, |
| 129 |
"follow_redirects": 'all', |
| 130 |
} |
| 131 |
|
| 132 |
def _args_without_session(self, method, api_timeout, headers=None): |
| 133 |
"""Creates an argument spec in case of basic authentication""" |
| 134 |
url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers) |
| 135 |
url_kwargs["url_username"] = self.username |
| 136 |
url_kwargs["url_password"] = self.password |
| 137 |
url_kwargs["force_basic_auth"] = True |
| 138 |
return url_kwargs |
| 139 |
|
| 140 |
def _args_with_session(self, method, api_timeout, headers=None): |
| 141 |
"""Creates an argument spec, in case of authentication with session""" |
| 142 |
url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers) |
| 143 |
url_kwargs["force_basic_auth"] = False |
| 144 |
return url_kwargs |
| 145 |
|
| 146 |
def validate_input(self): |
| 147 |
if not (1 <= self.port <= 65535): |
| 148 |
raise ValueError("Invalid port number. Enter the valid port number.") |
| 149 |
if self.timeout is None or self.timeout <= 0: |
| 150 |
raise ValueError("Invalid timeout value. Enter the valid positive integer.") |
| 151 |
|
| 152 |
def _base_invoke_request(self, method, path, data=None, query_param=None, headers=None, |
| 153 |
api_timeout=None, dump=True, auth_token_header='X-Auth-Token'): |
| 154 |
""" |
| 155 |
Sends a request through open_url |
| 156 |
Returns :class:`OpenURLResponse` object. |
| 157 |
:arg method: HTTP verb to use for the request |
| 158 |
:arg path: path to request without query parameter |
| 159 |
:arg data: (optional) Payload to send with the request |
| 160 |
:arg query_param: (optional) Dictionary of query parameter to send with request |
| 161 |
:arg headers: (optional) Dictionary of HTTP Headers to send with the |
| 162 |
request |
| 163 |
:arg api_timeout: (optional) How long to wait for the server to send |
| 164 |
data before giving up |
| 165 |
:arg dump: (Optional) boolean value for dumping payload data. |
| 166 |
:returns: OpenURLResponse |
| 167 |
""" |
| 168 |
self.validate_input() |
| 169 |
if self.req_session and auth_token_header in self._headers: |
| 170 |
url_kwargs = self._args_with_session(method, api_timeout, headers=headers) |
| 171 |
else: |
| 172 |
url_kwargs = self._args_without_session(method, api_timeout, headers=headers) |
| 173 |
if data and dump: |
| 174 |
data = json.dumps(data) |
| 175 |
path = self.root_uri + path |
| 176 |
url = self.__build_url(path, query_param=query_param) |
| 177 |
resp = open_url(url, data=data, **url_kwargs) |
| 178 |
resp_data = OpenURLResponse(resp) |
| 179 |
return resp_data |
| 180 |
|
| 181 |
def __enter__(self): |
| 182 |
return self |
| 183 |
|
| 184 |
def __exit__(self, exc_type, exc_value, traceback): |
| 185 |
return False |