| 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 |
import time |
| 36 |
from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError |
| 37 |
from ansible.module_utils.common.parameters import env_fallback |
| 38 |
from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError |
| 39 |
from ansible.module_utils.six.moves.urllib.parse import urlencode |
| 40 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import config_ipv6 |
| 41 |
from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import strip_substr_dict |
| 42 |
from ansible.module_utils.basic import AnsibleModule |
| 43 |
|
| 44 |
ome_auth_params = { |
| 45 |
"hostname": {"required": True, "type": "str"}, |
| 46 |
"username": {"required": True, "type": "str", "fallback": (env_fallback, ['OME_USERNAME'])}, |
| 47 |
"password": {"required": True, "type": "str", "no_log": True, "fallback": (env_fallback, ['OME_PASSWORD'])}, |
| 48 |
"port": {"type": "int", "default": 443}, |
| 49 |
"validate_certs": {"type": "bool", "default": True}, |
| 50 |
"ca_path": {"type": "path"}, |
| 51 |
"timeout": {"type": "int", "default": 30}, |
| 52 |
} |
| 53 |
|
| 54 |
SESSION_RESOURCE_COLLECTION = { |
| 55 |
"SESSION": "SessionService/Sessions", |
| 56 |
"SESSION_ID": "SessionService/Sessions('{Id}')", |
| 57 |
} |
| 58 |
|
| 59 |
JOB_URI = "JobService/Jobs({job_id})" |
| 60 |
JOB_SERVICE_URI = "JobService/Jobs" |
| 61 |
HOST_UNRESOLVED_MSG = "Unable to resolve hostname or IP {0}." |
| 62 |
JOB_EXEC_HISTORY = "JobService/Jobs({job_id})/ExecutionHistories" |
| 63 |
|
| 64 |
|
| 65 |
class OpenURLResponse(object): |
| 66 |
"""Handles HTTPResponse""" |
| 67 |
|
| 68 |
def __init__(self, resp): |
| 69 |
self.body = None |
| 70 |
self.resp = resp |
| 71 |
if self.resp: |
| 72 |
self.body = self.resp.read() |
| 73 |
|
| 74 |
@property |
| 75 |
def json_data(self): |
| 76 |
try: |
| 77 |
return json.loads(self.body) |
| 78 |
except ValueError: |
| 79 |
raise ValueError("Unable to parse json") |
| 80 |
|
| 81 |
@property |
| 82 |
def status_code(self): |
| 83 |
return self.resp.getcode() |
| 84 |
|
| 85 |
@property |
| 86 |
def success(self): |
| 87 |
return self.status_code in (200, 201, 202, 204) |
| 88 |
|
| 89 |
@property |
| 90 |
def token_header(self): |
| 91 |
return self.resp.headers.get('X-Auth-Token') |
| 92 |
|
| 93 |
|
| 94 |
class RestOME(object): |
| 95 |
"""Handles OME API requests""" |
| 96 |
|
| 97 |
def __init__(self, module_params=None, req_session=False): |
| 98 |
self.module_params = module_params |
| 99 |
self.hostname = str(self.module_params["hostname"]).strip('][') |
| 100 |
self.username = self.module_params["username"] |
| 101 |
self.password = self.module_params["password"] |
| 102 |
self.x_auth_token = self.module_params.get("x_auth_token") |
| 103 |
self.port = self.module_params["port"] |
| 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.req_session = req_session |
| 108 |
self.session_id = None |
| 109 |
self.protocol = 'https' |
| 110 |
self._headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} |
| 111 |
self.hostname = config_ipv6(self.hostname) |
| 112 |
|
| 113 |
def _get_base_url(self): |
| 114 |
"""builds base url""" |
| 115 |
return '{0}://{1}:{2}/api'.format(self.protocol, self.hostname, self.port) |
| 116 |
|
| 117 |
def _build_url(self, path, query_param=None): |
| 118 |
"""builds complete url""" |
| 119 |
url = path |
| 120 |
base_uri = self._get_base_url() |
| 121 |
if path: |
| 122 |
url = '{0}/{1}'.format(base_uri, path) |
| 123 |
if query_param: |
| 124 |
"""Ome filtering does not work as expected when '+' is passed, |
| 125 |
urlencode will encode spaces as '+' so replace it to '%20'""" |
| 126 |
url += "?{0}".format(urlencode(query_param).replace('+', '%20')) |
| 127 |
return url |
| 128 |
|
| 129 |
def _url_common_args_spec(self, method, api_timeout, headers=None): |
| 130 |
"""Creates an argument common spec""" |
| 131 |
req_header = self._headers |
| 132 |
if headers: |
| 133 |
req_header.update(headers) |
| 134 |
if api_timeout is None: |
| 135 |
api_timeout = self.timeout |
| 136 |
if self.ca_path is None: |
| 137 |
self.ca_path = self._get_omam_ca_env() |
| 138 |
url_kwargs = { |
| 139 |
"method": method, |
| 140 |
"validate_certs": self.validate_certs, |
| 141 |
"ca_path": self.ca_path, |
| 142 |
"use_proxy": True, |
| 143 |
"headers": req_header, |
| 144 |
"timeout": api_timeout, |
| 145 |
"follow_redirects": 'all', |
| 146 |
} |
| 147 |
return url_kwargs |
| 148 |
|
| 149 |
def _args_without_session(self, 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 |
url_kwargs["url_username"] = self.username |
| 156 |
url_kwargs["url_password"] = self.password |
| 157 |
url_kwargs["force_basic_auth"] = True |
| 158 |
return url_kwargs |
| 159 |
|
| 160 |
def _args_with_session(self, method, api_timeout, headers=None): |
| 161 |
"""Creates an argument spec, in case of authentication with session""" |
| 162 |
url_kwargs = self._url_common_args_spec(method, api_timeout, headers=headers) |
| 163 |
url_kwargs["force_basic_auth"] = False |
| 164 |
return url_kwargs |
| 165 |
|
| 166 |
def invoke_request(self, method, path, data=None, query_param=None, headers=None, |
| 167 |
api_timeout=None, dump=True): |
| 168 |
""" |
| 169 |
Sends a request through open_url |
| 170 |
Returns :class:`OpenURLResponse` object. |
| 171 |
:arg method: HTTP verb to use for the request |
| 172 |
:arg path: path to request without query parameter |
| 173 |
:arg data: (optional) Payload to send with the request |
| 174 |
:arg query_param: (optional) Dictionary of query parameter to send with request |
| 175 |
:arg headers: (optional) Dictionary of HTTP Headers to send with the |
| 176 |
request |
| 177 |
:arg api_timeout: (optional) How long to wait for the server to send |
| 178 |
data before giving up |
| 179 |
:arg dump: (Optional) boolean value for dumping payload data. |
| 180 |
:returns: OpenURLResponse |
| 181 |
""" |
| 182 |
try: |
| 183 |
if 'X-Auth-Token' in self._headers: |
| 184 |
url_kwargs = self._args_with_session(method, api_timeout, headers=headers) |
| 185 |
else: |
| 186 |
url_kwargs = self._args_without_session(method, api_timeout, headers=headers) |
| 187 |
if data and dump: |
| 188 |
data = json.dumps(data) |
| 189 |
url = self._build_url(path, query_param=query_param) |
| 190 |
resp = open_url(url, data=data, **url_kwargs) |
| 191 |
resp_data = OpenURLResponse(resp) |
| 192 |
except (HTTPError, URLError, SSLValidationError, ConnectionError) as err: |
| 193 |
raise err |
| 194 |
return resp_data |
| 195 |
|
| 196 |
def __enter__(self): |
| 197 |
"""Creates sessions by passing it to header""" |
| 198 |
if self.req_session and not self.x_auth_token: |
| 199 |
payload = {'UserName': self.username, |
| 200 |
'Password': self.password, |
| 201 |
'SessionType': 'API', } |
| 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.token_header |
| 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""" |
| 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 |
def get_all_report_details(self, uri): |
| 222 |
""" |
| 223 |
This implementation mainly dependent on '@odata.count' value. |
| 224 |
Currently first request without query string, always returns total number of available |
| 225 |
reports in '@odata.count'. |
| 226 |
""" |
| 227 |
try: |
| 228 |
resp = self.invoke_request('GET', uri) |
| 229 |
data = resp.json_data |
| 230 |
report_list = data["value"] |
| 231 |
total_count = data['@odata.count'] |
| 232 |
remaining_count = total_count - len(report_list) |
| 233 |
first_page_count = len(report_list) |
| 234 |
while remaining_count > 0: |
| 235 |
resp = self.invoke_request('GET', uri, |
| 236 |
query_param={"$top": first_page_count, "$skip": len(report_list)}) |
| 237 |
data = resp.json_data |
| 238 |
value = data["value"] |
| 239 |
report_list.extend(value) |
| 240 |
remaining_count = remaining_count - len(value) |
| 241 |
return {"resp_obj": resp, "report_list": report_list} |
| 242 |
except (URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError) as err: |
| 243 |
raise err |
| 244 |
|
| 245 |
def get_job_type_id(self, jobtype_name): |
| 246 |
"""This provides an ID of the job type.""" |
| 247 |
job_type_id = None |
| 248 |
resp = self.invoke_request('GET', "JobService/JobTypes") |
| 249 |
data = resp.json_data["value"] |
| 250 |
for each in data: |
| 251 |
if each["Name"] == jobtype_name: |
| 252 |
job_type_id = each["Id"] |
| 253 |
break |
| 254 |
return job_type_id |
| 255 |
|
| 256 |
def get_device_id_from_service_tag(self, service_tag): |
| 257 |
""" |
| 258 |
:param service_tag: service tag of the device |
| 259 |
:return: dict |
| 260 |
Id: int: device id |
| 261 |
value: dict: device id details |
| 262 |
not_found_msg: str: message if service tag not found |
| 263 |
""" |
| 264 |
device_id = None |
| 265 |
query = "DeviceServiceTag eq '{0}'".format(service_tag) |
| 266 |
response = self.invoke_request("GET", "DeviceService/Devices", query_param={"$filter": query}) |
| 267 |
value = response.json_data.get("value", []) |
| 268 |
device_info = {} |
| 269 |
if value: |
| 270 |
device_info = value[0] |
| 271 |
device_id = device_info["Id"] |
| 272 |
return {"Id": device_id, "value": device_info} |
| 273 |
|
| 274 |
def get_all_items_with_pagination(self, uri, query_param=None): |
| 275 |
""" |
| 276 |
This implementation mainly to get all available items from ome for pagination |
| 277 |
supported GET uri |
| 278 |
:param uri: uri which supports pagination |
| 279 |
:return: dict. |
| 280 |
""" |
| 281 |
try: |
| 282 |
resp = self.invoke_request('GET', uri, query_param=query_param) |
| 283 |
data = resp.json_data |
| 284 |
total_items = data.get("value", []) |
| 285 |
total_count = data.get('@odata.count', 0) |
| 286 |
next_link = data.get('@odata.nextLink', '') |
| 287 |
while next_link: |
| 288 |
resp = self.invoke_request('GET', next_link.split('/api')[-1]) |
| 289 |
data = resp.json_data |
| 290 |
value = data["value"] |
| 291 |
next_link = data.get('@odata.nextLink', '') |
| 292 |
total_items.extend(value) |
| 293 |
return {"total_count": total_count, "value": total_items} |
| 294 |
except (URLError, HTTPError, SSLValidationError, ConnectionError, TypeError, ValueError) as err: |
| 295 |
raise err |
| 296 |
|
| 297 |
def get_device_type(self): |
| 298 |
""" |
| 299 |
Returns device type map where as key is type and value is type name |
| 300 |
eg: {1000: "SERVER", 2000: "CHASSIS", 4000: "NETWORK_IOM", "8000": "STORAGE_IOM", 3000: "STORAGE"} |
| 301 |
:return: dict, first item dict gives device type map |
| 302 |
""" |
| 303 |
device_map = {} |
| 304 |
response = self.invoke_request("GET", "DeviceService/DeviceType") |
| 305 |
if response.json_data.get("value"): |
| 306 |
device_map = dict([(item["DeviceType"], item["Name"]) for item in response.json_data["value"]]) |
| 307 |
return device_map |
| 308 |
|
| 309 |
def get_job_info(self, job_id): |
| 310 |
try: |
| 311 |
job_status_map = { |
| 312 |
2020: "Scheduled", 2030: "Queued", 2040: "Starting", 2050: "Running", 2060: "Completed", |
| 313 |
2070: "Failed", 2090: "Warning", 2080: "New", 2100: "Aborted", 2101: "Paused", 2102: "Stopped", |
| 314 |
2103: "Canceled" |
| 315 |
} |
| 316 |
failed_job_status = [2070, 2090, 2100, 2101, 2102, 2103] |
| 317 |
job_url = JOB_URI.format(job_id=job_id) |
| 318 |
job_resp = self.invoke_request('GET', job_url) |
| 319 |
job_dict = job_resp.json_data |
| 320 |
job_status = job_dict['LastRunStatus']['Id'] |
| 321 |
if job_status in [2060, 2020]: |
| 322 |
job_failed = False |
| 323 |
message = "Job {0} successfully.".format(job_status_map[job_status]) |
| 324 |
exit_poll = True |
| 325 |
return exit_poll, job_failed, message |
| 326 |
elif job_status in failed_job_status: |
| 327 |
exit_poll = True |
| 328 |
job_failed = True |
| 329 |
message = "Job is in {0} state, and is not completed.".format(job_status_map[job_status]) |
| 330 |
return exit_poll, job_failed, message |
| 331 |
return False, False, None |
| 332 |
except HTTPError: |
| 333 |
job_failed = True |
| 334 |
message = "Unable to track the job status of {0}.".format(job_id) |
| 335 |
exit_poll = True |
| 336 |
return exit_poll, job_failed, message |
| 337 |
|
| 338 |
def job_tracking(self, job_id, job_wait_sec=600, sleep_time=60): |
| 339 |
""" |
| 340 |
job_id: job id |
| 341 |
job_wait_sec: Maximum time to wait to fetch the final job details in seconds |
| 342 |
sleep_time: Maximum time to sleep in seconds in each job details fetch |
| 343 |
""" |
| 344 |
max_sleep_time = job_wait_sec |
| 345 |
sleep_interval = sleep_time |
| 346 |
while max_sleep_time: |
| 347 |
if max_sleep_time > sleep_interval: |
| 348 |
max_sleep_time = max_sleep_time - sleep_interval |
| 349 |
else: |
| 350 |
sleep_interval = max_sleep_time |
| 351 |
max_sleep_time = 0 |
| 352 |
time.sleep(sleep_interval) |
| 353 |
exit_poll, job_failed, job_message = self.get_job_info(job_id) |
| 354 |
if exit_poll is True: |
| 355 |
return job_failed, job_message |
| 356 |
return True, "The job is not complete after {0} seconds.".format(job_wait_sec) |
| 357 |
|
| 358 |
def strip_substr_dict(self, odata_dict, chkstr='@odata.'): |
| 359 |
cp = odata_dict.copy() |
| 360 |
klist = cp.keys() |
| 361 |
for k in klist: |
| 362 |
if chkstr in str(k).lower(): |
| 363 |
odata_dict.pop(k) |
| 364 |
return odata_dict |
| 365 |
|
| 366 |
def job_submission(self, job_name, job_desc, targets, params, job_type, |
| 367 |
schedule="startnow", state="Enabled"): |
| 368 |
job_payload = {"JobName": job_name, "JobDescription": job_desc, |
| 369 |
"Schedule": schedule, "State": state, "Targets": targets, |
| 370 |
"Params": params, "JobType": job_type} |
| 371 |
response = self.invoke_request("POST", JOB_SERVICE_URI, data=job_payload) |
| 372 |
return response |
| 373 |
|
| 374 |
def test_network_connection(self, share_address, share_path, share_type, |
| 375 |
share_user=None, share_password=None, share_domain=None): |
| 376 |
job_type = {"Id": 56, "Name": "ValidateNWFileShare_Task"} |
| 377 |
params = [ |
| 378 |
{"Key": "checkPathOnly", "Value": "false"}, |
| 379 |
{"Key": "shareType", "Value": share_type}, |
| 380 |
{"Key": "ShareNetworkFilePath", "Value": share_path}, |
| 381 |
{"Key": "shareAddress", "Value": share_address}, |
| 382 |
{"Key": "testShareWriteAccess", "Value": "true"} |
| 383 |
] |
| 384 |
if share_user is not None: |
| 385 |
params.append({"Key": "UserName", "Value": share_user}) |
| 386 |
if share_password is not None: |
| 387 |
params.append({"Key": "Password", "Value": share_password}) |
| 388 |
if share_domain is not None: |
| 389 |
params.append({"Key": "domainName", "Value": share_domain}) |
| 390 |
job_response = self.job_submission("Validate Share", "Validate Share", [], params, job_type) |
| 391 |
return job_response |
| 392 |
|
| 393 |
def check_existing_job_state(self, job_type_name): |
| 394 |
query_param = {"$filter": "LastRunStatus/Id eq 2030 or LastRunStatus/Id eq 2040 or LastRunStatus/Id eq 2050"} |
| 395 |
job_resp = self.invoke_request("GET", JOB_SERVICE_URI, query_param=query_param) |
| 396 |
job_lst = job_resp.json_data["value"] if job_resp.json_data.get("value") is not None else [] |
| 397 |
for job in job_lst: |
| 398 |
if job["JobType"]["Name"] == job_type_name: |
| 399 |
job_allowed = False |
| 400 |
available_jobs = job |
| 401 |
break |
| 402 |
else: |
| 403 |
job_allowed = True |
| 404 |
available_jobs = job_lst |
| 405 |
return job_allowed, available_jobs |
| 406 |
|
| 407 |
def _get_omam_ca_env(self): |
| 408 |
"""Check if the value is set in REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE or OMAM_CA_BUNDLE or returns None""" |
| 409 |
return os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("CURL_CA_BUNDLE") or os.environ.get("OMAM_CA_BUNDLE") |
| 410 |
|
| 411 |
def get_job_execution_details(self, job_id): |
| 412 |
try: |
| 413 |
job_detail_status = [] |
| 414 |
resp = self.invoke_request('GET', JOB_EXEC_HISTORY.format(job_id=job_id)) |
| 415 |
ex_hist = resp.json_data.get('value') |
| 416 |
|
| 417 |
tmp_dict = dict((x["StartTime"], x["Id"]) for x in ex_hist) |
| 418 |
sorted_dates = sorted(tmp_dict.keys()) |
| 419 |
ex_url = JOB_EXEC_HISTORY.format(job_id=job_id) + "({0})/ExecutionHistoryDetails".format(tmp_dict[sorted_dates[-1]]) |
| 420 |
all_exec = self.get_all_items_with_pagination(ex_url) |
| 421 |
for jb_ip in all_exec.get('value'): |
| 422 |
jb_ip = strip_substr_dict(jb_ip) |
| 423 |
jb_ip.get('JobStatus', {}).pop('@odata.type', None) |
| 424 |
job_detail_status.append(jb_ip) |
| 425 |
except Exception: |
| 426 |
pass |
| 427 |
return job_detail_status |
| 428 |
|
| 429 |
|
| 430 |
class OmeAnsibleModule(AnsibleModule): |
| 431 |
def __init__(self, argument_spec, bypass_checks=False, no_log=False, |
| 432 |
mutually_exclusive=None, required_together=None, |
| 433 |
required_one_of=None, add_file_common_args=False, |
| 434 |
supports_check_mode=False, required_if=None, required_by=None): |
| 435 |
ome_argument_spec = { |
| 436 |
"hostname": {"required": True, "type": "str"}, |
| 437 |
"username": {"required": False, "type": "str", "fallback": (env_fallback, ['OME_USERNAME'])}, |
| 438 |
"password": {"required": False, "type": "str", "no_log": True, "fallback": (env_fallback, ['OME_PASSWORD'])}, |
| 439 |
"x_auth_token": {"required": False, "type": "str", "no_log": True, "fallback": (env_fallback, ['OME_X_AUTH_TOKEN'])}, |
| 440 |
"port": {"type": "int", "default": 443}, |
| 441 |
"validate_certs": {"type": "bool", "default": True}, |
| 442 |
"ca_path": {"type": "path"}, |
| 443 |
"timeout": {"type": "int", "default": 30}, |
| 444 |
} |
| 445 |
argument_spec.update(ome_argument_spec) |
| 446 |
|
| 447 |
auth_mutually_exclusive = [("username", "x_auth_token"), ("password", "x_auth_token")] |
| 448 |
auth_required_one_of = [("username", "x_auth_token")] |
| 449 |
auth_required_together = [("username", "password")] |
| 450 |
|
| 451 |
if mutually_exclusive is None: |
| 452 |
mutually_exclusive = [] |
| 453 |
mutually_exclusive.extend(auth_mutually_exclusive) |
| 454 |
if required_together is None: |
| 455 |
required_together = [] |
| 456 |
required_together.extend(auth_required_together) |
| 457 |
if required_one_of is None: |
| 458 |
required_one_of = [] |
| 459 |
required_one_of.extend(auth_required_one_of) |
| 460 |
if required_by is None: |
| 461 |
required_by = {} |
| 462 |
|
| 463 |
super().__init__(argument_spec, bypass_checks, no_log, |
| 464 |
mutually_exclusive, required_together, |
| 465 |
required_one_of, add_file_common_args, |
| 466 |
supports_check_mode, required_if, required_by) |