Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_job_info.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.4
7 # Copyright (C) 2020-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12 from __future__ import (absolute_import, division, print_function)
13 __metaclass__ = type
14
15 DOCUMENTATION = r'''
16 ---
17 module: ome_job_info
18 short_description: Get job details for a given job ID or an entire job queue on OpenMange Enterprise
19 version_added: "2.0.0"
20 description: This module retrieves job details for a given job ID or an entire job queue on OpenMange Enterprise.
21 extends_documentation_fragment:
22 - dellemc.openmanage.ome_auth_options
23 options:
24 job_id:
25 description: Unique ID of the job.
26 type: int
27 system_query_options:
28 description: Options for pagination of the output.
29 type: dict
30 suboptions:
31 top:
32 description: Number of records to return. Default value is 100.
33 type: int
34 skip:
35 description: Number of records to skip. Default value is 0.
36 type: int
37 filter:
38 description: Filter records by the values supported.
39 type: str
40 fetch_execution_history:
41 description:
42 - Fetches the execution history of the job.
43 - I(fetch_execution_history) is only applicable when valid I(job_id) is given.
44 - When C(true), fetches all the execution history details.
45 - When C(false), fetches only the job info and last execution details.
46 type: bool
47 default: false
48 requirements:
49 - "python >= 3.9.6"
50 author:
51 - "Jagadeesh N V (@jagadeeshnv)"
52 - "Abhishek Sinha (@Abhishek-Dell)"
53 - "Mangirish Kenkare(@MangirishK)"
54 notes:
55 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
56 - This module supports C(check_mode).
57 '''
58
59 EXAMPLES = r'''
60 ---
61 - name: Get all jobs details
62 dellemc.openmanage.ome_job_info:
63 hostname: "192.168.0.1"
64 username: "username"
65 password: "password"
66 ca_path: "/path/to/ca_cert.pem"
67
68 - name: Get job details for id
69 dellemc.openmanage.ome_job_info:
70 hostname: "192.168.0.1"
71 username: "username"
72 password: "password"
73 ca_path: "/path/to/ca_cert.pem"
74 job_id: 12345
75
76 - name: Get filtered job details
77 dellemc.openmanage.ome_job_info:
78 hostname: "192.168.0.1"
79 username: "username"
80 password: "password"
81 ca_path: "/path/to/ca_cert.pem"
82 system_query_options:
83 top: 2
84 skip: 1
85 filter: "JobType/Id eq 8"
86
87 - name: Get detail job execution history with last execution detail for a job.
88 dellemc.openmanage.ome_job_info:
89 hostname: "192.168.0.1"
90 username: "username"
91 password: "password"
92 ca_path: "/path/to/ca_cert.pem"
93 job_id: 12345
94 fetch_execution_history: true
95 '''
96
97 RETURN = r'''
98 ---
99 msg:
100 description: Overall status of the job facts operation.
101 returned: always
102 type: str
103 sample: "Successfully fetched the job info"
104 job_info:
105 description: Details of the OpenManage Enterprise jobs.
106 returned: success
107 type: dict
108 sample: {
109 "value": [
110 {
111 "Id": 10429,
112 "JobName": "Discovery-201",
113 "JobDescription": "Discovery-201",
114 "NextRun": null,
115 "LastRun": "2023-06-07 09:33:07.161",
116 "StartTime": null,
117 "EndTime": null,
118 "Schedule": "startnow",
119 "State": "Enabled",
120 "CreatedBy": "admin",
121 "UpdatedBy": "admin",
122 "Visible": true,
123 "Editable": true,
124 "Builtin": false,
125 "UserGenerated": true,
126 "Targets": [],
127 "Params": [],
128 "LastRunStatus": {
129 "Id": 2070,
130 "Name": "Failed"
131 },
132 "JobType": {
133 "Id": 101,
134 "Name": "Discovery_Task",
135 "Internal": false
136 },
137 "JobStatus": {
138 "Id": 2080,
139 "Name": "New"
140 },
141 "ExecutionHistories": [
142 {
143 "Id": 1243224,
144 "JobName": "Discovery-201",
145 "Progress": "100",
146 "StartTime": "2023-06-07 09:33:07.148",
147 "EndTime": "2023-06-07 09:33:08.403",
148 "LastUpdateTime": "2023-06-07 09:33:08.447185",
149 "ExecutedBy": "admin",
150 "JobId": 10429,
151 "JobStatus": {
152 "Id": 2070,
153 "Name": "Failed"
154 },
155 "ExecutionHistoryDetails": [
156 {
157 "Id": 1288519,
158 "Progress": "100",
159 "StartTime": "2023-06-07 09:33:07.525",
160 "EndTime": "2023-06-07 09:33:08.189",
161 "ElapsedTime": "00:00:00",
162 "Key": "198.168.0.1",
163 "Value": "Running\nDiscovery of target 198.168.0.1 started
164 .\nDiscovery target resolved to IP 198.168.0.1 .\n:
165 ========== EEMI Code: CGEN1009 ==========\nMessage:
166 Unable to perform the requested action because the device
167 management endpoint authentication over WSMAN, REDFISH failed.
168 \nRecommended actions: Make sure the credentials associated
169 with the device management endpoint are valid and retry the
170 operation.\n=======================================\nTask Failed.
171 Completed With Errors.",
172 "ExecutionHistoryId": 1243224,
173 "IdBaseEntity": 0,
174 "JobStatus": {
175 "Id": 2070,
176 "Name": "Failed"
177 }
178 },
179 {
180 "Id": 1288518,
181 "Progress": "100",
182 "StartTime": "2023-06-07 09:33:07.521",
183 "EndTime": "2023-06-07 09:33:08.313",
184 "ElapsedTime": "00:00:00",
185 "Key": "198.168.0.2",
186 "Value": "Running\nDiscovery of target 198.168.0.2 started.
187 \nDiscovery target resolved to IP 198.168.0.2 .\n:
188 ========== EEMI Code: CGEN1009 ==========\nMessage:
189 Unable to perform the requested action because the device
190 management endpoint authentication over WSMAN, REDFISH failed.
191 \nRecommended actions: Make sure the credentials associated
192 with the device management endpoint are valid and retry the
193 operation.\n=======================================\nTask Failed.
194 Completed With Errors.",
195 "ExecutionHistoryId": 1243224,
196 "IdBaseEntity": 0,
197 "JobStatus": {
198 "Id": 2070,
199 "Name": "Failed"
200 }
201 }
202 ]
203 },
204 {
205 "Id": 1243218,
206 "JobName": "Discovery-201",
207 "Progress": "100",
208 "StartTime": "2023-06-07 09:30:55.064",
209 "EndTime": "2023-06-07 09:30:56.338",
210 "LastUpdateTime": "2023-06-07 09:30:56.365294",
211 "ExecutedBy": "admin",
212 "JobId": 10429,
213 "JobStatus": {
214 "Id": 2070,
215 "Name": "Failed"
216 },
217 "ExecutionHistoryDetails": [
218 {
219 "Id": 1288512,
220 "Progress": "100",
221 "StartTime": "2023-06-07 09:30:55.441",
222 "EndTime": "2023-06-07 09:30:56.085",
223 "ElapsedTime": "00:00:00",
224 "Key": "198.168.0.1",
225 "Value": "Running\nDiscovery of target 198.168.0.1 started.
226 \nDiscovery target resolved to IP 198.168.0.1 .\n:
227 ========== EEMI Code: CGEN1009 ==========\nMessage:
228 Unable to perform the requested action because the device
229 management endpoint authentication over WSMAN, REDFISH failed.
230 \nRecommended actions: Make sure the credentials associated
231 with the device management endpoint are valid and retry the
232 operation.\n=======================================\nTask Failed.
233 Completed With Errors.",
234 "ExecutionHistoryId": 1243218,
235 "IdBaseEntity": 0,
236 "JobStatus": {
237 "Id": 2070,
238 "Name": "Failed"
239 }
240 },
241 {
242 "Id": 1288511,
243 "Progress": "100",
244 "StartTime": "2023-06-07 09:30:55.439",
245 "EndTime": "2023-06-07 09:30:56.21",
246 "ElapsedTime": "00:00:00",
247 "Key": "198.168.0.2",
248 "Value": "Running\nDiscovery of target 198.168.0.2 started.
249 \nDiscovery target resolved to IP 198.168.0.2 .\n:
250 ========== EEMI Code: CGEN1009 ==========\nMessage:
251 Unable to perform the requested action because the device
252 management endpoint authentication over WSMAN, REDFISH failed.
253 \nRecommended actions: Make sure the credentials associated
254 with the device management endpoint are valid and retry
255 the operation.\n=======================================\nTask Failed.
256 Completed With Errors.",
257 "ExecutionHistoryId": 1243218,
258 "IdBaseEntity": 0,
259 "JobStatus": {
260 "Id": 2070,
261 "Name": "Failed"
262 }
263 }
264 ]
265 }
266 ],
267 "LastExecutionDetail": {
268 "Id": 1288519,
269 "Progress": "100",
270 "StartTime": "2023-06-07 09:33:07.525",
271 "EndTime": "2023-06-07 09:33:08.189",
272 "ElapsedTime": null,
273 "Key": "198.168.0.1",
274 "Value": "Running\nDiscovery of target 198.168.0.1 started.
275 \nDiscovery target resolved to IP 198.168.0.1 .\n:
276 ========== EEMI Code: CGEN1009 ==========\nMessage:
277 Unable to perform the requested action because the device
278 management endpoint authentication over WSMAN, REDFISH failed.
279 \nRecommended actions: Make sure the credentials associated
280 with the device management endpoint are valid and retry the operation.
281 \n=======================================\nTask Failed.
282 Completed With Errors.",
283 "ExecutionHistoryId": 1243224,
284 "IdBaseEntity": 0,
285 "JobStatus": {
286 "Id": 2070,
287 "Name": "Failed"
288 }
289 }
290 }
291 ]
292 }
293 '''
294
295 import json
296 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
297 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import strip_substr_dict, remove_key
298 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
299 from ansible.module_utils.urls import ConnectionError, SSLValidationError
300
301 JOBS_URI = "JobService/Jobs"
302 EXECUTION_HISTORIES_URI = "JobService/Jobs({0})/ExecutionHistories"
303 LAST_EXECUTION_DETAIL_URI = "JobService/Jobs({0})/LastExecutionDetail"
304
305
306 def _get_query_parameters(module_params):
307 """Builds query parameter
308 :returns: dictionary, which builds the query format
309 eg : {"$filter": "JobType/Id eq 8"}
310 """
311 system_query_options_param = module_params.get("system_query_options")
312 query_parameter = {}
313 if system_query_options_param:
314 query_parameter = dict([("$" + k, v) for k, v in system_query_options_param.items() if v is not None])
315 return query_parameter
316
317
318 def get_uri_detail(rest_obj, uri):
319 try:
320 result = []
321 resp = rest_obj.invoke_request('GET', uri)
322 json_data = resp.json_data
323 if value := json_data.get('value'):
324 for each_element in value:
325 each_element.get('JobStatus', {}).pop('@odata.type', None)
326 execution_history_detail_uri = each_element.get('[email protected]', '')[5:]
327 if execution_history_detail_uri:
328 execution_history_detail = get_uri_detail(rest_obj, execution_history_detail_uri)
329 each_element.update({"ExecutionHistoryDetails": execution_history_detail})
330 result.append(strip_substr_dict(each_element))
331 else:
332 json_data.get('JobStatus', {}).pop('@odata.type', None)
333 result = strip_substr_dict(json_data)
334 except Exception:
335 pass
336 return result
337
338
339 def get_execution_history_of_a_job(rest_obj, job_id):
340 try:
341 execution_histories = get_uri_detail(
342 rest_obj, EXECUTION_HISTORIES_URI.format(job_id))
343 except Exception:
344 pass
345 return execution_histories
346
347
348 def last_execution_detail_of_a_job(rest_obj, job_id):
349 try:
350 last_execution_detail = get_uri_detail(
351 rest_obj, LAST_EXECUTION_DETAIL_URI.format(job_id))
352 except Exception:
353 pass
354 return last_execution_detail
355
356
357 def main():
358 specs = {
359 "job_id": {"required": False, "type": 'int'},
360 "system_query_options": {"required": False, "type": 'dict', "options": {
361 "top": {"type": 'int', "required": False},
362 "skip": {"type": 'int', "required": False},
363 "filter": {"type": 'str', "required": False},
364 }},
365 "fetch_execution_history": {"type": 'bool', "default": False},
366 }
367
368 module = OmeAnsibleModule(
369 argument_spec=specs,
370 supports_check_mode=True
371 )
372
373 try:
374 with RestOME(module.params, req_session=True) as rest_obj:
375 resp_status = []
376 if module.params.get("job_id") is not None:
377 # Fetch specific job
378 job_id = module.params.get("job_id")
379 jpath = "{0}({1})".format(JOBS_URI, job_id)
380 resp = rest_obj.invoke_request('GET', jpath)
381 job_facts = remove_key(resp.json_data)
382 execution_detail = []
383 if module.params.get("fetch_execution_history"):
384 execution_detail = get_execution_history_of_a_job(rest_obj, job_id)
385 last_execution = last_execution_detail_of_a_job(rest_obj, job_id)
386 job_facts.update({'ExecutionHistories': execution_detail,
387 'LastExecutionDetail': last_execution})
388 resp_status.append(resp.status_code)
389 else:
390 # query applicable only for all jobs list fetching
391 query_param = _get_query_parameters(module.params)
392 if query_param:
393 resp = rest_obj.invoke_request('GET', JOBS_URI, query_param=query_param)
394 job_facts = resp.json_data
395 job_facts = remove_key(job_facts)
396 resp_status.append(resp.status_code)
397 else:
398 # Fetch all jobs, filter and pagination options
399 job_report = rest_obj.get_all_report_details(JOBS_URI)
400 job_facts = {"value": job_report["report_list"]}
401 job_facts = remove_key(job_facts)
402 if len(job_facts["value"]) > 0:
403 resp_status.append(200)
404 for each_value in job_facts["value"]:
405 job_id = each_value["Id"] if "Id" in each_value else None
406 last_execution = last_execution_detail_of_a_job(rest_obj, job_id)
407 each_value.update({'ExecutionHistories': [],
408 'LastExecutionDetail': last_execution})
409 except HTTPError as httperr:
410 module.exit_json(msg=str(httperr), job_info=json.load(httperr), failed=True)
411 except URLError as err:
412 module.exit_json(msg=str(err), unreachable=True)
413 except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err:
414 module.exit_json(msg=str(err), failed=True)
415 if 200 in resp_status:
416 module.exit_json(msg="Successfully fetched the job info", job_info=job_facts)
417 else:
418 module.exit_json(msg="Failed to fetch the job info", failed=True)
419
420
421 if __name__ == '__main__':
422 main()