Debian Codegraph @

ansible_collections/netapp/storagegrid/plugins/modules/na_sg_grid_hotfix.py

raw
1 #!/usr/bin/python
2
3 # (c) 2025, NetApp Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """NetApp StorageGRID - Apply Hotfixes"""
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 ANSIBLE_METADATA = {
14 "metadata_version": "1.0",
15 "status": ["preview"],
16 "supported_by": "community",
17 }
18
19
20 DOCUMENTATION = """
21 module: na_sg_grid_hotfix
22 short_description: Apply hotfixes on StorageGRID.
23 extends_documentation_fragment:
24 - netapp.storagegrid.netapp.sg
25 version_added: '21.15.0'
26 author: NetApp Ansible Team (@vinaykus) <[email protected]>
27 description:
28 - Apply hotfix on NetApp StorageGRID.
29 options:
30 state:
31 description:
32 - The hotfix will start applying if present.
33 - If absent, it remove all nodes from the hotfix queue.
34 choices: ['present', 'absent']
35 default: 'present'
36 type: str
37 passphrase:
38 description:
39 - The provisioning passphrase.
40 type: str
41 type:
42 description:
43 - the type of software update to deploy.
44 choices: ['hotfix']
45 type: str
46 file_path:
47 description:
48 - The path to the software update file.
49 type: str
50 timeout:
51 description:
52 - The time in seconds to wait for the software update to complete.
53 type: int
54 default: 20
55
56 notes:
57 - It is recommend to apply the latest hotfix before and after each software upgrade.
58 - Before starting the hotfix process, confirm that there are no active alerts and that all grid nodes are online and available.
59 - When the primary Admin Node is updated, services are stopped and restarted. Connectivity might be interrupted until the services are back online.
60 """
61
62 EXAMPLES = """
63 - name: Apply hotfix on StorageGRID
64 na_sg_grid_hotfix:
65 api_url: "https://<storagegrid-endpoint-url>"
66 auth_token: "storagegrid-auth-token"
67 state: "present"
68 validate_certs: false
69 passphrase: "{{ storagegrid_passphrase }}"
70 type: "hotfix"
71 file_path: "/path/to/hotfix_file"
72 """
73
74 RETURN = """
75 resp:
76 description: Returns information about the StorageGRID software update.
77 returned: success
78 type: dict
79 sample: {
80 "id": "software-update",
81 "filePath": "/tmp/StorageGRID-Software-Update",
82 "fileName": "StorageGRID-Software-Update",
83 "version": "11.4.0.1",
84 "restart": true,
85 "startTime": "2025-03-28T06:33:58.576Z",
86 "endTime": "2025-03-28T06:33:58.576Z",
87 "inProgress": true,
88 "stage": "applying",
89 "error": "Failed to apply software update to DC1-S1",
90 "validationError": "Failed to validate installer file: File is empty",
91 "percent": 75,
92 "type": "hotfix",
93 "uploadType": "hotfix"
94 }
95 """
96
97 import time
98 import ansible_collections.netapp.storagegrid.plugins.module_utils.netapp as netapp_utils
99 from ansible.module_utils.basic import AnsibleModule
100 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp_module import NetAppModule
101 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp import SGRestAPI
102
103
104 class SgHotfix:
105 """
106 Apply hotfix on NetApp StorageGRID
107 """
108
109 def __init__(self):
110 """
111 Parse arguments, setup state variables,
112 check parameters and ensure request module is installed
113 """
114 self.argument_spec = netapp_utils.na_storagegrid_host_argument_spec()
115 self.argument_spec.update(
116 dict(
117 state=dict(type="str", choices=["present", "absent"], default="present"),
118 passphrase=dict(required=False, type="str", no_log=True),
119 type=dict(required=False, type="str", choices=["hotfix"]),
120 timeout=dict(required=False, type="int", default=20),
121 file_path=dict(required=False, type="str"),
122 )
123 )
124
125 self.module = AnsibleModule(
126 argument_spec=self.argument_spec,
127 required_if=[["state", "present", ["passphrase", "type"]]],
128 supports_check_mode=True
129 )
130 self.na_helper = NetAppModule()
131
132 # set up state variables
133 self.parameters = self.na_helper.set_parameters(self.module.params)
134 # Calling generic SG rest_api class
135 self.rest_api = SGRestAPI(self.module)
136 # Get API version
137 self.rest_api.get_sg_product_version()
138 self.api_version = self.rest_api.get_api_version()
139
140 # Checking for the parameters passed and create new parameters list
141 self.data = {}
142
143 self.data["passphrase"] = self.parameters["passphrase"]
144 self.data["type"] = self.parameters["type"]
145
146 if "file_path" in self.parameters:
147 self.rest_api.fail_if_not_sg_minimum_version("flie_path", 11, 9)
148
149 def get_hotfix_details(self):
150 """ Retrieve the status of the current software update procedure """
151 api = "api/%s/private/software-update" % self.api_version
152 response, error = self.rest_api.get(api)
153
154 if error:
155 self.module.fail_json(msg=error)
156 else:
157 return response["data"]
158
159 def start_apply_hotfix(self):
160 """ Runs the software update procedure """
161 api = "api/%s/private/software-update/start" % self.api_version
162 response, error = self.rest_api.post(api, self.data)
163
164 if error:
165 self.module.fail_json(msg=error)
166
167 def get_hotfix_node_details(self):
168 """ Retrieve the list of node details """
169 api = "api/%s/private/software-update/nodes" % self.api_version
170 response, error = self.rest_api.get(api)
171
172 if error:
173 self.module.fail_json(msg=error)
174 else:
175 return response["data"]
176
177 def update_hotfix_node_queue(self, node_id):
178 """ Update the node queue schedule for the software update """
179 api = "api/%s/private/software-update/queue" % self.api_version
180 body = [node_id]
181 response, error = self.rest_api.post(api, body)
182
183 if error:
184 self.module.fail_json(msg=error)
185
186 def remove_hotfix_node_queue(self, node_id):
187 """ Remove the node from the hotfix queue """
188 api = "api/%s/private/software-update/queue" % self.api_version
189 body = [node_id]
190 response, error = self.rest_api.delete(api, body)
191
192 if error:
193 self.module.fail_json(msg=error)
194
195 def upload_hotfix_software_update_file(self, file_path):
196 """ Upload the software update file """
197 api = "api/%s/tools/upload-software-update" % self.api_version
198 with open(file_path, "rb") as file:
199 file_name = file_path.split('/')[-1]
200 files = {
201 "file": (file_name, file, "application/octet-stream"),
202 }
203 params = {"type": "hotfix"}
204
205 response, error = self.rest_api.post(api, files=files, params=params)
206
207 if error or response.get("status_code") != 202:
208 self.module.fail_json(msg="Failed to upload hotfix file")
209 # sleep for 5 seconds to allow the upload to get refreshed
210 time.sleep(5)
211
212 def wait_for_hotfix_to_complete(self, current_node):
213 """ Wait for the software update procedure to complete """
214 for __ in range(self.parameters["timeout"]):
215 current_hotfix = self.get_hotfix_details()
216
217 # Check for any validation errors after updating the node queue
218 if current_hotfix["validationError"]:
219 self.module.fail_json(msg=current_hotfix["validationError"])
220
221 node_details = self.get_hotfix_node_details()
222 if node_details:
223 for node in node_details:
224 # Check if the node update is in progress
225 if node["id"] == current_node["id"] and node["progress"]["percent"] == 100:
226 return
227
228 elif node["progress"].get("error"):
229 self.module.fail_json(msg=node["progress"]["error"])
230
231 # sleep for 5 seconds before checking again
232 time.sleep(5)
233 else:
234 return
235
236 self.module.fail_json(msg="Timeout waiting for hotfix to complete")
237
238 def apply(self):
239 """ Apply hotfix on NetApp StorageGRID """
240
241 current_hotfix = self.get_hotfix_details()
242
243 if self.parameters['state'] == 'present' and self.parameters.get("file_path") and not current_hotfix["inProgress"]:
244 self.upload_hotfix_software_update_file(self.parameters["file_path"])
245 # get the hotfix details again after uploading the file
246 current_hotfix = self.get_hotfix_details()
247
248 current_nodes_to_update = None
249
250 if self.parameters['state'] == 'absent':
251 if current_hotfix["inProgress"]:
252 current_nodes_to_update = self.get_hotfix_node_details()
253 for node in current_nodes_to_update:
254 if node["queued"]:
255 self.remove_hotfix_node_queue(node["id"])
256 self.na_helper.changed = True
257
258 if self.parameters["state"] == "present":
259 if current_hotfix["uploadType"] == "hotfix" and not current_hotfix["inProgress"]:
260 self.start_apply_hotfix()
261 # get the nodes details after starting the hotfix
262 current_nodes_to_update = self.get_hotfix_node_details()
263 for current_node in current_nodes_to_update:
264 self.update_hotfix_node_queue(current_node["id"])
265 # sleep for 5 seconds before checking the status
266 time.sleep(5)
267 self.wait_for_hotfix_to_complete(current_node)
268 self.na_helper.changed = True
269
270 elif current_hotfix["inProgress"]:
271 current_nodes_to_update = self.get_hotfix_node_details()
272 for current_node in current_nodes_to_update:
273 self.update_hotfix_node_queue(current_node["id"])
274 # sleep for 5 seconds before checking the status
275 time.sleep(5)
276 self.wait_for_hotfix_to_complete(current_node)
277 self.na_helper.changed = True
278
279 result_message = ""
280 resp_data = current_hotfix
281 if self.na_helper.changed:
282 if self.module.check_mode:
283 pass
284 else:
285 if self.parameters['state'] == 'absent':
286 result_message = "Hotfix node removed successfully."
287 else:
288 if self.parameters["state"] == "present":
289 result_message = "Hotfix applied successfully."
290
291 self.module.exit_json(changed=self.na_helper.changed, msg=result_message, resp=resp_data)
292
293
294 def main():
295 """
296 Main function
297 """
298 na_sg_grid_hotfix = SgHotfix()
299 na_sg_grid_hotfix.apply()
300
301
302 if __name__ == "__main__":
303 main()