Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2021-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+
10 # see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt
11 #
12
13
14 from __future__ import (absolute_import, division, print_function)
15
16 __metaclass__ = type
17
18 DOCUMENTATION = r"""
19 ---
20 module: redfish_event_subscription
21 short_description: Manage Redfish Subscriptions
22 version_added: "4.1.0"
23 description:
24 This module allows to add or delete Redfish Event subscriptions.
25 extends_documentation_fragment:
26 - dellemc.openmanage.redfish_auth_options
27 options:
28 destination:
29 description:
30 - The HTTPS URI of the destination to send events.
31 - HTTPS is required.
32 type: str
33 required: true
34 event_type:
35 description:
36 - Specifies the event type to be subscribed.
37 - C(Alert) used to subscribe for alert.
38 - C(MetricReport) used to subscribe for the metrics report.
39 type: str
40 default: Alert
41 choices: [Alert, MetricReport]
42 event_format_type:
43 description:
44 - Specifies the format type of the event to be subscribed.
45 - C(Event) used to subscribe for Event format type.
46 - C(MetricReport) used to subscribe for the metrics report format type.
47 type: str
48 default: Event
49 choices: [Event, MetricReport]
50 state:
51 description:
52 - C(present) adds new event subscription.
53 - C(absent) deletes event subscription with the specified I(destination).
54 type: str
55 default: present
56 choices: ["present", "absent"]
57 requirements:
58 - "python >= 3.9.6"
59 author:
60 - "Trevor Squillario (@TrevorSquillario)"
61 - "Sachin Apagundi (@sachin-apa)"
62 notes:
63 - I(event_type) needs to be C(MetricReport) and I(event_format_type) needs to be C(MetricReport) for metrics
64 subscription.
65 - I(event_type) needs to be C(Alert) and I(event_format_type) needs to be C(Event) for event subscription.
66 - Modifying a subscription is not supported.
67 - Context is always set to RedfishEvent.
68 - This module supports C(check_mode).
69 """
70
71 EXAMPLES = """
72 ---
73 - name: Add Redfish metric subscription
74 redfish_event_subscription:
75 baseuri: "192.168.0.1"
76 username: "user_name"
77 password: "user_password"
78 ca_path: "/path/to/ca_cert.pem"
79 destination: "https://192.168.1.100:8188"
80 event_type: MetricReport
81 event_format_type: MetricReport
82 state: present
83
84 - name: Add Redfish alert subscription
85 redfish_event_subscription:
86 baseuri: "192.168.0.1"
87 username: "user_name"
88 password: "user_password"
89 ca_path: "/path/to/ca_cert.pem"
90 destination: "https://server01.example.com:8188"
91 event_type: Alert
92 event_format_type: Event
93 state: present
94
95 - name: Delete Redfish subscription with a specified destination
96 redfish_event_subscription:
97 baseuri: "192.168.0.1"
98 username: "user_name"
99 password: "user_password"
100 ca_path: "/path/to/ca_cert.pem"
101 destination: "https://server01.example.com:8188"
102 state: absent
103 """
104
105 RETURN = """
106 ---
107 msg:
108 description: Overall status of the task.
109 returned: always
110 type: str
111 sample: Successfully added the subscription.
112 status:
113 description: Returns subscription object created
114 returned: on adding subscription successfully
115 type: dict
116 sample: {
117 "@Message.ExtendedInfo": [
118 {
119 "Message": "The resource has been created successfully",
120 "MessageArgs": [],
121 "[email protected]": 0,
122 "MessageId": "Base.1.7.Created",
123 "RelatedProperties": [],
124 "[email protected]": 0,
125 "Resolution": "None",
126 "Severity": "OK"
127 },
128 {
129 "Message": "A new resource is successfully created.",
130 "MessageArgs": [],
131 "[email protected]": 0,
132 "MessageId": "IDRAC.2.2.SYS414",
133 "RelatedProperties": [],
134 "[email protected]": 0,
135 "Resolution": "No response action is required.",
136 "Severity": "Informational"
137 }
138 ],
139 "Actions": {
140 "#EventDestination.ResumeSubscription": {
141 "target": "/redfish/v1/EventService/Subscriptions/5d432f36-81f4-11eb-9dc0-2cea7ff7ff9a/Actions/EventDestination.ResumeSubscription"
142 }
143 },
144 "Context": "RedfishEvent",
145 "DeliveryRetryPolicy": "RetryForever",
146 "Description": "Event Subscription Details",
147 "Destination": "https://192.168.1.100:8188",
148 "EventFormatType": "Event",
149 "EventTypes": [
150 "Alert"
151 ],
152 "[email protected]": 1,
153 "HttpHeaders": [],
154 "[email protected]": 0,
155 "Id": "5d432f36-81f4-11eb-9dc0-2cea7ff7ff9a",
156 "MetricReportDefinitions": [],
157 "[email protected]": 0,
158 "Name": "EventSubscription 5d432f36-81f4-11eb-9dc0-2cea7ff7ff9a",
159 "OriginResources": [],
160 "[email protected]": 0,
161 "Protocol": "Redfish",
162 "Status": {
163 "Health": "OK",
164 "HealthRollup": "OK",
165 "State": "Enabled"
166 },
167 "SubscriptionType": "RedfishEvent"
168 }
169 error_info:
170 type: dict
171 description: Details of http error.
172 returned: on http error
173 sample: {
174 "error": {
175 "@Message.ExtendedInfo": [
176 {
177 "Message": "Unable to complete the operation because the JSON data format entered is invalid.",
178 "Resolution": "Do the following and the retry the operation:
179 1) Enter the correct JSON data format and retry the operation.
180 2) Make sure that no syntax error is present in JSON data format.
181 3) Make sure that a duplicate key is not present in JSON data format.",
182 "Severity": "Critical"
183 },
184 {
185 "Message": "The request body submitted was malformed JSON and
186 could not be parsed by the receiving service.",
187 "Resolution": "Ensure that the request body is valid JSON and resubmit the request.",
188 "Severity": "Critical"
189 }
190 ],
191 "code": "Base.1.2.GeneralError",
192 "message": "A general error has occurred. See ExtendedInfo for more information."
193 }
194 }
195 """
196
197 import json
198 import os
199 from ssl import SSLError
200 from ansible_collections.dellemc.openmanage.plugins.module_utils.redfish import Redfish, RedfishAnsibleModule
201 from ansible.module_utils.urls import ConnectionError, SSLValidationError
202 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
203
204 DESTINATION_INVALID = "The Parameter destination must have an HTTPS destination. The HTTP destination is not allowed"
205 SUBSCRIPTION_EXISTS = "No changes found to be applied."
206 SUBSCRIPTION_DELETED = "Successfully deleted the subscription."
207 SUBSCRIPTION_UNABLE_DEL = "Unable to delete the subscription."
208 SUBSCRIPTION_UNABLE_ADD = "Unable to add a subscription."
209 SUBSCRIPTION_ADDED = "Successfully added the subscription."
210 DESTINATION_MISMATCH = "No changes found to be applied."
211 CHANGES_FOUND = "Changes found to be applied."
212
213
214 def get_subscription_payload():
215 payload = {
216 "Destination": "https://192.168.1.100:8188",
217 "EventFormatType": "MetricReport",
218 "Context": "RedfishEvent",
219 "Protocol": "Redfish",
220 "EventTypes": ["MetricReport"],
221 "SubscriptionType": "RedfishEvent"
222 }
223 return payload
224
225
226 def get_subscription(obj, destination):
227 url = "{0}{1}".format(obj.root_uri, "EventService/Subscriptions")
228 list_resp = obj.invoke_request("GET", url)
229 list_subscriptions = list_resp.json_data["Members"]
230 for list_subscription in list_subscriptions:
231 id = os.path.basename(list_subscription.get('@odata.id'))
232 detail_json = get_subscription_details(obj, id)
233 subscription = get_subscription_payload()
234 if detail_json and detail_json["Destination"] == destination:
235 subscription["Id"] = detail_json["Id"]
236 subscription["Destination"] = detail_json["Destination"]
237 subscription["EventFormatType"] = detail_json["EventFormatType"]
238 subscription["Context"] = detail_json["Context"]
239 subscription["Protocol"] = detail_json["Protocol"]
240 subscription["EventTypes"] = detail_json["EventTypes"]
241 subscription["SubscriptionType"] = detail_json["SubscriptionType"]
242 return subscription
243 return None
244
245
246 def get_subscription_details(obj, id):
247 detail_url = "{0}{1}".format(obj.root_uri, "EventService/Subscriptions/%s" % id)
248 detail_resp = obj.invoke_request("GET", detail_url)
249 detail_json = detail_resp.json_data
250 if detail_resp.success:
251 return detail_json
252 else:
253 return None
254
255
256 def create_subscription(obj, module):
257 payload = get_subscription_payload()
258 payload["Destination"] = module.params["destination"]
259 payload["EventFormatType"] = module.params["event_format_type"]
260 payload["EventTypes"] = [module.params["event_type"]]
261 if module.check_mode:
262 module.exit_json(changed=True, msg=CHANGES_FOUND)
263 resp = obj.invoke_request("POST", "{0}{1}".format(obj.root_uri, "EventService/Subscriptions"), data=payload)
264 return resp
265
266
267 def delete_subscription(obj, id):
268 resp = obj.invoke_request("DELETE", "{0}{1}".format(obj.root_uri, "EventService/Subscriptions/%s" % id))
269 return resp
270
271
272 def _validate_inputs(module):
273 """validates that destination has https instead of http"""
274 inp_destination = module.params['destination']
275 if not inp_destination.startswith("https"):
276 module.fail_json(msg=DESTINATION_INVALID)
277
278
279 def _get_formatted_payload(obj, existing_payload):
280 """get the payload after removing unwanted tags"""
281 existing_payload = obj.strip_substr_dict(existing_payload)
282 return existing_payload
283
284
285 def main():
286 specs = {
287 "destination": {"required": True, "type": "str"},
288 "event_type": {"type": "str", "default": "Alert", "choices": ['Alert', 'MetricReport']},
289 "event_format_type": {"type": "str", "default": "Event",
290 "choices": ['Event', 'MetricReport']},
291 "state": {"type": "str", "default": "present", "choices": ['present', 'absent']},
292 }
293
294 module = RedfishAnsibleModule(
295 argument_spec=specs,
296 supports_check_mode=True)
297
298 try:
299 _validate_inputs(module)
300 with Redfish(module.params, req_session=True) as obj:
301 subscription = get_subscription(obj, module.params["destination"])
302 if subscription:
303 if module.params["state"] == "present":
304 module.exit_json(msg=SUBSCRIPTION_EXISTS, changed=False)
305 else:
306 if module.check_mode:
307 module.exit_json(changed=True, msg=CHANGES_FOUND)
308 delete_resp = delete_subscription(obj, subscription["Id"])
309 if delete_resp.success:
310 module.exit_json(msg=SUBSCRIPTION_DELETED, changed=True)
311 else:
312 module.fail_json(msg=SUBSCRIPTION_UNABLE_DEL)
313 else:
314 if module.params["state"] == "present":
315 create_resp = create_subscription(obj, module)
316 if create_resp.success:
317 module.exit_json(msg=SUBSCRIPTION_ADDED, changed=True,
318 status=_get_formatted_payload(obj, create_resp.json_data))
319 else:
320 module.fail_json(msg=SUBSCRIPTION_UNABLE_ADD)
321 else:
322 module.exit_json(msg=DESTINATION_MISMATCH, changed=False)
323 except HTTPError as err:
324 module.fail_json(msg=str(err), error_info=json.load(err))
325 except URLError as err:
326 module.exit_json(msg=str(err), unreachable=True)
327 except (RuntimeError, URLError, SSLValidationError, ConnectionError, KeyError,
328 ImportError, ValueError, TypeError, IOError, AssertionError, OSError, SSLError) as e:
329 module.fail_json(msg=str(e))
330
331
332 if __name__ == '__main__':
333 main()