Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 '''
4 na_ontap_snapmirror
5 '''
6
7 # (c) 2018-2026, NetApp, Inc
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = '''
14 author: NetApp Ansible Team (@carchi8py) <[email protected]>
15 description:
16 - Create/Delete/Update/Initialize/Break/Resync/Resume SnapMirror volume/vserver relationships for ONTAP/ONTAP
17 - This includes SVM replication, aka vserver DR
18 - Create/Delete/Update/Initialize SnapMirror volume relationship between ElementSW and ONTAP
19 - Modify schedule for a SnapMirror relationship for ONTAP/ONTAP and ElementSW/ONTAP
20 - Pre-requisite for ElementSW to ONTAP relationship or vice-versa is an established SnapMirror endpoint for ONTAP cluster with ElementSW UI
21 - Pre-requisite for ElementSW to ONTAP relationship or vice-versa is to have SnapMirror enabled in the ElementSW volume
22 - For creating a SnapMirror ElementSW/ONTAP relationship, an existing ONTAP/ElementSW relationship should be present
23 - Performs resync if the C(relationship_state=active) and the current mirror state of the snapmirror relationship is broken-off
24 - Performs resume if the C(relationship_state=active), the current snapmirror relationship status is quiesced and mirror state is snapmirrored
25 - Performs restore if the C(relationship_type=restore) and all other operations will not be performed during this task
26 extends_documentation_fragment:
27 - netapp.ontap.netapp.na_ontap
28 - netapp.ontap.netapp.na_ontap_peer
29 module: na_ontap_snapmirror
30 options:
31 state:
32 choices: ['present', 'absent']
33 description:
34 - Whether the specified relationship should exist or not.
35 default: present
36 type: str
37 source_volume:
38 description:
39 - Specifies the name of the source volume for the SnapMirror.
40 - Deprecated as of 21.2.0, use source_endpoint and path.
41 type: str
42 destination_volume:
43 description:
44 - Specifies the name of the destination volume for the SnapMirror.
45 - Deprecated as of 21.2.0, use source_endpoint and path.
46 type: str
47 source_vserver:
48 description:
49 - Name of the source vserver for the SnapMirror.
50 - Deprecated as of 21.2.0, use source_endpoint and path, or svm.
51 type: str
52 destination_vserver:
53 description:
54 - Name of the destination vserver for the SnapMirror.
55 - Deprecated as of 21.2.0, use destination_endpoint and path, or svm.
56 type: str
57 source_path:
58 description:
59 - Specifies the source endpoint of the SnapMirror relationship.
60 - If the source is an ONTAP volume, format should be <[vserver:][volume]> or <[[cluster:]//vserver/]volume>
61 - If the source is an ElementSW volume, format should be <[Element_SVIP]:/lun/[Element_VOLUME_ID]>
62 - If the source is an ElementSW volume, the volume should have SnapMirror enabled.
63 - Deprecated as of 21.2.0, use source_endpoint and path.
64 type: str
65 destination_path:
66 description:
67 - Specifies the destination endpoint of the SnapMirror relationship.
68 - Deprecated as of 21.2.0, use destination_endpoint and path.
69 type: str
70 relationship_type:
71 choices: ['data_protection', 'load_sharing', 'vault', 'restore', 'transition_data_protection',
72 'extended_data_protection']
73 type: str
74 description:
75 - Specify the type of SnapMirror relationship.
76 - for 'restore' unless 'source_snapshot' is specified the most recent Snapshot copy on the source volume is restored.
77 - restore SnapMirror is not idempotent.
78 - With REST, only 'extended_data_protection' and 'restore' are supported.
79 schedule:
80 description:
81 - Specify the name of the current schedule, which is used to update the SnapMirror relationship.
82 - Optional for create, modifiable.
83 - With REST, this option requires ONTAP 9.11.1 or later.
84 type: str
85 aliases: ['transfer_schedule']
86 version_added: 22.2.0
87 policy:
88 description:
89 - Specify the name of the SnapMirror policy that applies to this relationship.
90 version_added: 2.8.0
91 type: str
92 source_hostname:
93 description:
94 - DEPRECATED - please use C(peer_options).
95 - Source hostname or management IP address for ONTAP or ElementSW cluster.
96 - If present, when state is absent, the relationship is released at the source before being deleted at destination.
97 - It is recommended to always release before deleting, so make sure this parameter is present if the source hostname is known.
98 type: str
99 source_username:
100 description:
101 - DEPRECATED - please use C(peer_options).
102 - Source username for ONTAP or ElementSW cluster.
103 - Optional if this is same as destination username.
104 type: str
105 source_password:
106 description:
107 - DEPRECATED - please use C(peer_options).
108 - Source password for ONTAP or ElementSW cluster.
109 - Optional if this is same as destination password.
110 type: str
111 connection_type:
112 description:
113 - Type of SnapMirror relationship.
114 - Pre-requisite for either elementsw_ontap or ontap_elementsw the ElementSW volume should have enableSnapmirror option set to true.
115 - For using ontap_elementsw, elementsw_ontap snapmirror relationship should exist.
116 choices: ['ontap_ontap', 'elementsw_ontap', 'ontap_elementsw']
117 default: ontap_ontap
118 type: str
119 version_added: 2.9.0
120 max_transfer_rate:
121 description:
122 - Specifies the upper bound, in kilobytes per second, at which data is transferred.
123 - Default is unlimited, it can be explicitly set to 0 as unlimited.
124 - Not supported with REST.
125 type: int
126 version_added: 2.9.0
127 initialize:
128 description:
129 - Specifies whether to initialize SnapMirror relation.
130 - Default is True, it can be explicitly set to False to avoid initializing SnapMirror relation.
131 default: true
132 type: bool
133 version_added: '19.11.0'
134 update:
135 description:
136 - Specifies whether to update the destination endpoint of the SnapMirror relationship only if the relationship is already present and active.
137 - Default is True.
138 default: true
139 type: bool
140 version_added: '20.2.0'
141 relationship_info_only:
142 description:
143 - If relationship-info-only is set to true then only relationship information is removed.
144 default: false
145 type: bool
146 version_added: '20.4.0'
147 relationship_state:
148 description:
149 - Specifies whether to break SnapMirror relation or establish a SnapMirror relationship.
150 - state must be present to use this option.
151 default: active
152 choices: ['active', 'broken']
153 type: str
154 version_added: '20.2.0'
155 source_snapshot:
156 description:
157 - Specifies the Snapshot from the source to be restored.
158 type: str
159 version_added: '20.6.0'
160 identity_preserve:
161 description:
162 - Specifies whether or not the identity of the source Vserver is replicated to the destination Vserver.
163 - If this parameter is set to true, the source Vserver's configuration will additionally be replicated to the destination.
164 - If the parameter is set to false, then only the source Vserver's volumes and RBAC configuration are replicated to the destination.
165 - Not supported with REST.
166 type: bool
167 version_added: 2.9.0
168 create_destination:
169 description:
170 - Requires ONTAP 9.7 or later.
171 - Creates the destination volume if enabled and destination_volume is present or destination_path includes a volume name.
172 - Creates and peers the destination vserver for SVM DR.
173 type: dict
174 version_added: 21.1.0
175 suboptions:
176 enabled:
177 description:
178 - Whether to create the destination volume or vserver.
179 - This is automatically enabled if any other suboption is present.
180 type: bool
181 default: true
182 storage_service:
183 description: storage service associated with the destination endpoint.
184 type: dict
185 suboptions:
186 enabled:
187 description: whether to create the destination endpoint using storage service.
188 type: bool
189 enforce_performance:
190 description: whether to enforce storage service performance on the destination endpoint.
191 type: bool
192 name:
193 description: the performance service level (PSL) for this volume endpoint.
194 type: str
195 choices: ['value', 'performance', 'extreme']
196 tiering:
197 description:
198 - Cloud tiering policy.
199 type: dict
200 suboptions:
201 policy:
202 description:
203 - Cloud tiering policy.
204 choices: ['all', 'auto', 'none', 'snapshot-only']
205 type: str
206 supported:
207 description:
208 - enable provisioning of the destination endpoint volumes on FabricPool aggregates.
209 - only supported for FlexVol volume, FlexGroup volume, and Consistency Group endpoints.
210 type: bool
211 destination_cluster:
212 description:
213 - Requires ONTAP 9.7 or higher.
214 - Required to create the destination vserver for SVM DR or the destination volume.
215 - Deprecated as of 21.2.0, use destination_endpoint and cluster.
216 type: str
217 version_added: 21.1.0
218 source_cluster:
219 description:
220 - Requires ONTAP 9.7 or higher.
221 - Required to create the peering relationship between source and destination SVMs.
222 - Deprecated as of 21.2.0, use source_endpoint and cluster.
223 type: str
224 version_added: 21.1.0
225 source_endpoint:
226 description:
227 - source endpoint of a SnapMirror relationship.
228 type: dict
229 version_added: 21.2.0
230 suboptions:
231 cluster:
232 description:
233 - Requires ONTAP 9.7 or higher.
234 - Required to create the peering relationship between source and destination SVMs.
235 type: str
236 consistency_group_volumes:
237 description:
238 - Requires ONTAP 9.8 or higher.
239 - Mandatory property for a Consistency Group endpoint. Specifies the list of FlexVol volumes for a Consistency Group.
240 type: list
241 elements: str
242 ipspace:
243 description:
244 - Requires ONTAP 9.8 or higher.
245 - Optional property to specify the IPSpace of the SVM.
246 type: str
247 path:
248 description:
249 - The source endpoint for the relationship.
250 - If the source is an ONTAP volume (FlexVol or FlexGroup), format should be <vserver:volume>
251 - For SVM DR, format should be <vserver:>
252 - For a consistency group, format should be <vserver:/cg/cg_name>
253 - If the source is an ElementSW volume, format should be <Element_SVIP:/lun/Element_VOLUME_ID>
254 - If the source is an ElementSW volume, the volume should have SnapMirror enabled.
255 type: str
256 required: true
257 svm:
258 description:
259 - The name of the SVM. Not sure when this is needed.
260 type: str
261 destination_endpoint:
262 description:
263 - destination endpoint of a SnapMirror relationship.
264 type: dict
265 version_added: 21.2.0
266 suboptions:
267 cluster:
268 description:
269 - Requires ONTAP 9.7 or higher.
270 - Required to create the destination vserver for SVM DR or the destination volume.
271 type: str
272 consistency_group_volumes:
273 description:
274 - Requires ONTAP 9.8 or higher.
275 - Mandatory property for a Consistency Group endpoint. Specifies the list of FlexVol volumes for a Consistency Group.
276 type: list
277 elements: str
278 ipspace:
279 description:
280 - Requires ONTAP 9.8 or higher.
281 - Optional property to specify the IPSpace of the SVM.
282 type: str
283 path:
284 description:
285 - The destination endpoint for the relationship.
286 - format is <vserver:volume>, <vserver:>, <vserver:/cg/cg_name>
287 type: str
288 required: true
289 svm:
290 description:
291 - The name of the SVM. Not sure when this is needed.
292 type: str
293 transferring_time_out:
294 description:
295 - How long to wait when a transfer is in progress (after initializing for instance). Unit is seconds.
296 default: 300
297 type: int
298 version_added: 21.20.0
299 quiesced_time_out:
300 description:
301 - How long to wait for a relationship to quiesce. Unit is seconds.
302 default: 300
303 type: int
304 version_added: 22.14.0
305 clean_up_failure:
306 description:
307 - An optional parameter to recover from an aborted or failed restore operation.
308 - Any temporary RST relationship is removed from the destination Vserver.
309 - Only supported with ZAPI.
310 default: False
311 type: bool
312 version_added: 21.20.0
313 validate_source_path:
314 description:
315 - The relationship is found based on the destination as it is unique.
316 - By default, the source information is verified and an error is reported if there is a mismatch.
317 This would mean the destination is already used by another relationship.
318 - The check accounts for a local vserver name that may be different from the remote vserver name.
319 - This may be disabled in case the check is too strict, to unconditionally delete a realtionship for instance.
320 default: True
321 type: bool
322 version_added: 21.21.0
323 identity_preservation:
324 description:
325 - Specifies which configuration of the source SVM is replicated to the destination SVM.
326 - This property is applicable only for SVM data protection with "async" policy type.
327 - Only supported with REST and requires ONTAP 9.11.1 or later.
328 type: str
329 choices: ['full', 'exclude_network_config', 'exclude_network_and_protocol_config']
330 version_added: '22.4.0'
331 quick_resync:
332 description:
333 - Set to true to reduce resync time by not preserving storage efficiency.
334 - This property is applicable only for relationships with FlexVol volume endpoints and SVMDR relationships
335 when the PATCH state is being changed to "snapmirrored".
336 - Only supported with REST.
337 type: bool
338 version_added: 23.1.0
339 time_out:
340 version_added: 23.4.0
341 description:
342 - With C(wait_for_completion) set, specifies time to wait for snapmirror operation in seconds.
343 - Only supported with REST.
344 type: int
345 default: 30
346 wait_for_completion:
347 version_added: 23.4.0
348 description:
349 - Set this parameter to 'true' for synchronous execution.
350 - For asynchronous, execution exits as soon as the request is sent, and the operation continues in the background.
351 - Only supported with REST.
352 type: bool
353 default: true
354
355 lambda_config:
356 description:
357 - Configuration parameters for AWS Lambda proxy functionality.
358 - These option and suboptions are only supported with REST.
359 type: dict
360 version_added: 23.4.0
361 suboptions:
362 function_name:
363 description:
364 - The name of the AWS Lambda function to invoke.
365 type: str
366 required: true
367 aws_region:
368 description:
369 - The name of the AWS region.
370 type: str
371 required: true
372 aws_profile:
373 description:
374 - The name of the AWS profile to use for authentication.
375 type: str
376
377 short_description: "NetApp ONTAP or ElementSW Manage SnapMirror"
378 version_added: 2.7.0
379 notes:
380 - supports REST and ZAPI.
381 - supports check_mode.
382 - restore is not idempotent.
383 - snapmirror runs on the destination for most operations, peer_options identify the source cluster.
384 - ONTAP supports either username/password or a SSL certificate for authentication.
385 - ElementSW only supports username/password for authentication.
386 - Supports AWS Lambda proxy functionality when using REST. See README for example usage.
387 '''
388
389 EXAMPLES = """
390 # creates and initializes the snapmirror
391 - name: Create ONTAP/ONTAP SnapMirror
392 netapp.ontap.na_ontap_snapmirror:
393 state: present
394 source_volume: test_src
395 destination_volume: test_dest
396 source_vserver: ansible_src
397 destination_vserver: ansible_dest
398 schedule: hourly
399 policy: MirrorAllSnapshots
400 max_transfer_rate: 1000
401 initialize: false
402 wait_for_completion: true
403 time_out: 90
404 hostname: "{{ destination_cluster_hostname }}"
405 username: "{{ destination_cluster_username }}"
406 password: "{{ destination_cluster_password }}"
407
408 # creates and initializes the snapmirror between vservers
409 - name: Create ONTAP/ONTAP vserver SnapMirror
410 netapp.ontap.na_ontap_snapmirror:
411 state: present
412 source_vserver: ansible_src
413 destination_vserver: ansible_dest
414 identity_preserve: true
415 hostname: "{{ destination_cluster_hostname }}"
416 username: "{{ destination_cluster_username }}"
417 password: "{{ destination_cluster_password }}"
418
419 # existing snapmirror relation with status 'snapmirrored' will be initialized
420 - name: Inititalize ONTAP/ONTAP SnapMirror
421 netapp.ontap.na_ontap_snapmirror:
422 state: present
423 source_path: 'ansible:test'
424 destination_path: 'ansible:dest'
425 relationship_state: active
426 hostname: "{{ destination_cluster_hostname }}"
427 username: "{{ destination_cluster_username }}"
428 password: "{{ destination_cluster_password }}"
429
430 - name: Delete SnapMirror
431 netapp.ontap.na_ontap_snapmirror:
432 state: absent
433 destination_path: <path>
434 relationship_info_only: true
435 source_hostname: "{{ source_hostname }}"
436 hostname: "{{ destination_cluster_hostname }}"
437 username: "{{ destination_cluster_username }}"
438 password: "{{ destination_cluster_password }}"
439
440 - name: Break SnapMirror
441 netapp.ontap.na_ontap_snapmirror:
442 state: present
443 relationship_state: broken
444 destination_path: <path>
445 source_hostname: "{{ source_hostname }}"
446 hostname: "{{ destination_cluster_hostname }}"
447 username: "{{ destination_cluster_username }}"
448 password: "{{ destination_cluster_password }}"
449
450 - name: Restore SnapMirror volume using location (Idempotency)
451 netapp.ontap.na_ontap_snapmirror:
452 state: present
453 source_path: <path>
454 destination_path: <path>
455 relationship_type: restore
456 source_snapshot: "{{ snapshot }}"
457 hostname: "{{ destination_cluster_hostname }}"
458 username: "{{ destination_cluster_username }}"
459 password: "{{ destination_cluster_password }}"
460
461 - name: Set schedule to NULL
462 netapp.ontap.na_ontap_snapmirror:
463 state: present
464 destination_path: <path>
465 schedule: ""
466 hostname: "{{ destination_cluster_hostname }}"
467 username: "{{ destination_cluster_username }}"
468 password: "{{ destination_cluster_password }}"
469
470 - name: Create SnapMirror from ElementSW to ONTAP
471 netapp.ontap.na_ontap_snapmirror:
472 state: present
473 connection_type: elementsw_ontap
474 source_path: '10.10.10.10:/lun/300'
475 destination_path: 'ansible_test:ansible_dest_vol'
476 schedule: hourly
477 policy: MirrorLatest
478 hostname: "{{ netapp_hostname }}"
479 username: "{{ netapp_username }}"
480 password: "{{ netapp_password }}"
481 source_hostname: " {{ Element_cluster_mvip }}"
482 source_username: "{{ Element_cluster_username }}"
483 source_password: "{{ Element_cluster_password }}"
484
485 - name: Create SnapMirror from ONTAP to ElementSW
486 netapp.ontap.na_ontap_snapmirror:
487 state: present
488 connection_type: ontap_elementsw
489 destination_path: '10.10.10.10:/lun/300'
490 source_path: 'ansible_test:ansible_dest_vol'
491 policy: MirrorLatest
492 hostname: "{{ Element_cluster_mvip }}"
493 username: "{{ Element_cluster_username }}"
494 password: "{{ Element_cluster_password }}"
495 source_hostname: " {{ netapp_hostname }}"
496 source_username: "{{ netapp_username }}"
497 source_password: "{{ netapp_password }}"
498
499 - name: Create SnapMirror relationship (create destination volume)
500 netapp.ontap.na_ontap_snapmirror:
501 state: present
502 source_endpoint:
503 cluster: "{{ _source_cluster }}"
504 path: "{{ source_vserver + ':' + source_volume }}"
505 destination_endpoint:
506 cluster: "{{ _destination_cluster }}"
507 path: "{{ destination_vserver_VOLDP + ':' + destination_volume }}"
508 create_destination:
509 enabled: true
510 hostname: "{{ destination_hostname }}"
511 username: "{{ username }}"
512 password: "{{ password }}"
513 https: true
514 validate_certs: false
515
516 - name: Create SnapMirror relationship - SVM DR (creating and peering destination svm)
517 tags: create_svmdr
518 netapp.ontap.na_ontap_snapmirror:
519 state: present
520 source_endpoint:
521 cluster: "{{ _source_cluster }}"
522 path: "{{ source_vserver + ':' }}"
523 destination_endpoint:
524 cluster: "{{ _destination_cluster }}"
525 path: "{{ destination_vserver_SVMDR + ':' }}"
526 create_destination:
527 enabled: true
528 hostname: "{{ destination_hostname }}"
529 username: "{{ username }}"
530 password: "{{ password }}"
531 https: true
532 validate_certs: false
533
534 - name: Resync SnapMirror relationship - SVM DR
535 tags: resync_svmdr
536 netapp.ontap.na_ontap_snapmirror:
537 state: present
538 source_endpoint:
539 cluster: "{{ _source_cluster }}"
540 path: "{{ source_vserver + ':' }}"
541 destination_endpoint:
542 cluster: "{{ _destination_cluster }}"
543 path: "{{ destination_vserver_SVMDR + ':' }}"
544 create_destination:
545 enabled: true
546 relationship_state: active
547 quick_resync: true
548 hostname: "{{ destination_hostname }}"
549 username: "{{ username }}"
550 password: "{{ password }}"
551 https: true
552 validate_certs: false
553 """
554
555 RETURN = """
556 """
557
558 import re
559 import time
560 import traceback
561 from ansible.module_utils.basic import AnsibleModule
562 from ansible.module_utils._text import to_native
563 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
564 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_elementsw_module import NaElementSWModule
565 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
566 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
567
568 HAS_SF_SDK = netapp_utils.has_sf_sdk()
569 try:
570 import solidfire.common
571 except ImportError:
572 HAS_SF_SDK = False
573
574
575 class NetAppONTAPSnapmirror(object):
576 """
577 Class with SnapMirror methods
578 """
579
580 def __init__(self):
581
582 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
583 self.argument_spec.update(dict(
584 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
585 destination_endpoint=dict(type='dict', options=dict(
586 cluster=dict(type='str'),
587 consistency_group_volumes=dict(type='list', elements='str'),
588 ipspace=dict(type='str'),
589 path=dict(required=True, type='str'),
590 svm=dict(type='str'),
591 )),
592 source_endpoint=dict(type='dict', options=dict(
593 cluster=dict(type='str'),
594 consistency_group_volumes=dict(type='list', elements='str'),
595 ipspace=dict(type='str'),
596 path=dict(required=True, type='str'),
597 svm=dict(type='str'),
598 )),
599 source_vserver=dict(required=False, type='str'),
600 destination_vserver=dict(required=False, type='str'),
601 source_volume=dict(required=False, type='str'),
602 destination_volume=dict(required=False, type='str'),
603 source_path=dict(required=False, type='str'),
604 destination_path=dict(required=False, type='str'),
605 schedule=dict(required=False, type='str', aliases=['transfer_schedule']),
606 policy=dict(required=False, type='str'),
607 relationship_type=dict(required=False, type='str',
608 choices=['data_protection', 'load_sharing',
609 'vault', 'restore',
610 'transition_data_protection',
611 'extended_data_protection']
612 ),
613 connection_type=dict(required=False, type='str',
614 choices=['ontap_ontap', 'elementsw_ontap', 'ontap_elementsw'],
615 default='ontap_ontap'),
616 peer_options=dict(type='dict', options=netapp_utils.na_ontap_host_argument_spec_peer()),
617 source_hostname=dict(required=False, type='str'),
618 source_username=dict(required=False, type='str'),
619 source_password=dict(required=False, type='str', no_log=True),
620 max_transfer_rate=dict(required=False, type='int'),
621 initialize=dict(required=False, type='bool', default=True),
622 update=dict(required=False, type='bool', default=True),
623 identity_preserve=dict(required=False, type='bool'),
624 identity_preservation=dict(required=False, type="str", choices=['full', 'exclude_network_config', 'exclude_network_and_protocol_config']),
625 relationship_state=dict(required=False, type='str', choices=['active', 'broken'], default='active'),
626 relationship_info_only=dict(required=False, type='bool', default=False),
627 source_snapshot=dict(required=False, type='str'),
628 create_destination=dict(required=False, type='dict', options=dict(
629 enabled=dict(type='bool', default=True),
630 storage_service=dict(type='dict', options=dict(
631 enabled=dict(type='bool'),
632 enforce_performance=dict(type='bool'),
633 name=dict(type='str', choices=['value', 'performance', 'extreme']),
634 )),
635 tiering=dict(type='dict', options=dict(
636 policy=dict(type='str', choices=['all', 'auto', 'none', 'snapshot-only']),
637 supported=dict(type='bool')
638 )),
639 )),
640 source_cluster=dict(required=False, type='str'),
641 destination_cluster=dict(required=False, type='str'),
642 transferring_time_out=dict(required=False, type='int', default=300),
643 quiesced_time_out=dict(required=False, type='int', default=300),
644 clean_up_failure=dict(required=False, type='bool', default=False),
645 validate_source_path=dict(required=False, type='bool', default=True),
646 quick_resync=dict(required=False, type='bool'),
647 time_out=dict(required=False, type='int', default=30),
648 wait_for_completion=dict(required=False, type='bool', default=True),
649 ))
650 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
651 # Add Lambda support to peer_options
652 self.argument_spec['peer_options']['options'].update(netapp_utils.na_ontap_lambda_argument_spec())
653
654 self.module = AnsibleModule(
655 argument_spec=self.argument_spec,
656 mutually_exclusive=[
657 ('source_endpoint', 'source_cluster'),
658 ('source_endpoint', 'source_path'),
659 ('source_endpoint', 'source_volume'),
660 ('source_endpoint', 'source_vserver'),
661 ('destination_endpoint', 'destination_cluster'),
662 ('destination_endpoint', 'destination_path'),
663 ('destination_endpoint', 'destination_volume'),
664 ('destination_endpoint', 'destination_vserver'),
665 ('peer_options', 'source_hostname'),
666 ('peer_options', 'source_username'),
667 ('peer_options', 'source_password'),
668 ('identity_preserve', 'identity_preservation')
669 ],
670 required_if=[
671 ['use_lambda', True, ('lambda_config',)]
672 ],
673 required_together=(['source_volume', 'destination_volume'],
674 ['source_vserver', 'destination_vserver'],
675 ['source_endpoint', 'destination_endpoint'],
676 ),
677 supports_check_mode=True
678 )
679
680 self.na_helper = NetAppModule()
681 self.parameters = self.na_helper.set_parameters(self.module.params)
682 self.policy_type = None
683 self.new_style = False
684 # when deleting, ignore previous errors, but report them if delete fails
685 self.previous_errors = []
686 # setup later if required
687 self.source_server = None
688 # only for ElementSW -> ONTAP snapmirroring, validate if ElementSW SDK is available
689 if self.parameters.get('connection_type') in ['elementsw_ontap', 'ontap_elementsw'] and HAS_SF_SDK is False:
690 self.module.fail_json(msg="Unable to import the SolidFire Python SDK")
691
692 self.src_rest_api = None
693 self.src_use_rest = None
694 self.set_source_peer()
695 self.rest_api, self.use_rest = self.setup_rest()
696 if not self.use_rest:
697 if self.parameters.get('use_lambda'):
698 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
699 self.server = self.setup_zapi()
700
701 def set_source_peer(self):
702 if self.parameters.get('source_hostname') is None and self.parameters.get('peer_options') is None:
703 if self.parameters.get('connection_type') == 'ontap_elementsw':
704 return self.module.fail_json(msg='Error: peer_options are required to identify ONTAP cluster with connection_type: ontap_elementsw')
705 if self.parameters.get('connection_type') == 'elementsw_ontap':
706 return self.module.fail_json(msg='Error: peer_options are required to identify SolidFire cluster with connection_type: elementsw_ontap')
707 if self.parameters.get('source_hostname') is not None:
708 # if source_hostname is present, peer_options is absent
709 self.parameters['peer_options'] = dict(
710 hostname=self.parameters.get('source_hostname'),
711 username=self.parameters.get('source_username'),
712 password=self.parameters.get('source_password'),
713 )
714 elif self.na_helper.safe_get(self.parameters, ['peer_options', 'hostname']):
715 self.parameters['source_hostname'] = self.parameters['peer_options']['hostname']
716 if 'peer_options' in self.parameters:
717 netapp_utils.setup_host_options_from_module_params(
718 self.parameters['peer_options'], self.module,
719 netapp_utils.na_ontap_host_argument_spec_peer().keys())
720
721 def setup_rest(self):
722 unsupported_rest_properties = ['identity_preserve', 'max_transfer_rate']
723 host_options = self.parameters['peer_options'] if self.parameters.get('connection_type') == 'ontap_elementsw' else None
724 rest_api = netapp_utils.OntapRestAPI(self.module, host_options=host_options)
725 rtype = self.parameters.get('relationship_type')
726 if rtype not in (None, 'extended_data_protection', 'restore'):
727 unsupported_rest_properties.append('relationship_type')
728 used_unsupported_rest_properties = [x for x in unsupported_rest_properties if x in self.parameters]
729 ontap_97_options = ['create_destination', 'source_cluster', 'destination_cluster']
730 partially_supported_rest_properties = [(property, (9, 7)) for property in ontap_97_options]
731 partially_supported_rest_properties.extend([('schedule', (9, 11, 1)), ('identity_preservation', (9, 11, 1))])
732 use_rest, error = rest_api.is_rest_supported_properties(
733 self.parameters, used_unsupported_rest_properties, partially_supported_rest_properties, report_error=True)
734 if error is not None:
735 if 'relationship_type' in error:
736 error = error.replace('relationship_type', 'relationship_type: %s' % rtype)
737 if 'schedule' in error:
738 error += ' - With REST use the policy option to define a schedule.'
739 self.module.fail_json(msg=error)
740
741 if not use_rest and any(x in self.parameters for x in ontap_97_options):
742 self.module.fail_json(msg='Error: %s' % rest_api.options_require_ontap_version(ontap_97_options, version='9.7', use_rest=use_rest))
743 return rest_api, use_rest
744
745 def setup_zapi(self):
746 if 'wait_for_completion' in self.parameters or 'time_out' in self.parameters:
747 self.module.warn("'wait_for_completion' and 'time_out' parameters are only supported when using REST.")
748 if self.parameters.get('identity_preservation'):
749 self.module.fail_json(msg="Error: The option identity_preservation is supported only with REST.")
750 if not netapp_utils.has_netapp_lib():
751 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
752 host_options = self.parameters['peer_options'] if self.parameters.get('connection_type') == 'ontap_elementsw' else None
753 return netapp_utils.setup_na_ontap_zapi(module=self.module, host_options=host_options)
754
755 def set_element_connection(self, kind):
756 if kind == 'source':
757 elem = netapp_utils.create_sf_connection(module=self.module, host_options=self.parameters['peer_options'])
758 elif kind == 'destination':
759 elem = netapp_utils.create_sf_connection(module=self.module, host_options=self.parameters)
760 elementsw_helper = NaElementSWModule(elem)
761 return elementsw_helper, elem
762
763 def snapmirror_get_iter(self, destination=None):
764 """
765 Compose NaElement object to query current SnapMirror relations using destination-path
766 SnapMirror relation for a destination path is unique
767 :return: NaElement object for SnapMirror-get-iter
768 """
769 snapmirror_get_iter = netapp_utils.zapi.NaElement('snapmirror-get-iter')
770 query = netapp_utils.zapi.NaElement('query')
771 snapmirror_info = netapp_utils.zapi.NaElement('snapmirror-info')
772 if destination is None:
773 destination = self.parameters['destination_path']
774 snapmirror_info.add_new_child('destination-location', destination)
775 query.add_child_elem(snapmirror_info)
776 snapmirror_get_iter.add_child_elem(query)
777 return snapmirror_get_iter
778
779 def snapmirror_get(self, destination=None):
780 """
781 Get current SnapMirror relations
782 :return: Dictionary of current SnapMirror details if query successful, else None
783 """
784 if self.use_rest:
785 return self.snapmirror_get_rest(destination)
786
787 snapmirror_get_iter = self.snapmirror_get_iter(destination)
788 try:
789 result = self.server.invoke_successfully(snapmirror_get_iter, enable_tunneling=True)
790 except netapp_utils.zapi.NaApiError as error:
791 self.module.fail_json(msg='Error fetching snapmirror info: %s' % to_native(error),
792 exception=traceback.format_exc())
793 if result.get_child_by_name('num-records') and \
794 int(result.get_child_content('num-records')) > 0:
795 snapmirror_info = result.get_child_by_name('attributes-list').get_child_by_name(
796 'snapmirror-info')
797 snap_info = {}
798 snap_info['mirror_state'] = snapmirror_info.get_child_content('mirror-state')
799 snap_info['status'] = snapmirror_info.get_child_content('relationship-status')
800 snap_info['schedule'] = snapmirror_info.get_child_content('schedule')
801 snap_info['policy'] = snapmirror_info.get_child_content('policy')
802 snap_info['relationship_type'] = snapmirror_info.get_child_content('relationship-type')
803 snap_info['current_transfer_type'] = snapmirror_info.get_child_content('current-transfer-type')
804 snap_info['source_path'] = snapmirror_info.get_child_content('source-location')
805 if snapmirror_info.get_child_by_name('max-transfer-rate'):
806 snap_info['max_transfer_rate'] = int(snapmirror_info.get_child_content('max-transfer-rate'))
807 if snapmirror_info.get_child_by_name('last-transfer-error'):
808 snap_info['last_transfer_error'] = snapmirror_info.get_child_content('last-transfer-error')
809 if snapmirror_info.get_child_by_name('is-healthy') is not None:
810 snap_info['is_healthy'] = self.na_helper.get_value_for_bool(True, snapmirror_info.get_child_content('is-healthy'))
811 if snapmirror_info.get_child_by_name('unhealthy-reason'):
812 snap_info['unhealthy_reason'] = snapmirror_info.get_child_content('unhealthy-reason')
813 if snap_info['schedule'] is None:
814 snap_info['schedule'] = ""
815 return snap_info
816 return None
817
818 def wait_for_idle_status(self):
819 # sleep for a maximum of X seconds (with a default of 5 minutes), in 30 seconds increments
820 transferring_time_out = self.parameters['transferring_time_out']
821 increment = 30
822 if transferring_time_out <= 0:
823 return self.snapmirror_get()
824 for __ in range(0, transferring_time_out, increment):
825 time.sleep(increment)
826 current = self.snapmirror_get()
827 if current and current['status'] != 'transferring':
828 return current
829 self.module.warn('SnapMirror relationship is still transferring after %d seconds.' % transferring_time_out)
830 return current
831
832 def wait_for_quiesced_status(self):
833 # sleep for a maximum of X seconds (with a default of 5 minutes), in 10 seconds increments
834 quiesced_time_out = self.parameters['quiesced_time_out']
835 increment = 10
836 for __ in range(0, quiesced_time_out, increment):
837 time.sleep(increment)
838 sm_info = self.snapmirror_get()
839 if sm_info and (sm_info['status'] == 'quiesced' or sm_info['mirror_state'] == 'paused'):
840 return
841 self.module.fail_json(msg='Taking a long time to quiesce SnapMirror relationship after %d seconds, try again later' % quiesced_time_out)
842
843 def check_if_remote_volume_exists(self):
844 """
845 Validate existence of source volume
846 :return: True if volume exists, False otherwise
847 """
848 self.set_source_cluster_connection()
849
850 if self.src_use_rest:
851 return self.check_if_remote_volume_exists_rest()
852
853 # do a get volume to check if volume exists or not
854 volume_info = netapp_utils.zapi.NaElement('volume-get-iter')
855 volume_attributes = netapp_utils.zapi.NaElement('volume-attributes')
856 volume_id_attributes = netapp_utils.zapi.NaElement('volume-id-attributes')
857 volume_id_attributes.add_new_child('name', self.parameters['source_volume'])
858 # if source_volume is present, then source_vserver is also guaranteed to be present
859 volume_id_attributes.add_new_child('vserver-name', self.parameters['source_vserver'])
860 volume_attributes.add_child_elem(volume_id_attributes)
861 query = netapp_utils.zapi.NaElement('query')
862 query.add_child_elem(volume_attributes)
863 volume_info.add_child_elem(query)
864 try:
865 result = self.source_server.invoke_successfully(volume_info, True)
866 except netapp_utils.zapi.NaApiError as error:
867 self.module.fail_json(msg='Error fetching source volume details %s: %s'
868 % (self.parameters['source_volume'], to_native(error)),
869 exception=traceback.format_exc())
870 return bool(result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) > 0)
871
872 def get_svm_from_destination_vserver_or_path(self):
873 svm_name = self.parameters.get('destination_vserver')
874 if svm_name is None:
875 path = self.parameters.get('destination_path')
876 if path is not None:
877 # if there is no ':' in path, it returns path
878 svm_name = path.split(':', 1)[0]
879 return svm_name
880
881 def set_initialization_state(self):
882 """
883 return:
884 'snapmirrored' for relationships with a policy of type 'async'
885 'in_sync' for relationships with a policy of type 'sync'
886 """
887 policy_type = 'async' # REST defaults to Asynchronous
888 if self.na_helper.safe_get(self.parameters, ['destination_endpoint', 'consistency_group_volumes']) is not None:
889 # except for consistency groups
890 policy_type = 'sync'
891 if self.parameters.get('policy') is not None:
892 svm_name = self.get_svm_from_destination_vserver_or_path()
893 policy_type, error = self.snapmirror_policy_rest_get(self.parameters['policy'], svm_name)
894 if error:
895 error = 'Error fetching SnapMirror policy: %s' % error
896 elif policy_type is None:
897 error = 'Error: cannot find policy %s for vserver %s' % (self.parameters['policy'], svm_name)
898 elif policy_type not in ('async', 'sync'):
899 error = 'Error: unexpected type: %s for policy %s for vserver %s' % (policy_type, self.parameters['policy'], svm_name)
900 if error:
901 self.module.fail_json(msg=error)
902 return 'snapmirrored' if policy_type == 'async' else 'in_sync'
903
904 @staticmethod
905 def string_or_none(value):
906 """ REST expect null for "" """
907 return value or None
908
909 def get_create_body(self):
910 """
911 It gathers the required information for snapmirror create
912 """
913 initialized = False
914 body = {
915 "source": self.na_helper.filter_out_none_entries(self.parameters['source_endpoint']),
916 "destination": self.na_helper.filter_out_none_entries(self.parameters['destination_endpoint'])
917 }
918 if self.na_helper.safe_get(self.parameters, ['create_destination', 'enabled']): # testing for True
919 body['create_destination'] = self.na_helper.filter_out_none_entries(self.parameters['create_destination'])
920 if self.parameters['initialize']:
921 body['state'] = self.set_initialization_state()
922 initialized = True
923 if self.na_helper.safe_get(self.parameters, ['policy']) is not None:
924 body['policy'] = {'name': self.parameters['policy']}
925 if self.na_helper.safe_get(self.parameters, ['schedule']) is not None:
926 body['transfer_schedule'] = {'name': self.string_or_none(self.parameters['schedule'])}
927 if self.parameters.get('identity_preservation'):
928 body['identity_preservation'] = self.parameters['identity_preservation']
929 return body, initialized
930
931 def snapmirror_create(self):
932 """
933 Create a SnapMirror relationship
934 """
935 if self.parameters.get('peer_options') and self.parameters.get('source_volume') and not self.check_if_remote_volume_exists():
936 self.module.fail_json(msg='Source volume does not exist. Please specify a volume that exists')
937 if self.use_rest:
938 return self.snapmirror_rest_create()
939
940 options = {'source-location': self.parameters['source_path'],
941 'destination-location': self.parameters['destination_path']}
942 snapmirror_create = netapp_utils.zapi.NaElement.create_node_with_children('snapmirror-create', **options)
943 if self.parameters.get('relationship_type'):
944 snapmirror_create.add_new_child('relationship-type', self.parameters['relationship_type'])
945 if self.parameters.get('schedule'):
946 snapmirror_create.add_new_child('schedule', self.parameters['schedule'])
947 if self.parameters.get('policy'):
948 snapmirror_create.add_new_child('policy', self.parameters['policy'])
949 if self.parameters.get('max_transfer_rate'):
950 snapmirror_create.add_new_child('max-transfer-rate', str(self.parameters['max_transfer_rate']))
951 if self.parameters.get('identity_preserve'):
952 snapmirror_create.add_new_child('identity-preserve', self.na_helper.get_value_for_bool(False, self.parameters['identity_preserve']))
953 try:
954 self.server.invoke_successfully(snapmirror_create, enable_tunneling=True)
955 except netapp_utils.zapi.NaApiError as error:
956 self.module.fail_json(msg='Error creating SnapMirror %s' % to_native(error),
957 exception=traceback.format_exc())
958 if self.parameters['initialize']:
959 self.snapmirror_initialize()
960
961 def set_source_cluster_connection(self):
962 """
963 Setup ontap ZAPI or REST server connection for source hostname
964 :return: None
965 """
966 self.src_rest_api = netapp_utils.OntapRestAPI(self.module, host_options=self.parameters['peer_options'])
967 unsupported_rest_properties = ['identity_preserve', 'max_transfer_rate', 'schedule']
968 rtype = self.parameters.get('relationship_type')
969 if rtype not in (None, 'extended_data_protection', 'restore'):
970 unsupported_rest_properties.append('relationship_type')
971 used_unsupported_rest_properties = [x for x in unsupported_rest_properties if x in self.parameters]
972 self.src_use_rest, error = self.src_rest_api.is_rest(used_unsupported_rest_properties)
973 if error is not None:
974 if 'relationship_type' in error:
975 error = error.replace('relationship_type', 'relationship_type: %s' % rtype)
976 self.module.fail_json(msg=error)
977 if not self.src_use_rest:
978 if not netapp_utils.has_netapp_lib():
979 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
980 self.source_server = netapp_utils.setup_na_ontap_zapi(module=self.module, host_options=self.parameters['peer_options'])
981
982 def delete_snapmirror(self, relationship_type, mirror_state):
983 """
984 Delete a SnapMirror relationship
985 #1. Quiesce the SnapMirror relationship at destination
986 #2. Break the SnapMirror relationship at the destination
987 #3. Release the SnapMirror at source
988 #4. Delete SnapMirror at destination
989 """
990 # Quiesce and Break at destination
991 if relationship_type not in ['load_sharing', 'vault'] and mirror_state not in ['uninitialized', 'broken-off', 'broken_off']:
992 self.snapmirror_break(before_delete=True)
993 # if source is ONTAP, release the destination at source cluster
994 # if the source_hostname is unknown, do not run snapmirror_release
995 if self.parameters.get('peer_options') is not None and self.parameters.get('connection_type') != 'elementsw_ontap' and not self.use_rest:
996 self.set_source_cluster_connection()
997 if self.get_destination():
998 # Release at source
999 # Note: REST remove the source from destination, so not required to release from source for REST
1000 self.snapmirror_release()
1001 # Delete at destination
1002 self.snapmirror_delete()
1003
1004 def snapmirror_quiesce(self):
1005 """
1006 Quiesce SnapMirror relationship - disable all future transfers to this destination
1007 """
1008 if self.use_rest:
1009 return self.snapmirror_quiesce_rest()
1010
1011 options = {'destination-location': self.parameters['destination_path']}
1012
1013 snapmirror_quiesce = netapp_utils.zapi.NaElement.create_node_with_children(
1014 'snapmirror-quiesce', **options)
1015 try:
1016 self.server.invoke_successfully(snapmirror_quiesce, enable_tunneling=True)
1017 except netapp_utils.zapi.NaApiError as error:
1018 self.module.fail_json(msg='Error quiescing SnapMirror: %s'
1019 % (to_native(error)), exception=traceback.format_exc())
1020 # checking if quiesce was passed successfully
1021 self.wait_for_quiesced_status()
1022
1023 def snapmirror_delete(self):
1024 """
1025 Delete SnapMirror relationship at destination cluster
1026 """
1027 if self.use_rest:
1028 return self.snapmirror_delete_rest()
1029 options = {'destination-location': self.parameters['destination_path']}
1030
1031 snapmirror_delete = netapp_utils.zapi.NaElement.create_node_with_children(
1032 'snapmirror-destroy', **options)
1033 try:
1034 self.server.invoke_successfully(snapmirror_delete,
1035 enable_tunneling=True)
1036 except netapp_utils.zapi.NaApiError as error:
1037 msg = 'Error deleting SnapMirror: %s' % to_native(error)
1038 if self.previous_errors:
1039 msg += '. Previous error(s): %s' % ' -- '.join(self.previous_errors)
1040 self.module.fail_json(msg=msg, exception=traceback.format_exc())
1041
1042 def snapmirror_break(self, destination=None, before_delete=False):
1043 """
1044 Break SnapMirror relationship at destination cluster
1045 #1. Quiesce the SnapMirror relationship at destination
1046 #2. Break the SnapMirror relationship at the destination
1047 """
1048 self.snapmirror_quiesce()
1049
1050 if self.use_rest:
1051 if self.parameters['current_mirror_state'] == 'broken_off' or self.parameters['current_transfer_status'] == 'transferring':
1052 self.na_helper.changed = False
1053 self.module.fail_json(msg="snapmirror data are transferring")
1054 return self.snapmirror_mod_init_resync_break_quiesce_resume_rest(state="broken_off", before_delete=before_delete)
1055 if destination is None:
1056 destination = self.parameters['destination_path']
1057 options = {'destination-location': destination}
1058 snapmirror_break = netapp_utils.zapi.NaElement.create_node_with_children(
1059 'snapmirror-break', **options)
1060 try:
1061 self.server.invoke_successfully(snapmirror_break,
1062 enable_tunneling=True)
1063 except netapp_utils.zapi.NaApiError as error:
1064 msg = 'Error breaking SnapMirror relationship: %s' % to_native(error)
1065 if before_delete:
1066 # record error but proceed with deletion
1067 self.previous_errors.append(msg)
1068 else:
1069 self.module.fail_json(msg=msg, exception=traceback.format_exc())
1070
1071 def snapmirror_release(self):
1072 """
1073 Release SnapMirror relationship from source cluster
1074 """
1075 # if it's REST call, then not required to run release
1076 if self.use_rest:
1077 return
1078 options = {'destination-location': self.parameters['destination_path'],
1079 'relationship-info-only': self.na_helper.get_value_for_bool(False, self.parameters['relationship_info_only'])}
1080 snapmirror_release = netapp_utils.zapi.NaElement.create_node_with_children(
1081 'snapmirror-release', **options)
1082 try:
1083 self.source_server.invoke_successfully(snapmirror_release,
1084 enable_tunneling=True)
1085 except netapp_utils.zapi.NaApiError as error:
1086 self.module.fail_json(msg='Error releasing SnapMirror relationship: %s'
1087 % (to_native(error)),
1088 exception=traceback.format_exc())
1089
1090 def snapmirror_abort(self):
1091 """
1092 Abort a SnapMirror relationship in progress
1093 """
1094 if self.use_rest:
1095 return self.snapmirror_abort_rest()
1096
1097 options = {'destination-location': self.parameters['destination_path']}
1098 snapmirror_abort = netapp_utils.zapi.NaElement.create_node_with_children(
1099 'snapmirror-abort', **options)
1100 try:
1101 self.server.invoke_successfully(snapmirror_abort,
1102 enable_tunneling=True)
1103 except netapp_utils.zapi.NaApiError as error:
1104 self.module.fail_json(msg='Error aborting SnapMirror relationship: %s'
1105 % (to_native(error)),
1106 exception=traceback.format_exc())
1107
1108 def snapmirror_initialize(self, current=None):
1109 """
1110 Initialize SnapMirror based on relationship state
1111 """
1112 if current and current['status'] == 'transferring' or self.parameters.get('current_transfer_status') == 'transferring':
1113 # Operation already in progress, let's wait for it to end
1114 current = self.wait_for_idle_status()
1115 if not current:
1116 current = self.snapmirror_get()
1117 if self.use_rest:
1118 if current['mirror_state'] == 'uninitialized' and current['status'] != 'transferring':
1119 state = 'in_sync' if self.policy_type == 'sync' else 'snapmirrored'
1120 self.snapmirror_mod_init_resync_break_quiesce_resume_rest(state=state)
1121 self.wait_for_idle_status()
1122 return
1123 if current['mirror_state'] != 'snapmirrored':
1124 initialize_zapi = 'snapmirror-initialize'
1125 if self.parameters.get('relationship_type') == 'load_sharing':
1126 initialize_zapi = 'snapmirror-initialize-ls-set'
1127 options = {'source-location': self.parameters['source_path']}
1128 else:
1129 options = {'destination-location': self.parameters['destination_path']}
1130 snapmirror_init = netapp_utils.zapi.NaElement.create_node_with_children(
1131 initialize_zapi, **options)
1132 try:
1133 self.server.invoke_successfully(snapmirror_init,
1134 enable_tunneling=True)
1135 except netapp_utils.zapi.NaApiError as error:
1136 self.module.fail_json(msg='Error initializing SnapMirror: %s'
1137 % (to_native(error)),
1138 exception=traceback.format_exc())
1139 self.wait_for_idle_status()
1140
1141 def snapmirror_resync(self, current=None):
1142 """
1143 resync SnapMirror based on relationship state
1144 """
1145 if self.use_rest:
1146 state = 'in_sync' if self.policy_type == 'sync' else 'snapmirrored'
1147 quick_resync = False
1148 if 'quick_resync' in self.parameters:
1149 quick_resync = self.parameters.get('quick_resync')
1150 self.snapmirror_mod_init_resync_break_quiesce_resume_rest(state=state, quick_resync=quick_resync)
1151 else:
1152 options = {'destination-location': self.parameters['destination_path']}
1153 snapmirror_resync = netapp_utils.zapi.NaElement.create_node_with_children('snapmirror-resync', **options)
1154 try:
1155 self.server.invoke_successfully(snapmirror_resync, enable_tunneling=True)
1156 except netapp_utils.zapi.NaApiError as error:
1157 self.module.fail_json(msg='Error resyncing SnapMirror relationship: %s' % (to_native(error)),
1158 exception=traceback.format_exc())
1159 self.wait_for_idle_status()
1160
1161 def snapmirror_resume(self):
1162 """
1163 resume SnapMirror based on relationship state
1164 """
1165 if self.use_rest:
1166 state = 'in_sync' if self.policy_type == 'sync' else 'snapmirrored'
1167 return self.snapmirror_mod_init_resync_break_quiesce_resume_rest(state=state)
1168
1169 options = {'destination-location': self.parameters['destination_path']}
1170 snapmirror_resume = netapp_utils.zapi.NaElement.create_node_with_children('snapmirror-resume', **options)
1171 try:
1172 self.server.invoke_successfully(snapmirror_resume, enable_tunneling=True)
1173 except netapp_utils.zapi.NaApiError as error:
1174 self.module.fail_json(msg='Error resuming SnapMirror relationship: %s' % (to_native(error)), exception=traceback.format_exc())
1175
1176 def snapmirror_restore(self):
1177 """
1178 restore SnapMirror based on relationship state
1179 """
1180 if self.use_rest:
1181 return self.snapmirror_restore_rest()
1182
1183 options = {'destination-location': self.parameters['destination_path'],
1184 'source-location': self.parameters['source_path']}
1185 if self.parameters.get('source_snapshot'):
1186 options['source-snapshot'] = self.parameters['source_snapshot']
1187 if self.parameters.get('clean_up_failure'):
1188 # only send it when True
1189 options['clean-up-failure'] = self.na_helper.get_value_for_bool(False, self.parameters['clean_up_failure'])
1190 snapmirror_restore = netapp_utils.zapi.NaElement.create_node_with_children('snapmirror-restore', **options)
1191 try:
1192 self.server.invoke_successfully(snapmirror_restore, enable_tunneling=True)
1193 except netapp_utils.zapi.NaApiError as error:
1194 self.module.fail_json(msg='Error restoring SnapMirror relationship: %s' % (to_native(error)), exception=traceback.format_exc())
1195
1196 def snapmirror_modify(self, modify):
1197 """
1198 Modify SnapMirror schedule or policy
1199 """
1200 if self.use_rest:
1201 return self.snapmirror_mod_init_resync_break_quiesce_resume_rest(modify=modify)
1202
1203 options = {'destination-location': self.parameters['destination_path']}
1204 snapmirror_modify = netapp_utils.zapi.NaElement.create_node_with_children(
1205 'snapmirror-modify', **options)
1206 param_to_zapi = {
1207 'schedule': 'schedule',
1208 'policy': 'policy',
1209 'max_transfer_rate': 'max-transfer-rate'
1210 }
1211 for param_key, value in modify.items():
1212 snapmirror_modify.add_new_child(param_to_zapi[param_key], str(value))
1213 try:
1214 self.server.invoke_successfully(snapmirror_modify,
1215 enable_tunneling=True)
1216 except netapp_utils.zapi.NaApiError as error:
1217 self.module.fail_json(msg='Error modifying SnapMirror schedule or policy: %s'
1218 % (to_native(error)),
1219 exception=traceback.format_exc())
1220
1221 def snapmirror_update(self, relationship_type):
1222 """
1223 Update data in destination endpoint
1224 """
1225 if self.use_rest:
1226 return self.snapmirror_update_rest()
1227
1228 zapi = 'snapmirror-update'
1229 options = {'destination-location': self.parameters['destination_path']}
1230 if relationship_type == 'load_sharing':
1231 zapi = 'snapmirror-update-ls-set'
1232 options = {'source-location': self.parameters['source_path']}
1233
1234 snapmirror_update = netapp_utils.zapi.NaElement.create_node_with_children(
1235 zapi, **options)
1236 try:
1237 self.server.invoke_successfully(snapmirror_update, enable_tunneling=True)
1238 except netapp_utils.zapi.NaApiError as error:
1239 self.module.fail_json(msg='Error updating SnapMirror: %s'
1240 % (to_native(error)),
1241 exception=traceback.format_exc())
1242
1243 @staticmethod
1244 def new_option(option, prefix):
1245 new_option_name = option[len(prefix):]
1246 if new_option_name == 'vserver':
1247 new_option_name = 'path (or svm)'
1248 elif new_option_name == 'volume':
1249 new_option_name = 'path'
1250 return '%sendpoint:%s' % (prefix, new_option_name)
1251
1252 def too_old(self, minimum_generation, minimum_major):
1253 return not self.rest_api.meets_rest_minimum_version(self.use_rest, minimum_generation, minimum_major, 0)
1254
1255 def set_new_style(self):
1256 # if source_endpoint or destination_endpoint if present, both are required
1257 # then sanitize inputs to support new style
1258 if not self.parameters.get('destination_endpoint') or not self.parameters.get('source_endpoint'):
1259 self.module.fail_json(msg='Missing parameters: Source endpoint or Destination endpoint')
1260 # sanitize inputs
1261 self.parameters['source_endpoint'] = self.na_helper.filter_out_none_entries(self.parameters['source_endpoint'])
1262 self.parameters['destination_endpoint'] = self.na_helper.filter_out_none_entries(self.parameters['destination_endpoint'])
1263 # options requiring 9.7 or better, and REST
1264 ontap_97_options = ['cluster', 'ipspace']
1265 if self.too_old(9, 7) and any(x in self.parameters['source_endpoint'] for x in ontap_97_options):
1266 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version(ontap_97_options, version='9.7', use_rest=self.use_rest))
1267 if self.too_old(9, 7) and any(x in self.parameters['destination_endpoint'] for x in ontap_97_options):
1268 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version(ontap_97_options, version='9.7', use_rest=self.use_rest))
1269 # options requiring 9.8 or better, and REST
1270 ontap_98_options = ['consistency_group_volumes']
1271 if self.too_old(9, 8) and any(x in self.parameters['source_endpoint'] for x in ontap_98_options):
1272 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version(ontap_98_options, version='9.8', use_rest=self.use_rest))
1273 if self.too_old(9, 8) and any(x in self.parameters['destination_endpoint'] for x in ontap_98_options):
1274 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version(ontap_98_options, version='9.8', use_rest=self.use_rest))
1275 # fill in old style parameters
1276 self.parameters['source_cluster'] = self.na_helper.safe_get(self.parameters, ['source_endpoint', 'cluster'])
1277 self.parameters['source_path'] = self.na_helper.safe_get(self.parameters, ['source_endpoint', 'path'])
1278 self.parameters['source_vserver'] = self.na_helper.safe_get(self.parameters, ['source_endpoint', 'svm'])
1279 self.parameters['destination_cluster'] = self.na_helper.safe_get(self.parameters, ['destination_endpoint', 'cluster'])
1280 self.parameters['destination_path'] = self.na_helper.safe_get(self.parameters, ['destination_endpoint', 'path'])
1281 self.parameters['destination_vserver'] = self.na_helper.safe_get(self.parameters, ['destination_endpoint', 'svm'])
1282 self.new_style = True
1283
1284 def set_endpoints(self):
1285 # use new structures for source and destination endpoints
1286 for location in ('source', 'destination'):
1287 endpoint = '%s_endpoint' % location
1288 self.parameters[endpoint] = {}
1289 # skipping svm for now, as it is not accepted and not needed with path
1290 # for old, new in (('path', 'path'), ('vserver', 'svm'), ('cluster', 'cluster')):
1291 for old, new in (('path', 'path'), ('cluster', 'cluster')):
1292 value = self.parameters.get('%s_%s' % (location, old))
1293 if value is not None:
1294 self.parameters[endpoint][new] = value
1295
1296 def check_parameters(self):
1297 """
1298 Validate parameters and fail if one or more required params are missing
1299 Update source and destination path from vserver and volume parameters
1300 """
1301 for option in ['source_cluster', 'source_path', 'source_volume', 'source_vserver']:
1302 if option in self.parameters:
1303 self.module.warn('option: %s is deprecated, please use %s' % (option, self.new_option(option, 'source_')))
1304 for option in ['destination_cluster', 'destination_path', 'destination_volume', 'destination_vserver']:
1305 if option in self.parameters:
1306 self.module.warn('option: %s is deprecated, please use %s' % (option, self.new_option(option, 'destination_')))
1307
1308 if self.parameters.get('source_endpoint') or self.parameters.get('destination_endpoint'):
1309 self.set_new_style()
1310 if self.parameters.get('source_path') or self.parameters.get('destination_path'):
1311 if (not self.parameters.get('destination_path') or not self.parameters.get('source_path'))\
1312 and (self.parameters['state'] == 'present' or (self.parameters['state'] == 'absent' and not self.parameters.get('destination_path'))):
1313 self.module.fail_json(msg='Missing parameters: Source path or Destination path')
1314 elif self.parameters.get('source_volume'):
1315 if not self.parameters.get('source_vserver') or not self.parameters.get('destination_vserver'):
1316 self.module.fail_json(msg='Missing parameters: source vserver or destination vserver or both')
1317 self.parameters['source_path'] = self.parameters['source_vserver'] + ":" + self.parameters['source_volume']
1318 self.parameters['destination_path'] = self.parameters['destination_vserver'] + ":" +\
1319 self.parameters['destination_volume']
1320 elif self.parameters.get('source_vserver') and self.parameters.get('source_endpoint') is None:
1321 self.parameters['source_path'] = self.parameters['source_vserver'] + ":"
1322 self.parameters['destination_path'] = self.parameters['destination_vserver'] + ":"
1323
1324 if self.use_rest and not self.new_style:
1325 self.set_endpoints()
1326
1327 def get_destination(self):
1328 """
1329 get the destination info
1330 # Note: REST module to get_destination is not required as it's used in only ZAPI.
1331 """
1332 result = None
1333 get_dest_iter = netapp_utils.zapi.NaElement('snapmirror-get-destination-iter')
1334 query = netapp_utils.zapi.NaElement('query')
1335 snapmirror_dest_info = netapp_utils.zapi.NaElement('snapmirror-destination-info')
1336 snapmirror_dest_info.add_new_child('destination-location', self.parameters['destination_path'])
1337 query.add_child_elem(snapmirror_dest_info)
1338 get_dest_iter.add_child_elem(query)
1339 try:
1340 result = self.source_server.invoke_successfully(get_dest_iter, enable_tunneling=True)
1341 except netapp_utils.zapi.NaApiError as error:
1342 self.module.fail_json(msg='Error fetching snapmirror destinations info: %s' % to_native(error),
1343 exception=traceback.format_exc())
1344 if result.get_child_by_name('num-records') and \
1345 int(result.get_child_content('num-records')) > 0:
1346 return True
1347 return None
1348
1349 @staticmethod
1350 def element_source_path_format_matches(value):
1351 return re.match(pattern=r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\/lun\/[0-9]+",
1352 string=value)
1353
1354 def check_elementsw_parameters(self, kind='source'):
1355 """
1356 Validate all ElementSW cluster parameters required for managing the SnapMirror relationship
1357 Validate if both source and destination paths are present
1358 Validate if source_path follows the required format
1359 Validate SVIP
1360 Validate if ElementSW volume exists
1361 :return: None
1362 """
1363 path = None
1364 if kind == 'destination':
1365 path = self.parameters.get('destination_path')
1366 elif kind == 'source':
1367 path = self.parameters.get('source_path')
1368 if path is None:
1369 self.module.fail_json(msg="Error: Missing required parameter %s_path for "
1370 "connection_type %s" % (kind, self.parameters['connection_type']))
1371 if NetAppONTAPSnapmirror.element_source_path_format_matches(path) is None:
1372 self.module.fail_json(msg="Error: invalid %s_path %s. "
1373 "If the path is a ElementSW cluster, the value should be of the format"
1374 " <Element_SVIP>:/lun/<Element_VOLUME_ID>" % (kind, path))
1375 # validate source_path
1376 elementsw_helper, elem = self.set_element_connection(kind)
1377 self.validate_elementsw_svip(path, elem)
1378 self.check_if_elementsw_volume_exists(path, elementsw_helper)
1379
1380 def validate_elementsw_svip(self, path, elem):
1381 """
1382 Validate ElementSW cluster SVIP
1383 :return: None
1384 """
1385 result = None
1386 try:
1387 result = elem.get_cluster_info()
1388 except solidfire.common.ApiServerError as err:
1389 self.module.fail_json(msg="Error fetching SVIP", exception=to_native(err))
1390 if result and result.cluster_info.svip:
1391 cluster_svip = result.cluster_info.svip
1392 svip = path.split(':')[0] # split IP address from source_path
1393 if svip != cluster_svip:
1394 self.module.fail_json(msg="Error: Invalid SVIP")
1395
1396 def check_if_elementsw_volume_exists(self, path, elementsw_helper):
1397 """
1398 Check if remote ElementSW volume exists
1399 :return: None
1400 """
1401 volume_id, vol_id = None, path.split('/')[-1]
1402 try:
1403 volume_id = elementsw_helper.volume_id_exists(int(vol_id))
1404 except solidfire.common.ApiServerError as err:
1405 self.module.fail_json(msg="Error fetching Volume details", exception=to_native(err))
1406
1407 if volume_id is None:
1408 self.module.fail_json(msg="Error: Source volume does not exist in the ElementSW cluster")
1409
1410 def check_health(self):
1411 """
1412 Checking the health of the snapmirror
1413 """
1414 if self.parameters.get('connection_type') == 'ontap_elementsw':
1415 return
1416 current = self.snapmirror_get()
1417 if current is not None and not current.get('is_healthy', True):
1418 msg = ['SnapMirror relationship exists but is not healthy.']
1419 if 'unhealthy_reason' in current:
1420 msg.append('Unhealthy reason: %s' % current['unhealthy_reason'])
1421 if 'last_transfer_error' in current:
1422 msg.append('Last transfer error: %s' % current['last_transfer_error'])
1423 self.module.warn(' '.join(msg))
1424
1425 def check_if_remote_volume_exists_rest(self):
1426 """
1427 Check the remote volume exists using REST
1428 """
1429 if self.src_use_rest:
1430 if self.parameters.get('source_volume') is not None and self.parameters.get('source_vserver') is not None:
1431 volume_name = self.parameters['source_volume']
1432 svm_name = self.parameters['source_vserver']
1433 options = {'name': volume_name, 'svm.name': svm_name, 'fields': 'name,svm.name'}
1434 api = 'storage/volumes'
1435 record, error = rest_generic.get_one_record(self.src_rest_api, api, options)
1436 if error:
1437 self.module.fail_json(msg='Error fetching source volume: %s' % error)
1438 return record is not None
1439 return False
1440 self.module.fail_json(msg='REST is not supported on Source')
1441
1442 def snapmirror_restore_rest(self):
1443 ''' snapmirror restore using rest '''
1444 # Use the POST /api/snapmirror/relationships REST API call with the property "restore=true" to create the SnapMirror restore relationship
1445 # Use the POST /api/snapmirror/relationships/{relationship.uuid}/transfers REST API call to start the restore transfer on the SnapMirror relationship
1446 # run this API calls on Source cluster
1447 # if the source_hostname is unknown, do not run snapmirror_restore
1448 body = {'destination.path': self.parameters['destination_path'], 'source.path': self.parameters['source_path'], 'restore': 'true'}
1449 api = 'snapmirror/relationships'
1450 timeout = 30 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
1451 dummy, error = rest_generic.post_async(self.rest_api, api, body, timeout=timeout, job_timeout=timeout)
1452 if error:
1453 self.module.fail_json(msg='Error restoring SnapMirror: %s' % to_native(error), exception=traceback.format_exc())
1454 relationship_uuid = self.get_relationship_uuid()
1455 # REST API call to start the restore transfer on the SnapMirror relationship
1456 if relationship_uuid is None:
1457 self.module.fail_json(msg="Error restoring SnapMirror: unable to get UUID for the SnapMirror relationship.")
1458
1459 body = {'source_snapshot': self.parameters['source_snapshot']} if self.parameters.get('source_snapshot') else {}
1460 api = 'snapmirror/relationships/%s/transfers' % relationship_uuid
1461 timeout = 30 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
1462 dummy, error = rest_generic.post_async(self.rest_api, api, body, timeout=timeout, job_timeout=timeout)
1463 if error:
1464 self.module.fail_json(msg='Error restoring SnapMirror Transfer: %s' % to_native(error), exception=traceback.format_exc())
1465
1466 def get_relationship_uuid(self, after_create=True):
1467 # this may be called after a create including restore, so we may need to fetch the data
1468 if after_create and self.parameters.get('uuid') is None:
1469 self.snapmirror_get()
1470 return self.parameters.get('uuid')
1471
1472 def snapmirror_mod_init_resync_break_quiesce_resume_rest(self, state=None, modify=None, before_delete=False, quick_resync=False):
1473 """
1474 To perform SnapMirror modify, init, resume, resync and break.
1475 1. Modify only update SnapMirror policy which passes the policy in body.
1476 2. To perform SnapMirror init - state=in_sync when type=sync otherwise state=snapmirrored and mirror_state=uninitialized.
1477 3. To perform SnapMirror resync - state=snapmirrored and mirror_state=broken_off.
1478 4. To perform SnapMirror break - state=broken_off and transfer_state not transferring.
1479 5. To perform SnapMirror quiesce - state=pause and mirror_state not broken_off.
1480 6. To perform SnapMirror resume - state=snapmirrored.
1481 """
1482 uuid = self.get_relationship_uuid()
1483 if uuid is None:
1484 self.module.fail_json(msg="Error in updating SnapMirror relationship: unable to get UUID for the SnapMirror relationship.")
1485
1486 body = {}
1487 if quick_resync:
1488 body['quick_resync'] = self.parameters.get('quick_resync')
1489 if state is not None:
1490 body["state"] = state
1491 elif modify:
1492 for key in modify:
1493 if key == 'policy':
1494 body[key] = {"name": modify[key]}
1495 elif key == 'schedule':
1496 body['transfer_schedule'] = {"name": self.string_or_none(modify[key])}
1497 else:
1498 self.module.warn(msg="Unexpected key in modify: %s, value: %s" % (key, modify[key]))
1499 else:
1500 self.na_helper.changed = False
1501 return
1502 api = 'snapmirror/relationships'
1503 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else None
1504 timeout = 30 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
1505 dummy, error = rest_generic.patch_async(self.rest_api, api, uuid, body, query, job_timeout=timeout)
1506 if error:
1507 msg = 'Error patching SnapMirror: %s: %s' % (body, to_native(error))
1508 if before_delete:
1509 self.previous_errors.append(msg)
1510 else:
1511 self.module.fail_json(msg=msg, exception=traceback.format_exc())
1512
1513 def snapmirror_update_rest(self):
1514 """
1515 Perform an update on the relationship using POST on /snapmirror/relationships/{relationship.uuid}/transfers
1516 """
1517 uuid = self.get_relationship_uuid()
1518 if uuid is None:
1519 self.module.fail_json(msg="Error in updating SnapMirror relationship: unable to get UUID for the SnapMirror relationship.")
1520 api = 'snapmirror/relationships/%s/transfers' % uuid
1521 body = {}
1522 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else None
1523 timeout = 30 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
1524 dummy, error = rest_generic.post_async(self.rest_api, api, body, query, job_timeout=timeout)
1525 if error:
1526 self.module.fail_json(msg='Error updating SnapMirror relationship: %s:' % to_native(error), exception=traceback.format_exc())
1527
1528 def snapmirror_abort_rest(self):
1529 """
1530 Abort a SnapMirror relationship in progress using REST
1531 """
1532 uuid = self.get_relationship_uuid(after_create=False)
1533 transfer_uuid = self.parameters.get('transfer_uuid')
1534 if uuid is None or transfer_uuid is None:
1535 self.module.fail_json(msg="Error in aborting SnapMirror: unable to get either uuid: %s or transfer_uuid: %s." % (uuid, transfer_uuid))
1536 api = 'snapmirror/relationships/%s/transfers' % uuid
1537 body = {"state": "aborted"}
1538 dummy, error = rest_generic.patch_async(self.rest_api, api, transfer_uuid, body)
1539 if error:
1540 self.module.fail_json(msg='Error aborting SnapMirror: %s' % to_native(error), exception=traceback.format_exc())
1541
1542 def snapmirror_quiesce_rest(self):
1543 """
1544 SnapMirror quiesce using REST
1545 """
1546 if (self.parameters['current_mirror_state'] == 'paused'
1547 or self.parameters['current_mirror_state'] == 'broken_off'
1548 or self.parameters['current_transfer_status'] == 'transferring'):
1549 return
1550 self.snapmirror_mod_init_resync_break_quiesce_resume_rest(state="paused")
1551 self.wait_for_quiesced_status()
1552
1553 def snapmirror_delete_rest(self):
1554 """
1555 Delete SnapMirror relationship at destination cluster using REST
1556 """
1557 uuid = self.get_relationship_uuid(after_create=False)
1558 if uuid is None:
1559 self.module.fail_json(msg='Error in deleting SnapMirror: %s, unable to get UUID for the SnapMirror relationship.' % uuid)
1560 api = 'snapmirror/relationships'
1561 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else None
1562 timeout = 30 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
1563 retry = 3
1564 while retry > 0:
1565 dummy, error = rest_generic.delete_async(self.rest_api, api, uuid, query, job_timeout=timeout)
1566 if error and 'Timeout error: Process still running' in error:
1567 time.sleep(120)
1568 retry -= 1
1569 elif error:
1570 msg = 'Error deleting SnapMirror: %s' % to_native(error)
1571 if self.previous_errors:
1572 msg += '. Previous error(s): %s' % ' -- '.join(self.previous_errors)
1573 self.module.fail_json(msg=msg, exception=traceback.format_exc())
1574 else:
1575 return
1576
1577 def snapmirror_rest_create(self):
1578 """
1579 Create a SnapMirror relationship using REST
1580 """
1581 body, initialized = self.get_create_body()
1582 api = 'snapmirror/relationships'
1583 query = {'return_timeout': 0} if not self.parameters['wait_for_completion'] else None
1584 timeout = 30 if not self.parameters['wait_for_completion'] else self.parameters['time_out']
1585 dummy, error = rest_generic.post_async(self.rest_api, api, body, query, timeout=timeout, job_timeout=timeout)
1586 if error:
1587 self.module.fail_json(msg='Error creating SnapMirror: %s' % to_native(error), exception=traceback.format_exc())
1588 if self.parameters['initialize']:
1589 if initialized:
1590 self.wait_for_idle_status()
1591 else:
1592 self.snapmirror_initialize()
1593
1594 def snapmirror_get_rest(self, destination=None):
1595 """ Get the current snapmirror info """
1596 if destination is None and "destination_path" in self.parameters:
1597 # check_param get the value if it's given in other format like destination_endpoint etc..
1598 destination = self.parameters['destination_path']
1599
1600 api = 'snapmirror/relationships'
1601 fields = 'uuid,state,transfer.state,transfer.uuid,policy.name,policy.type,unhealthy_reason.message,healthy,source'
1602 if 'schedule' in self.parameters:
1603 fields += ',transfer_schedule'
1604 options = {'destination.path': destination, 'fields': fields}
1605 record, error = rest_generic.get_one_record(self.rest_api, api, options)
1606 if error:
1607 self.module.fail_json(msg="Error getting SnapMirror %s: %s" % (destination, to_native(error)),
1608 exception=traceback.format_exc())
1609 if record is not None:
1610 snap_info = {}
1611 self.parameters['uuid'] = self.na_helper.safe_get(record, ['uuid'])
1612 self.parameters['transfer_uuid'] = self.na_helper.safe_get(record, ['transfer', 'uuid'])
1613 self.parameters['current_mirror_state'] = self.na_helper.safe_get(record, ['state'])
1614 snap_info['mirror_state'] = self.na_helper.safe_get(record, ['state'])
1615 snap_info['status'] = self.na_helper.safe_get(record, ['transfer', 'state'])
1616 self.parameters['current_transfer_status'] = self.na_helper.safe_get(record, ['transfer', 'state'])
1617 snap_info['policy'] = self.na_helper.safe_get(record, ['policy', 'name'])
1618 self.policy_type = self.na_helper.safe_get(record, ['policy', 'type'])
1619 # REST API supports only Extended Data Protection (XDP) SnapMirror relationship
1620 snap_info['relationship_type'] = 'extended_data_protection'
1621 # initialized to avoid name keyerror
1622 snap_info['current_transfer_type'] = ""
1623 snap_info['max_transfer_rate'] = ""
1624 if 'unhealthy_reason' in record:
1625 snap_info['last_transfer_error'] = self.na_helper.safe_get(record, ['unhealthy_reason'])
1626 snap_info['unhealthy_reason'] = self.na_helper.safe_get(record, ['unhealthy_reason'])
1627 snap_info['is_healthy'] = self.na_helper.safe_get(record, ['healthy'])
1628 snap_info['source_path'] = self.na_helper.safe_get(record, ['source', 'path'])
1629 # if the field is absent, assume ""
1630 snap_info['schedule'] = self.na_helper.safe_get(record, ['transfer_schedule', 'name']) or ""
1631 return snap_info
1632 return None
1633
1634 def snapmirror_policy_rest_get(self, policy_name, svm_name):
1635 """
1636 get policy type
1637 There is a set of system level policies, and users can create their own for a SVM
1638 REST does not return a svm entry for system policies
1639 svm_name may not exist yet as it can be created when creating the snapmirror relationship
1640 """
1641 policy_type = None
1642 system_policy_type = None # policies not associated to a SVM
1643 api = 'snapmirror/policies'
1644 query = {
1645 "name": policy_name,
1646 "fields": "svm.name,type"
1647 }
1648 records, error = rest_generic.get_0_or_more_records(self.rest_api, api, query)
1649 if error is None and records is not None:
1650 for record in records:
1651 if 'svm' in record:
1652 if record['svm']['name'] == svm_name:
1653 policy_type = record['type']
1654 break
1655 else:
1656 system_policy_type = record['type']
1657 if policy_type is None:
1658 policy_type = system_policy_type
1659 return policy_type, error
1660
1661 def add_break_action(self, actions, current):
1662 # If current is not None, it means the state is present otherwise we would take a delete action
1663 if current and self.parameters['relationship_state'] == 'broken':
1664 if current['mirror_state'] == 'uninitialized':
1665 self.module.fail_json(msg='SnapMirror relationship cannot be broken if mirror state is uninitialized')
1666 elif current['relationship_type'] in ['load_sharing', 'vault']:
1667 self.module.fail_json(msg='SnapMirror break is not allowed in a load_sharing or vault relationship')
1668 elif current['mirror_state'] not in ['broken-off', 'broken_off']:
1669 actions.append('break')
1670 self.na_helper.changed = True
1671
1672 def add_active_actions(self, actions, current):
1673 # add initialize or resume action as needed
1674 # add resync or check_for_update action as needed
1675 # If current is not None, it means the state is present otherwise we would take a delete action
1676 if current and self.parameters['relationship_state'] == 'active':
1677 # check for initialize
1678 if self.parameters['initialize'] and current['mirror_state'] == 'uninitialized' and current['current_transfer_type'] != 'initialize':
1679 actions.append('initialize')
1680 # set changed explicitly for initialize
1681 self.na_helper.changed = True
1682 # resume when state is quiesced
1683 if current['status'] == 'quiesced' or current['mirror_state'] == 'paused':
1684 actions.append('resume')
1685 # set changed explicitly for resume
1686 self.na_helper.changed = True
1687 # resync when state is broken-off
1688 if current['mirror_state'] in ['broken-off', 'broken_off']:
1689 actions.append('resync')
1690 # set changed explicitly for resync
1691 self.na_helper.changed = True
1692 # Update when create is called again, or modify is being called
1693 elif self.parameters['update']:
1694 actions.append('check_for_update')
1695
1696 def get_svm_peer(self, source_svm, destination_svm):
1697 if self.use_rest:
1698 api = 'svm/peers'
1699 query = {'name': source_svm, 'svm.name': destination_svm}
1700 record, error = rest_generic.get_one_record(self.rest_api, api, query, fields='peer')
1701 if error:
1702 self.module.fail_json(msg='Error retrieving SVM peer: %s' % error)
1703 if record:
1704 return self.na_helper.safe_get(record, ['peer', 'svm', 'name']), self.na_helper.safe_get(record, ['peer', 'cluster', 'name'])
1705 else:
1706 query = {
1707 'query': {
1708 'vserver-peer-info': {
1709 'peer-vserver': source_svm,
1710 'vserver': destination_svm
1711 }
1712 }
1713 }
1714 get_request = netapp_utils.zapi.NaElement('vserver-peer-get-iter')
1715 get_request.translate_struct(query)
1716 try:
1717 result = self.server.invoke_successfully(get_request, enable_tunneling=True)
1718 except netapp_utils.zapi.NaApiError as error:
1719 self.module.fail_json(msg='Error fetching vserver peer info: %s' % to_native(error),
1720 exception=traceback.format_exc())
1721 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) > 0:
1722 info = result.get_child_by_name('attributes-list').get_child_by_name('vserver-peer-info')
1723 return info['remote-vserver-name'], info['peer-cluster']
1724
1725 return None, None
1726
1727 def validate_source_path(self, current):
1728 """ There can only be one destination, so we use it as the key
1729 But we want to make sure another relationship is not already using the destination
1730 It's a bit complicated as the source SVM name can be aliased to a local name if there are conflicts
1731 So the source can be ansibleSVM: and show locally as ansibleSVM: if there is not conflict or ansibleSVM.1:
1732 or any alias the user likes.
1733 And in the input paramters, it may use the remote name or local alias.
1734 """
1735 if not current:
1736 return
1737 source_path = self.na_helper.safe_get(self.parameters, ['source_endpoint', 'path']) or self.parameters.get('source_path')
1738 destination_path = self.na_helper.safe_get(self.parameters, ['destination_endpoint', 'path']) or self.parameters.get('destination_path')
1739 source_cluster = self.na_helper.safe_get(self.parameters, ['source_endpoint', 'cluster']) or self.parameters.get('source_cluster')
1740 current_source_path = current.pop('source_path', None)
1741 if source_path and current_source_path and self.parameters.get('validate_source_path'):
1742 if self.parameters['connection_type'] != 'ontap_ontap':
1743 # take things at face value
1744 if current_source_path != source_path:
1745 self.module.fail_json(msg='Error: another relationship is present for the same destination with source_path:'
1746 ' "%s". Desired: %s on %s'
1747 % (current_source_path, source_path, source_cluster))
1748 return
1749 # with ONTAP -> ONTAP, vserver names can be aliased
1750 current_source_svm, dummy, dummy = current_source_path.rpartition(':')
1751 if not current_source_svm:
1752 self.module.warn('Unexpected source path: %s, skipping validation.' % current_source_path)
1753 destination_svm, dummy, dummy = destination_path.rpartition(':')
1754 if not destination_svm:
1755 self.module.warn('Unexpected destination path: %s, skipping validation.' % destination_path)
1756 if not current_source_svm or not destination_svm:
1757 return
1758 peer_svm, peer_cluster = self.get_svm_peer(current_source_svm, destination_svm)
1759 if peer_svm is not None:
1760 real_source_path = current_source_path.replace(current_source_svm, peer_svm, 1)
1761 # match either the local name or the remote name
1762 if (real_source_path != source_path and current_source_path != source_path)\
1763 or (peer_cluster is not None and source_cluster is not None and source_cluster != peer_cluster):
1764 self.module.fail_json(msg='Error: another relationship is present for the same destination with source_path:'
1765 ' "%s" (%s on cluster %s). Desired: %s on %s'
1766 % (current_source_path, real_source_path, peer_cluster, source_path, source_cluster))
1767
1768 def get_actions(self):
1769 restore = self.parameters.get('relationship_type', '') == 'restore'
1770 current = None if restore else self.snapmirror_get()
1771 self.validate_source_path(current)
1772 # ONTAP automatically convert DP to XDP
1773 if current and current['relationship_type'] == 'extended_data_protection' and self.parameters.get('relationship_type') == 'data_protection':
1774 self.parameters['relationship_type'] = 'extended_data_protection'
1775 cd_action = None if restore else self.na_helper.get_cd_action(current, self.parameters)
1776 modify = None
1777 if cd_action is None and self.parameters['state'] == 'present' and not restore:
1778 modify = self.na_helper.get_modified_attributes(current, self.parameters)
1779 if modify and 'relationship_type' in modify:
1780 self.module.fail_json(msg='Error: cannot modify relationship_type from %s to %s.' %
1781 (current['relationship_type'], modify['relationship_type']))
1782 actions = []
1783 if self.parameters['state'] == 'present' and restore:
1784 actions.append('restore')
1785 self.na_helper.changed = True
1786 elif cd_action == 'create':
1787 actions.append('create')
1788 elif cd_action == 'delete':
1789 if current['status'] == 'transferring' or self.parameters.get('current_transfer_status') == 'transferring':
1790 actions.append('abort')
1791 actions.append('delete')
1792 else:
1793 if modify:
1794 actions.append('modify')
1795 # If current is not None, it means the state is present otherwise we would take a delete action
1796 self.add_break_action(actions, current)
1797 self.add_active_actions(actions, current)
1798 return actions, current, modify
1799
1800 def take_actions(self, actions, current, modify):
1801 if 'restore' in actions:
1802 self.snapmirror_restore()
1803 if 'create' in actions:
1804 self.snapmirror_create()
1805 if 'abort' in actions:
1806 self.snapmirror_abort()
1807 self.wait_for_idle_status()
1808 if 'delete' in actions:
1809 self.delete_snapmirror(current['relationship_type'], current['mirror_state'])
1810 if 'modify' in actions:
1811 self.snapmirror_modify(modify)
1812 if 'break' in actions:
1813 self.snapmirror_break()
1814 if 'initialize' in actions:
1815 self.snapmirror_initialize(current)
1816 if 'resume' in actions:
1817 self.snapmirror_resume()
1818 if 'resync' in actions:
1819 self.snapmirror_resync(current)
1820
1821 def apply(self):
1822 """
1823 Apply action to SnapMirror
1824 """
1825 # source is ElementSW
1826 if self.parameters['state'] == 'present' and self.parameters.get('connection_type') == 'elementsw_ontap':
1827 self.check_elementsw_parameters()
1828 elif self.parameters.get('connection_type') == 'ontap_elementsw':
1829 self.check_elementsw_parameters('destination')
1830 else:
1831 self.check_parameters()
1832 if self.parameters['state'] == 'present' and self.parameters.get('connection_type') == 'ontap_elementsw':
1833 current_elementsw_ontap = self.snapmirror_get(self.parameters['source_path'])
1834 if current_elementsw_ontap is None:
1835 self.module.fail_json(msg='Error: creating an ONTAP to ElementSW snapmirror relationship requires an '
1836 'established SnapMirror relation from ElementSW to ONTAP cluster')
1837
1838 actions, current, modify = self.get_actions()
1839 if self.na_helper.changed and not self.module.check_mode:
1840 self.take_actions(actions, current, modify)
1841 if 'check_for_update' in actions:
1842 current = self.snapmirror_get()
1843 if current['mirror_state'] == 'snapmirrored':
1844 actions.append('update')
1845 if not self.module.check_mode:
1846 self.snapmirror_update(current['relationship_type'])
1847 self.na_helper.changed = True
1848
1849 self.check_health()
1850 if self.previous_errors:
1851 self.module.warn('Ignored error(s): %s' % ' -- '.join(self.previous_errors))
1852
1853 results = dict(changed=self.na_helper.changed)
1854 if actions:
1855 results['actions'] = actions
1856 self.module.exit_json(**results)
1857
1858
1859 def main():
1860 """Execute action"""
1861 snapmirror_obj = NetAppONTAPSnapmirror()
1862 snapmirror_obj.apply()
1863
1864
1865 if __name__ == '__main__':
1866 main()