Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2025, NetApp, Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 ANSIBLE_METADATA = {'metadata_version': '1.1',
10 'status': ['preview'],
11 'supported_by': 'certified'}
12
13 DOCUMENTATION = '''
14 short_description: NetApp ONTAP manage consistency group snapshot
15 author: NetApp Ansible Team (@carchi8py) <[email protected]>
16 description:
17 - Create or delete consistency group snapshot for ONTAP volumes.
18 extends_documentation_fragment:
19 - netapp.ontap.netapp.na_ontap
20 module: na_ontap_cg_snapshot
21 options:
22 state:
23 description:
24 - Specifies whether to create or delete the snapshot.
25 - Choice 'absent' is valid only with REST.
26 default: present
27 choices: ['present', 'absent']
28 type: str
29 vserver:
30 required: true
31 type: str
32 description:
33 - Name of the vserver.
34 volumes:
35 required: false
36 type: list
37 elements: str
38 description:
39 - A list of volumes in this filer that is part of this CG operation.
40 - Required with ZAPI.
41 consistency_group:
42 required: false
43 type: str
44 description:
45 - Name of the consistency group for which snapshot needs to be created or deleted.
46 - Valid only with REST.
47 version_added: 22.8.0
48 snapshot:
49 required: true
50 type: str
51 description:
52 - The provided name of the snapshot that is created in each volume.
53 timeout:
54 description:
55 - Timeout selector.
56 - Not supported with REST.
57 choices: ['urgent', 'medium', 'relaxed']
58 type: str
59 default: medium
60 snapmirror_label:
61 description:
62 - A human readable SnapMirror label to be attached with the consistency group snapshot copies.
63 type: str
64 comment:
65 description:
66 - Comment for the snapshot copy.
67 - Only supported with REST.
68 type: str
69 version_added: 22.8.0
70 consistency_type:
71 description:
72 - Type of consistency guarantee for the snapshot.
73 - Only supported with REST.
74 - If not specified, ONTAP uses its default consistency type.
75 choices: ['crash', 'application']
76 type: str
77 version_added: 23.2.0
78 version_added: 2.7.0
79
80 notes:
81 - REST support requires ONTAP 9.10 or later.
82 - Delete operation is supported only with REST.
83
84 '''
85
86 EXAMPLES = """
87 - name: Create CG snapshot
88 na_ontap_cg_snapshot:
89 state: present
90 vserver: vserver_name
91 snapshot: snapshot name
92 volumes: vol_name
93 # consistency_type defaults to 'crash' if not specified
94 username: "{{ netapp_username }}"
95 password: "{{ netapp_password }}"
96 hostname: "{{ netapp_hostname }}"
97
98 - name: Create CG snapshot using CG name - REST
99 na_ontap_cg_snapshot:
100 state: present
101 vserver: vserver_name
102 snapshot: snapshot_name
103 consistency_group: cg_name
104 snapmirror_label: sm_label
105 consistency_type: application
106 username: "{{ netapp_username }}"
107 password: "{{ netapp_password }}"
108 hostname: "{{ netapp_hostname }}"
109
110 - name: Create CG snapshot using volumes - REST
111 na_ontap_cg_snapshot:
112 state: present
113 vserver: vserver_name
114 snapshot: snapshot_name
115 volumes:
116 - vol1
117 - vol2
118 snapmirror_label: sm_label
119 consistency_type: crash
120 username: "{{ netapp_username }}"
121 password: "{{ netapp_password }}"
122 hostname: "{{ netapp_hostname }}"
123
124 - name: Delete CG snapshot - REST
125 na_ontap_cg_snapshot:
126 state: absent
127 vserver: vserver_name
128 snapshot: snapshot_name
129 consistency_group: cg_name
130 username: "{{ netapp_username }}"
131 password: "{{ netapp_password }}"
132 hostname: "{{ netapp_hostname }}"
133 """
134
135 RETURN = """
136 """
137
138 import traceback
139
140 from ansible.module_utils.basic import AnsibleModule
141 from ansible.module_utils._text import to_native
142 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
143 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
144 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
145
146
147 class NetAppONTAPCGSnapshot(object):
148 """
149 Methods to create or delete CG snapshots
150 """
151
152 def __init__(self):
153 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
154 self.argument_spec.update(dict(
155 state=dict(required=False, choices=['present', 'absent'], default='present'),
156 vserver=dict(required=True, type='str'),
157 volumes=dict(required=False, type='list', elements='str'),
158 snapshot=dict(required=True, type='str'),
159 timeout=dict(required=False, type='str', choices=[
160 'urgent', 'medium', 'relaxed'], default='medium'),
161 snapmirror_label=dict(required=False, type='str'),
162 consistency_group=dict(required=False, type='str'),
163 comment=dict(required=False, type='str'),
164 consistency_type=dict(required=False, type='str', choices=['crash', 'application']),
165 ))
166
167 self.module = AnsibleModule(
168 argument_spec=self.argument_spec,
169 supports_check_mode=False,
170 mutually_exclusive=[
171 ['consistency_group', 'volumes']]
172 )
173
174 self.na_helper = NetAppModule()
175 self.parameters = self.na_helper.set_parameters(self.module.params)
176 self.rest_api = netapp_utils.OntapRestAPI(self.module)
177 self.use_rest = self.rest_api.is_rest()
178
179 if self.use_rest:
180 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 10, 1):
181 self.module.fail_json(msg='REST requires ONTAP 9.10.1 or later for /application/consistency-groups APIs.')
182 self.cg_uuid = None
183 else:
184 self.cgid = None
185 if not netapp_utils.has_netapp_lib():
186 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
187 self.zapi_errors()
188 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
189
190 def does_snapshot_exist(self, volume):
191 """
192 This is duplicated from na_ontap_snapshot
193 Checks to see if a snapshot exists or not
194 :return: Return True if a snapshot exists, false if it dosen't
195 """
196 # TODO: Remove this method and import snapshot module and
197 # call get after re-factoring __init__ across all the modules
198 # we aren't importing now, since __init__ does a lot of Ansible setup
199 snapshot_obj = netapp_utils.zapi.NaElement("snapshot-get-iter")
200 desired_attr = netapp_utils.zapi.NaElement("desired-attributes")
201 snapshot_info = netapp_utils.zapi.NaElement('snapshot-info')
202 comment = netapp_utils.zapi.NaElement('comment')
203 # add more desired attributes that are allowed to be modified
204 snapshot_info.add_child_elem(comment)
205 desired_attr.add_child_elem(snapshot_info)
206 snapshot_obj.add_child_elem(desired_attr)
207 # compose query
208 query = netapp_utils.zapi.NaElement("query")
209 snapshot_info_obj = netapp_utils.zapi.NaElement("snapshot-info")
210 snapshot_info_obj.add_new_child("name", self.parameters['snapshot'])
211 snapshot_info_obj.add_new_child("volume", volume)
212 snapshot_info_obj.add_new_child("vserver", self.parameters['vserver'])
213 query.add_child_elem(snapshot_info_obj)
214 snapshot_obj.add_child_elem(query)
215 result = self.server.invoke_successfully(snapshot_obj, True)
216 return_value = None
217 if result.get_child_by_name('num-records') and \
218 int(result.get_child_content('num-records')) == 1:
219 attributes_list = result.get_child_by_name('attributes-list')
220 snap_info = attributes_list.get_child_by_name('snapshot-info')
221 return_value = {'comment': snap_info.get_child_content('comment')}
222 return return_value
223
224 def cgcreate(self):
225 """
226 Calls cg-start and cg-commit (when cg-start succeeds)
227 """
228 started = self.cg_start()
229 if started:
230 if self.cgid is not None:
231 self.cg_commit()
232 else:
233 self.module.fail_json(msg="Error fetching CG ID for CG commit %s" % self.parameters['snapshot'],
234 exception=traceback.format_exc())
235 return started
236
237 def cg_start(self):
238 """
239 For the given list of volumes, creates cg-snapshot
240 """
241 snapshot_started = False
242 cgstart = netapp_utils.zapi.NaElement("cg-start")
243 cgstart.add_new_child("snapshot", self.parameters['snapshot'])
244 cgstart.add_new_child("timeout", self.parameters['timeout'])
245 volume_list = netapp_utils.zapi.NaElement("volumes")
246 cgstart.add_child_elem(volume_list)
247 for vol in self.parameters['volumes']:
248 snapshot_exists = self.does_snapshot_exist(vol)
249 if snapshot_exists is None:
250 snapshot_started = True
251 volume_list.add_new_child("volume-name", vol)
252 if snapshot_started:
253 if self.parameters.get('snapmirror_label') is not None:
254 cgstart.add_new_child("snapmirror-label",
255 self.parameters['snapmirror_label'])
256 try:
257 cgresult = self.server.invoke_successfully(
258 cgstart, enable_tunneling=True)
259 if cgresult.get_child_by_name('cg-id'):
260 self.cgid = cgresult['cg-id']
261 except netapp_utils.zapi.NaApiError as error:
262 self.module.fail_json(msg="Error creating CG snapshot %s: %s" %
263 (self.parameters['snapshot'], to_native(error)),
264 exception=traceback.format_exc())
265 return snapshot_started
266
267 def cg_commit(self):
268 """
269 When cg-start is successful, performs a cg-commit with the cg-id
270 """
271 cgcommit = netapp_utils.zapi.NaElement.create_node_with_children(
272 'cg-commit', **{'cg-id': self.cgid})
273 try:
274 self.server.invoke_successfully(cgcommit,
275 enable_tunneling=True)
276 except netapp_utils.zapi.NaApiError as error:
277 self.module.fail_json(msg="Error committing CG snapshot %s: %s" %
278 (self.parameters['snapshot'], to_native(error)),
279 exception=traceback.format_exc())
280
281 def zapi_errors(self):
282 unsupported_zapi_properties = ['consistency_group', 'comment', 'consistency_type']
283 used_unsupported_zapi_properties = [option for option in unsupported_zapi_properties if option in self.parameters]
284 if used_unsupported_zapi_properties:
285 self.module.fail_json(msg="Error: %s options supported only with REST." % " ,".join(used_unsupported_zapi_properties))
286 if self.parameters.get('volumes') is None:
287 self.module.fail_json(msg="Error: 'volumes' option is mandatory while using ZAPI.")
288 if self.parameters.get('state') == 'absent':
289 self.module.fail_json(msg="Deletion of consistency group snapshot is not supported with ZAPI.")
290
291 def get_cg_rest(self):
292 """
293 Retrieve consistency group with the given CG name or list of volumes
294 """
295 api = '/application/consistency-groups'
296 query = {
297 'svm.name': self.parameters['vserver'],
298 'fields': 'svm.uuid,name,uuid,'
299 }
300
301 if self.parameters.get('consistency_group') is not None:
302 query['name'] = self.parameters['consistency_group']
303 record, error = rest_generic.get_one_record(self.rest_api, api, query)
304 if error:
305 self.module.fail_json(msg='Error searching for consistency group %s: %s' % (self.parameters['consistency_group'], to_native(error)),
306 exception=traceback.format_exc())
307 if record:
308 self.cg_uuid = record.get('uuid')
309
310 if self.parameters.get('volumes') is not None:
311 query['fields'] += 'volumes.name,'
312 records, error = rest_generic.get_0_or_more_records(self.rest_api, api, query)
313 if error:
314 self.module.fail_json(msg='Error searching for consistency group having volumes %s: %s' % (set(self.parameters['volumes']), to_native(error)),
315 exception=traceback.format_exc())
316 if records:
317 for record in records:
318 if record.get('volumes') is not None:
319 cg_volumes = [vol_item['name'] for vol_item in record['volumes']]
320 if sorted(cg_volumes) == sorted(set(self.parameters['volumes'])):
321 self.cg_uuid = record.get('uuid')
322 break
323 return None
324
325 def get_cg_snapshot_rest(self):
326 """
327 Retrieve CG snapshots using fetched CG uuid
328 """
329 self.get_cg_rest()
330 if self.cg_uuid is None:
331 if self.parameters.get('consistency_group') is not None:
332 self.module.fail_json(msg="Consistency group named '%s' not found" % self.parameters.get('consistency_group'))
333 if self.parameters.get('volumes') is not None:
334 self.module.fail_json(msg="Consistency group having volumes '%s' not found" % self.parameters.get('volumes'))
335
336 api = '/application/consistency-groups/%s/snapshots' % self.cg_uuid
337 query = {'name': self.parameters['snapshot'],
338 'fields': 'name,'
339 'uuid,'
340 'consistency_group,'
341 'snapmirror_label,'
342 'comment,'
343 'consistency_type,'}
344 record, error = rest_generic.get_one_record(self.rest_api, api, query)
345 if error:
346 self.module.fail_json(msg='Error searching for consistency group snapshot %s: %s' % (self.parameters['snapshot'], to_native(error)),
347 exception=traceback.format_exc())
348 if record:
349 return {
350 'snapshot': record.get('name'),
351 'snapshot_uuid': record.get('uuid'),
352 'consistency_group': self.na_helper.safe_get(record, ['consistency_group', 'name']),
353 'snapmirror_label': record.get('snapmirror_label'),
354 'comment': record.get('comment'),
355 'consistency_type': record.get('consistency_type'),
356 }
357 return None
358
359 def create_cg_snapshot_rest(self):
360 """Create CG snapshot"""
361 api = '/application/consistency-groups/%s/snapshots' % self.cg_uuid
362 body = {'name': self.parameters['snapshot']}
363 if self.parameters.get('snapmirror_label'):
364 body['snapmirror_label'] = self.parameters['snapmirror_label']
365 if self.parameters.get('comment'):
366 body['comment'] = self.parameters['comment']
367 if self.parameters.get('consistency_type'):
368 body['consistency_type'] = self.parameters['consistency_type']
369 dummy, error = rest_generic.post_async(self.rest_api, api, body)
370 if error:
371 self.module.fail_json(msg='Error creating consistency group snapshot %s: %s' % (self.parameters['snapshot'], to_native(error)),
372 exception=traceback.format_exc())
373
374 def delete_cg_snapshot_rest(self, current):
375 """Delete CG snapshot"""
376 api = '/application/consistency-groups/%s/snapshots' % self.cg_uuid
377 dummy, error = rest_generic.delete_async(self.rest_api, api, current['snapshot_uuid'])
378 if error:
379 self.module.fail_json(msg='Error deleting consistency group snapshot %s: %s' % (self.parameters['snapshot'], to_native(error)),
380 exception=traceback.format_exc())
381
382 def apply(self):
383 """Applies action from playbook"""
384 if not self.use_rest:
385 if not self.module.check_mode:
386 changed = self.cgcreate()
387 self.module.exit_json(changed=changed)
388 current = self.get_cg_snapshot_rest()
389 cd_action = self.na_helper.get_cd_action(current, self.parameters)
390
391 if self.na_helper.changed and not self.module.check_mode:
392 if cd_action == 'create':
393 self.create_cg_snapshot_rest()
394 elif cd_action == 'delete':
395 self.delete_cg_snapshot_rest(current)
396 result = netapp_utils.generate_result(self.na_helper.changed, cd_action)
397 self.module.exit_json(**result)
398
399
400 def main():
401 """Execute action from playbook"""
402 cg_obj = NetAppONTAPCGSnapshot()
403 cg_obj.apply()
404
405
406 if __name__ == '__main__':
407 main()