Debian Codegraph @

ansible_collections/netapp/ontap/plugins/modules/na_ontap_wait_for_condition.py

raw
1 #!/usr/bin/python
2 '''
3 # (c) 2020-2026, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 '''
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 author: NetApp Ansible Team (@carchi8py) <[email protected]>
12 description:
13 - Loop over an ONTAP get status request until a condition is satisfied.
14 - Report a timeout error if C(timeout) is exceeded while waiting for the condition.
15 extends_documentation_fragment:
16 - netapp.ontap.netapp.na_ontap
17 module: na_ontap_wait_for_condition
18 short_description: NetApp ONTAP wait_for_condition. Loop over a get status request until a condition is met.
19 version_added: 20.8.0
20 options:
21 name:
22 description:
23 - The name of the event to check for.
24 - snapmirror_relationship was added in 21.22.0.
25 choices: ['snapmirror_relationship', 'sp_upgrade', 'sp_version']
26 type: str
27 required: true
28
29 state:
30 description:
31 - whether the conditions should be present or absent.
32 - if C(present), the module exits when any of the conditions is observed.
33 - if C(absent), the module exits with success when None of the conditions is observed.
34 choices: ['present', 'absent']
35 default: present
36 type: str
37
38 conditions:
39 description:
40 - one or more conditions to match
41 - C(state) and/or C(transfer_state) for C(snapmirror_relationship),
42 - C(is_in_progress) for C(sp_upgrade),
43 - C(firmware_version) for C(sp_version).
44 type: list
45 elements: str
46 required: true
47
48 polling_interval:
49 description:
50 - how ofen to check for the conditions, in seconds.
51 default: 5
52 type: int
53
54 timeout:
55 description:
56 - how long to wait for the conditions, in seconds.
57 default: 180
58 type: int
59
60 attributes:
61 description:
62 - a dictionary of custom attributes for the condition.
63 - C(sp_upgrade), C(sp_version) require C(node).
64 - C(sp_version) requires C(expected_version).
65 - C(snapmirror_relationship) requires C(destination_path) and C(expected_state) or C(expected_transfer_state) to match the condition(s).
66 type: dict
67
68 lambda_config:
69 description:
70 - Configuration parameters for AWS Lambda proxy functionality.
71 - These option and suboptions are only supported with REST.
72 type: dict
73 version_added: 23.5.0
74 suboptions:
75 function_name:
76 description:
77 - The name of the AWS Lambda function to invoke.
78 type: str
79 required: true
80 aws_region:
81 description:
82 - The name of the AWS region.
83 type: str
84 required: true
85 aws_profile:
86 description:
87 - The name of the AWS profile to use for authentication.
88 type: str
89
90 notes:
91 - Supports AWS Lambda proxy functionality when using REST. See README for example usage.
92 '''
93
94 EXAMPLES = """
95 - name: Wait for sp_upgrade in progress
96 netapp.ontap.na_ontap_wait_for_condition:
97 hostname: "{{ netapp_hostname }}"
98 username: "{{ netapp_username }}"
99 password: "{{ netapp_password }}"
100 https: true
101 validate_certs: false
102 name: sp_upgrade
103 conditions: is_in_progress
104 attributes:
105 node: "{{ node }}"
106 polling_interval: 30
107 timeout: 1800
108
109 - name: Wait for sp_upgrade not in progress
110 netapp.ontap.na_ontap_wait_for_condition:
111 hostname: "{{ netapp_hostname }}"
112 username: "{{ netapp_username }}"
113 password: "{{ netapp_password }}"
114 https: true
115 validate_certs: false
116 name: sp_upgrade
117 conditions: is_in_progress
118 state: absent
119 attributes:
120 node: "{{ ontap_admin_ip }}"
121 polling_interval: 30
122 timeout: 1800
123
124 - name: Wait for sp_version to match 3.9
125 netapp.ontap.na_ontap_wait_for_condition:
126 hostname: "{{ netapp_hostname }}"
127 username: "{{ netapp_username }}"
128 password: "{{ netapp_password }}"
129 https: true
130 validate_certs: false
131 name: sp_version
132 conditions: firmware_version
133 state: present
134 attributes:
135 node: "{{ ontap_admin_ip }}"
136 expected_version: 3.9
137 polling_interval: 30
138 timeout: 1800
139 """
140
141 RETURN = """
142 states:
143 description:
144 - summarized list of observed states while waiting for completion
145 - reported for success or timeout error
146 returned: always
147 type: str
148 last_state:
149 description: last observed state for event
150 returned: always
151 type: str
152 """
153
154 import time
155 from ansible.module_utils.basic import AnsibleModule
156 from ansible.module_utils._text import to_native
157 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
158 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
159 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
160
161
162 class NetAppONTAPWFC:
163 ''' wait for a resource to match a condition or not '''
164
165 def __init__(self):
166 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
167 self.argument_spec.update(dict(
168 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
169 name=dict(required=True, type='str', choices=['snapmirror_relationship', 'sp_upgrade', 'sp_version']),
170 conditions=dict(required=True, type='list', elements='str'),
171 polling_interval=dict(required=False, type='int', default=5),
172 timeout=dict(required=False, type='int', default=180),
173 attributes=dict(required=False, type='dict')
174 ))
175 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
176
177 self.module = AnsibleModule(
178 argument_spec=self.argument_spec,
179 required_if=[
180 ('name', 'sp_upgrade', ['attributes']),
181 ('name', 'sp_version', ['attributes']),
182 ('use_lambda', True, ['lambda_config']),
183 ],
184 supports_check_mode=True
185 )
186 self.na_helper = NetAppModule()
187 self.parameters = self.na_helper.set_parameters(self.module.params)
188 self.states = []
189 self.rest_api = netapp_utils.OntapRestAPI(self.module)
190 self.use_rest = self.rest_api.is_rest()
191
192 if not self.use_rest:
193 if self.parameters.get('use_lambda'):
194 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
195 if not netapp_utils.has_netapp_lib():
196 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
197 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, wrap_zapi=True)
198
199 self.resource_configuration = {
200 'snapmirror_relationship': {
201 'required_attributes': ['destination_path'],
202 'conditions': {
203 'state': ('state' if self.use_rest else 'not_supported', None),
204 'transfer_state': ('transfer.state' if self.use_rest else 'not_supported', None)
205 }
206 },
207 'sp_upgrade': {
208 'required_attributes': ['node'],
209 'conditions': {
210 'is_in_progress': ('service_processor.state', 'updating') if self.use_rest else ('is-in-progress', 'true')
211 }
212 },
213 'sp_version': {
214 'required_attributes': ['node', 'expected_version'],
215 'conditions': {
216 'firmware_version': ('service_processor.firmware_version' if self.use_rest else 'firmware-version',
217 self.parameters['attributes'].get('expected_version'))
218 }
219 }
220 }
221
222 name = 'snapmirror_relationship'
223 if self.parameters['name'] == name:
224 for condition in self.resource_configuration[name]['conditions']:
225 if condition in self.parameters['conditions']:
226 self.update_condition_value(name, condition)
227
228 def update_condition_value(self, name, condition):
229 '''requires an expected value for a condition and sets it'''
230 expected_value = 'expected_%s' % condition
231 self.resource_configuration[name]['required_attributes'].append(expected_value)
232 # we can't update a tuple value, so rebuild the tuple
233 self.resource_configuration[name]['conditions'][condition] = (
234 self.resource_configuration[name]['conditions'][condition][0],
235 self.parameters['attributes'].get(expected_value))
236
237 def get_fields(self, name):
238 return ','.join([field for (field, dummy) in self.resource_configuration[name]['conditions'].values()])
239
240 def get_key_value(self, record, key):
241 if self.use_rest:
242 # with REST, we can have nested dictionaries
243 key = key.split('.')
244 return self.na_helper.safe_get(record, key)
245 return self.get_key_value_zapi(record, key)
246
247 def get_key_value_zapi(self, xml, key):
248 for child in xml.get_children():
249 value = xml.get_child_content(key)
250 if value is not None:
251 return value
252 value = self.get_key_value(child, key)
253 if value is not None:
254 return value
255 return None
256
257 def build_zapi(self, name):
258 ''' build ZAPI request based on resource name '''
259 if name == 'sp_upgrade':
260 zapi_obj = netapp_utils.zapi.NaElement("service-processor-image-update-progress-get")
261 zapi_obj.add_new_child('node', self.parameters['attributes']['node'])
262 return zapi_obj
263 if name == 'sp_version':
264 zapi_obj = netapp_utils.zapi.NaElement("service-processor-get")
265 zapi_obj.add_new_child('node', self.parameters['attributes']['node'])
266 return zapi_obj
267 if name in self.resource_configuration:
268 self.module.fail_json(msg='Error: event %s is not supported with ZAPI. It requires REST.' % name)
269 raise KeyError(name)
270
271 def build_rest_api_kwargs(self, name):
272 if name in ['sp_upgrade', 'sp_version']:
273 return {
274 'api': 'cluster/nodes',
275 'query': {'name': self.parameters['attributes']['node']},
276 'fields': self.get_fields(name)
277 }
278 if name == 'snapmirror_relationship':
279 return {
280 'api': 'snapmirror/relationships',
281 'query': {'destination.path': self.parameters['attributes']['destination_path']},
282 'fields': self.get_fields(name)
283 }
284 raise KeyError(name)
285
286 def extract_condition(self, name, results):
287 ''' check if any of the conditions is present
288 return:
289 None, error if key is not found
290 condition, None if a key is found with expected value
291 None, None if every key does not match the expected values
292 '''
293 for condition, (key, value) in self.resource_configuration[name]['conditions'].items():
294 status = self.get_key_value(results, key)
295 if status is None and name == 'snapmirror_relationship' and results and condition == 'transfer_state':
296 # key is absent when not transferring. We convert this to 'idle'
297 status = 'idle'
298 self.states.append(str(status))
299 if status == str(value):
300 return condition, None
301 if status is None:
302 return None, 'Cannot find element with name: %s in results: %s' % (key, results if self.use_rest else results.to_string())
303 # not found, or no match
304 return None, None
305
306 def get_condition(self, name, rest_or_zapi_args):
307 '''calls ZAPI or REST and extract condition value'''
308 record, error = self.get_record_rest(name, rest_or_zapi_args) if self.use_rest else self.get_record_zapi(name, rest_or_zapi_args)
309 if error:
310 return None, error
311 condition, error = self.extract_condition(name, record)
312 if error is not None:
313 return condition, error
314 if self.parameters['state'] == 'present':
315 if condition in self.parameters['conditions']:
316 return 'matched condition: %s' % condition, None
317 else:
318 if condition is None:
319 return 'conditions not matched', None
320 if condition not in self.parameters['conditions']:
321 return 'conditions not matched: found other condition: %s' % condition, None
322 return None, None
323
324 def get_record_zapi(self, name, zapi_obj):
325 ''' calls the ZAPI and extract condition value'''
326 try:
327 results = self.server.invoke_successfully(zapi_obj, True)
328 except netapp_utils.zapi.NaApiError as error:
329 return None, 'Error running command %s: %s' % (self.parameters['name'], to_native(error))
330 return results, None
331
332 def get_record_rest(self, name, rest_api_kwargs):
333 record, error = rest_generic.get_one_record(self.rest_api, **rest_api_kwargs)
334 if error:
335 return None, 'Error running command %s: %s' % (self.parameters['name'], error)
336 if not record:
337 return None, "no record for node: %s" % rest_api_kwargs['query']
338 return record, None
339
340 def summarize_states(self):
341 ''' replaces a long list of states with multipliers
342 eg 'false*5' or 'false*2,true'
343 return:
344 state_list as str
345 last_state
346 '''
347 previous_state = None
348 count = 0
349 summaries = []
350 for state in self.states:
351 if state == previous_state:
352 count += 1
353 else:
354 if previous_state is not None:
355 summaries.append('%s%s' % (previous_state, '' if count == 1 else '*%d' % count))
356 count = 1
357 previous_state = state
358 if previous_state is not None:
359 summaries.append('%s%s' % (previous_state, '' if count == 1 else '*%d' % count))
360 last_state = self.states[-1] if self.states else ''
361 return ','.join(summaries), last_state
362
363 def wait_for_condition(self, name):
364 ''' calls the ZAPI and extract condition value - loop until found '''
365 time_left = self.parameters['timeout']
366 max_consecutive_error_count = 3
367 error_count = 0
368 rest_or_zapi_args = self.build_rest_api_kwargs(name) if self.use_rest else self.build_zapi(name)
369
370 while time_left > 0:
371 condition, error = self.get_condition(name, rest_or_zapi_args)
372 if error is not None:
373 error_count += 1
374 if error_count >= max_consecutive_error_count:
375 self.module.fail_json(msg='Error: %s - count: %d' % (error, error_count))
376 elif condition is not None:
377 return condition
378 time.sleep(self.parameters['polling_interval'])
379 time_left -= self.parameters['polling_interval']
380
381 conditions = ["%s==%s" % (condition, self.resource_configuration[name]['conditions'][condition][1]) for condition in self.parameters['conditions']]
382 error = 'Error: timeout waiting for condition%s: %s.' %\
383 ('s' if len(conditions) > 1 else '',
384 ', '.join(conditions))
385 states, last_state = self.summarize_states()
386 self.module.fail_json(msg=error, states=states, last_state=last_state)
387
388 def validate_resource(self, name):
389 if name not in self.resource_configuration:
390 raise KeyError('%s - configuration entry missing for resource' % name)
391
392 def validate_attributes(self, name):
393 required = self.resource_configuration[name].get('required_attributes', list())
394 msgs = [
395 'attributes: %s is required for resource name: %s' % (attribute, name)
396 for attribute in required
397 if attribute not in self.parameters['attributes']
398 ]
399
400 if msgs:
401 self.module.fail_json(msg='Error: %s' % ', '.join(msgs))
402
403 def validate_conditions(self, name):
404 conditions = self.resource_configuration[name].get('conditions')
405 msgs = [
406 'condition: %s is not valid for resource name: %s' % (condition, name)
407 for condition in self.parameters['conditions']
408 if condition not in conditions
409 ]
410
411 if msgs:
412 msgs.append('valid condition%s: %s' %
413 ('s are' if len(conditions) > 1 else ' is', ', '.join(conditions.keys())))
414 self.module.fail_json(msg='Error: %s' % ', '.join(msgs))
415
416 def apply(self):
417 ''' calls the ZAPI and check conditions '''
418 changed = False
419 name = self.parameters['name']
420 self.validate_resource(name)
421 self.validate_attributes(name)
422 self.validate_conditions(name)
423 output = self.wait_for_condition(name)
424 states, last_state = self.summarize_states()
425 self.module.exit_json(changed=changed, msg=output, states=states, last_state=last_state)
426
427
428 def main():
429 """
430 Execute action from playbook
431 """
432 command = NetAppONTAPWFC()
433 command.apply()
434
435
436 if __name__ == '__main__':
437 main()