Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2018-2026, NetApp, Inc
4 # GNU General Public License v3.0+
5 # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 module: na_ontap_volume
12 short_description: NetApp ONTAP manage volumes.
13 extends_documentation_fragment:
14 - netapp.ontap.netapp.na_ontap
15 version_added: 2.6.0
16 author: NetApp Ansible Team (@carchi8py) <[email protected]>
17
18 description:
19 - Create or destroy or modify volumes on NetApp ONTAP.
20
21 options:
22
23 state:
24 description:
25 - Whether the specified volume should exist or not.
26 choices: ['present', 'absent']
27 type: str
28 default: 'present'
29
30 name:
31 description:
32 - The name of the volume to manage.
33 type: str
34 required: true
35
36 vserver:
37 description:
38 - Name of the vserver to use.
39 type: str
40 required: true
41
42 from_name:
43 description:
44 - Name of the existing volume to be renamed to name.
45 type: str
46 version_added: 2.7.0
47
48 is_infinite:
49 type: bool
50 description:
51 - Set True if the volume is an Infinite Volume.
52 - Deleting an infinite volume is asynchronous.
53 default: false
54
55 is_online:
56 type: bool
57 description:
58 - Whether the specified volume is online, or not.
59 default: True
60
61 aggregate_name:
62 description:
63 - The name of the aggregate the flexvol should exist on.
64 - Cannot be set when using the C(nas_application_template) option.
65 type: str
66
67 tags:
68 description:
69 - Tags are an optional way to track the uses of a resource.
70 - Tag values must be formatted as key:value strings, example ["team:csi", "environment:test"]
71 type: list
72 elements: str
73 version_added: 22.6.0
74
75 nas_application_template:
76 description:
77 - additional options when using the application/applications REST API to create a volume.
78 - the module is using ZAPI by default, and switches to REST if any suboption is present.
79 - create a FlexVol by default.
80 - create a FlexGroup if C(auto_provision_as) is set and C(FlexCache) option is not present.
81 - create a FlexCache if C(flexcache) option is present.
82 type: dict
83 version_added: 20.12.0
84 suboptions:
85 flexcache:
86 description: whether to create a flexcache. If absent, a FlexVol or FlexGroup is created.
87 type: dict
88 suboptions:
89 dr_cache:
90 description:
91 - whether to use the same flexgroup msid as the origin.
92 - requires ONTAP 9.9 and REST.
93 - create only option, ignored if the flexcache already exists.
94 type: bool
95 version_added: 21.3.0
96 origin_svm_name:
97 description: the remote SVM for the flexcache.
98 type: str
99 required: true
100 origin_component_name:
101 description: the remote component for the flexcache.
102 type: str
103 required: true
104 cifs_access:
105 description:
106 - The list of CIFS access controls. You must provide I(user_or_group) or I(access) to enable CIFS access.
107 type: list
108 elements: dict
109 suboptions:
110 access:
111 description: The CIFS access granted to the user or group. Default is full_control.
112 type: str
113 choices: ['change', 'full_control', 'no_access', 'read']
114 user_or_group:
115 description: The name of the CIFS user or group that will be granted access. Default is Everyone.
116 type: str
117 nfs_access:
118 description:
119 - The list of NFS access controls. You must provide I(host) or I(access) to enable NFS access.
120 - Mutually exclusive with export_policy option.
121 type: list
122 elements: dict
123 suboptions:
124 access:
125 description: The NFS access granted. Default is rw.
126 type: str
127 choices: ['none', 'ro', 'rw']
128 host:
129 description: The name of the NFS entity granted access. Default is 0.0.0.0/0.
130 type: str
131 storage_service:
132 description:
133 - The performance service level (PSL) for this volume
134 type: str
135 choices: ['value', 'performance', 'extreme']
136 tiering:
137 description:
138 - Cloud tiering policy (see C(tiering_policy) for a more complete description).
139 type: dict
140 suboptions:
141 control:
142 description: Storage tiering placement rules for the container.
143 choices: ['required', 'best_effort', 'disallowed']
144 type: str
145 policy:
146 description:
147 - Cloud tiering policy (see C(tiering_policy)).
148 - Must match C(tiering_policy) if both are present.
149 choices: ['all', 'auto', 'none', 'snapshot_only']
150 type: str
151 object_stores:
152 description: list of object store names for tiering.
153 type: list
154 elements: str
155 exclude_aggregates:
156 description:
157 - The list of aggregate names to exclude when creating a volume.
158 - Requires ONTAP 9.9.1 GA or later.
159 type: list
160 elements: str
161 version_added: 21.7.0
162 use_nas_application:
163 description:
164 - Whether to use the application/applications REST/API to create a volume.
165 - This will default to true if any other suboption is present.
166 type: bool
167 default: true
168 cifs_share_name:
169 description:
170 - The name of the CIFS share.
171 - Requires ONTAP 9.11 or later.
172 type: str
173 version_added: 22.13.0
174 snapshot_locking_enabled:
175 description:
176 - Indicates whether Snapshot copy locking is enabled on the volume.
177 - Requires ONTAP 9.13.1 or later.
178 type: bool
179 version_added: 22.13.0
180 snaplock:
181 description: Requires ONTAP 9.12 or later.
182 type: dict
183 version_added: 22.13.0
184 suboptions:
185 snaplock_type:
186 description: The SnapLock type of the smart container.
187 choices: ['compliance', 'enterprise', 'non_snaplock']
188 type: str
189 autocommit_period:
190 description:
191 - Specifies the autocommit period for SnapLock volume.
192 - Duration is in the ISO-8601 duration format (eg PY, PM, PD, PTH, PTM).
193 - Examples are P30M, P10Y, PT1H, none. A duration that combines different periods is not supported.
194 type: str
195 append_mode_enabled:
196 description: Specifies if the volume append mode is enabled or disabled.
197 type: bool
198 retention:
199 description:
200 - Default, maximum, and minumum retention periods for files committed to the WORM state on the volume.
201 - Durations are in the ISO-8601 duration format, see autocommit_period.
202 type: dict
203 suboptions:
204 default:
205 description: Default retention period that is applied to files while committing them to the WORM state without an associated retention period.
206 type: str
207 maximum:
208 description: Maximum allowed retention period for files committed to the WORM state on the volume.
209 type: str
210 minimum:
211 description: Minimum allowed retention period for files committed to the WORM state on the volume.
212 type: str
213
214 size:
215 description:
216 - The size of the volume in (size_unit). Required when C(state=present).
217 type: int
218
219 size_unit:
220 description:
221 - The unit used to interpret the size parameter.
222 choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
223 type: str
224 default: 'gb'
225
226 size_change_threshold:
227 description:
228 - Percentage in size change to trigger a resize.
229 - When this parameter is greater than 0, a difference in size between what is expected and what is configured is ignored if it is below the threshold.
230 - For instance, the nas application allocates a larger size than specified to account for overhead.
231 - When using C(nas_application_template), if the overhead size difference is within the threshold,
232 the module updates the size parameter to match the allocated size for idempotency in subsequent runs.
233 - If the difference exceeds the threshold, the volume will be resized to the requested size.
234 - For regular volumes (without nas_application_template), size differences within the threshold are ignored without parameter updates.
235 - Set this to 0 for an exact match.
236 type: int
237 default: 10
238 version_added: 20.12.0
239
240 sizing_method:
241 description:
242 - Represents the method to modify the size of a FlexGroup.
243 - use_existing_resources - Increases or decreases the size of the FlexGroup by increasing or decreasing the size of the current FlexGroup resources.
244 - add_new_resources - Increases the size of the FlexGroup by adding new resources. This is limited to two new resources per available aggregate.
245 - This is only supported if REST is enabled (ONTAP 9.6 or later) and only for FlexGroups. ONTAP defaults to use_existing_resources.
246 type: str
247 choices: ['add_new_resources', 'use_existing_resources']
248 version_added: 20.12.0
249
250 type:
251 description:
252 - The volume type, either read-write (RW) or data-protection (DP).
253 type: str
254
255 export_policy:
256 description:
257 - Name of the export policy.
258 - Mutually exclusive with nfs_access suboption in nas_application_template.
259 type: str
260 aliases: ['policy']
261
262 junction_path:
263 description:
264 - Junction path of the volume.
265 - To unmount, use junction path C('').
266 type: str
267
268 space_guarantee:
269 description:
270 - Space guarantee style for the volume.
271 - The file setting is no longer supported.
272 choices: ['none', 'file', 'volume']
273 type: str
274
275 percent_snapshot_space:
276 description:
277 - Amount of space reserved for snapshot copies of the volume.
278 type: int
279
280 volume_security_style:
281 description:
282 - The security style associated with this volume.
283 choices: ['mixed', 'ntfs', 'unified', 'unix']
284 type: str
285
286 encrypt:
287 type: bool
288 description:
289 - Whether or not to enable Volume Encryption.
290 - If not present, ONTAP defaults to false at volume creation.
291 - Changing encrypt value after creation requires ONTAP 9.3 or later.
292 version_added: 2.7.0
293
294 efficiency_policy:
295 description:
296 - Allows a storage efficiency policy to be set on volume creation.
297 type: str
298 version_added: 2.7.0
299
300 unix_permissions:
301 description:
302 - Unix permission bits in octal or symbolic format.
303 - For example, 0 is equivalent to ------------, 777 is equivalent to ---rwxrwxrwx,both formats are accepted.
304 - The valid octal value ranges between 0 and 777 inclusive.
305 type: str
306 version_added: 2.8.0
307
308 group_id:
309 description:
310 - The UNIX group ID for the volume. The default value is 0 ('root').
311 type: int
312 version_added: '20.1.0'
313
314 user_id:
315 description:
316 - The UNIX user ID for the volume. The default value is 0 ('root').
317 type: int
318 version_added: '20.1.0'
319
320 snapshot_policy:
321 description:
322 - The name of the snapshot policy.
323 - The default policy name is 'default'.
324 - If present, this will set the protection_type when using C(nas_application_template).
325 type: str
326 version_added: 2.8.0
327
328 aggr_list:
329 description:
330 - an array of names of aggregates to be used for FlexGroup constituents.
331 type: list
332 elements: str
333 version_added: 2.8.0
334
335 aggr_list_multiplier:
336 description:
337 - The number of times to iterate over the aggregates listed with the aggr_list parameter when creating a FlexGroup.
338 type: int
339 version_added: 2.8.0
340
341 auto_provision_as:
342 description:
343 - Automatically provision a FlexGroup volume.
344 version_added: 2.8.0
345 choices: ['flexgroup']
346 type: str
347
348 snapdir_access:
349 description:
350 - This is an advanced option, the default is False.
351 - Enable the visible '.snapshot' directory that is normally present at system internal mount points.
352 - This value also turns on access to all other '.snapshot' directories in the volume.
353 - This option is supported in REST for ONTAP 9.13.1 or later with ONTAP collection version 22.8.0 or later.
354 type: bool
355 version_added: 2.8.0
356
357 atime_update:
358 description:
359 - This is an advanced option, the default is True.
360 - If false, prevent the update of inode access times when a file is read.
361 - This value is useful for volumes with extremely high read traffic,
362 since it prevents writes to the inode file for the volume from contending with reads from other files.
363 - This field should be used carefully.
364 - That is, use this field when you know in advance that the correct access time for inodes will not be needed for files on that volume.
365 - This option is supported in REST for ONTAP 9.8 or later with ONTAP collection version 22.8.0 or later.
366 type: bool
367 version_added: 2.8.0
368
369 vol_nearly_full_threshold_percent:
370 description:
371 - Specifies the percentage at which the volume is considered nearly full, and above which an EMS warning will be generated.
372 - The default value is 95%. The maximum value for this option is 99%.
373 - Setting this threshold to 0 disables the volume nearly full space alerts.
374 - Supported only with REST and requires ONTAP 9.9 or later.
375 type: int
376 version_added: 22.8.0
377
378 vol_full_threshold_percent:
379 description:
380 - Specifies the percentage at which the volume is considered full, and above which a critical EMS error will be generated.
381 - The default value is 98%. The maximum value for this option is 100%.
382 - Setting this threshold to 0 disables the volume full space alerts.
383 - Supported only with REST and requires ONTAP 9.9 or later.
384 type: int
385 version_added: 22.8.0
386
387 large_size_enabled:
388 description:
389 - Indicates if the support for large FlexVol volumes and large files is enabled on this volume.
390 type: bool
391 version_added: 22.14.0
392
393 wait_for_completion:
394 description:
395 - Set this parameter to 'true' for synchronous execution during create (wait until volume status is online)
396 - Set this parameter to 'false' for asynchronous execution
397 - For asynchronous, execution exits as soon as the request is sent, without checking volume status
398 type: bool
399 default: false
400 version_added: 2.8.0
401
402 time_out:
403 description:
404 - With ZAPI - time to wait for Flexgroup creation, modification, or deletion in seconds.
405 - With REST - time to wait for any volume creation, modification, or deletion in seconds.
406 - Error out if task is not completed in defined time.
407 - With ZAPI - if 0, the request is asynchronous.
408 - Default is set to 3 minutes.
409 - Use C(max_wait_time) and C(wait_for_completion) for volume move and encryption operations.
410 default: 180
411 type: int
412 version_added: 2.8.0
413
414 max_wait_time:
415 description:
416 - Volume move and encryption operations might take longer time to complete.
417 - With C(wait_for_completion) set, module will wait for time set in this option for volume move and encryption to complete.
418 - If time exipres, module exit and the operation may still be running.
419 - Default is set to 10 minutes.
420 default: 600
421 type: int
422 version_added: 22.0.0
423
424 language:
425 description:
426 - Language to use for Volume
427 - Default uses SVM language
428 - Possible values Language
429 - c POSIX
430 - ar Arabic
431 - cs Czech
432 - da Danish
433 - de German
434 - en English
435 - en_us English (US)
436 - es Spanish
437 - fi Finnish
438 - fr French
439 - he Hebrew
440 - hr Croatian
441 - hu Hungarian
442 - it Italian
443 - ja Japanese euc-j
444 - ja_v1 Japanese euc-j
445 - ja_jp.pck Japanese PCK (sjis)
446 - ja_jp.932 Japanese cp932
447 - ja_jp.pck_v2 Japanese PCK (sjis)
448 - ko Korean
449 - no Norwegian
450 - nl Dutch
451 - pl Polish
452 - pt Portuguese
453 - ro Romanian
454 - ru Russian
455 - sk Slovak
456 - sl Slovenian
457 - sv Swedish
458 - tr Turkish
459 - zh Simplified Chinese
460 - zh.gbk Simplified Chinese (GBK)
461 - zh_tw Traditional Chinese euc-tw
462 - zh_tw.big5 Traditional Chinese Big 5
463 - To use UTF-8 as the NFS character set, append '.UTF-8' to the language code
464 type: str
465 version_added: 2.8.0
466
467 qos_policy_group:
468 description:
469 - Specifies a QoS policy group to be set on volume.
470 type: str
471 version_added: 2.9.0
472
473 qos_adaptive_policy_group:
474 description:
475 - Specifies a QoS adaptive policy group to be set on volume.
476 type: str
477 version_added: 2.9.0
478
479 tiering_policy:
480 description:
481 - The tiering policy that is to be associated with the volume.
482 - This policy decides whether the blocks of a volume will be tiered to the capacity tier.
483 - snapshot-only policy allows tiering of only the volume snapshot copies not associated with the active file system.
484 - auto policy allows tiering of both snapshot and active file system user data to the capacity tier.
485 - backup policy on DP volumes allows all transferred user data blocks to start in the capacity tier.
486 - all is the REST equivalent for backup.
487 - When set to none, the Volume blocks will not be tiered to the capacity tier.
488 - If no value specified, the volume is assigned snapshot only by default.
489 - Requires ONTAP 9.4 or later.
490 choices: ['snapshot_only', 'auto', 'backup', 'none', 'all']
491 type: str
492 version_added: 2.9.0
493
494 tiering_object_tags:
495 description:
496 - This parameter specifies tags of a volume for objects stored on a FabricPool-enabled aggregate.
497 - Each tag is a key,value pair and should be in the format "key=value".
498 - A maximum of 4 tags are allowed per volume.
499 - To remove all existing tiering object tags, specify an empty list as the parameter value.
500 type: list
501 elements: str
502 version_added: 23.1.0
503
504 space_slo:
505 description:
506 - Specifies the space SLO type for the volume. The space SLO type is the Service Level Objective for space management for the volume.
507 - The space SLO value is used to enforce existing volume settings so that sufficient space is set aside on the aggregate to meet the space SLO.
508 - This parameter is not supported on Infinite Volumes.
509 choices: ['none', 'thick', 'semi-thick']
510 type: str
511 version_added: 2.9.0
512
513 nvfail_enabled:
514 description:
515 - If true, the controller performs additional work at boot and takeover times if it finds that there has been any potential data loss in the volume's
516 constituents due to an NVRAM failure.
517 - The volume's constituents would be put in a special state called 'in-nvfailed-state' such that protocol access is blocked.
518 - This will cause the client applications to crash and thus prevent access to stale data.
519 - To get out of this situation, the admin needs to manually clear the 'in-nvfailed-state' on the volume's constituents.
520 type: bool
521 version_added: 2.9.0
522
523 vserver_dr_protection:
524 description:
525 - Specifies the protection type for the volume in a Vserver DR setup.
526 choices: ['protected', 'unprotected']
527 type: str
528 version_added: 2.9.0
529
530 comment:
531 description:
532 - Sets a comment associated with the volume.
533 type: str
534 version_added: 2.9.0
535
536 snapshot_auto_delete:
537 description:
538 - A dictionary for the auto delete options and values.
539 - All the above mentioned options except 'destroy_list' are supported in REST for ONTAP 9.13.1 or later with ONTAP collection version 22.8.0 or later.
540 type: dict
541 version_added: '20.4.0'
542 suboptions:
543 state:
544 description: Determines if the snapshot autodelete is currently enabled for the volume.
545 type: str
546 choices: ['on', 'off']
547 commitment:
548 description: Determines the snapshots that the snapshot autodelete is allowed to delete to get back space.
549 type: str
550 choices: [try, disrupt, destroy]
551 trigger:
552 description:
553 - Determines the condition which starts the automatic deletion of snapshots.
554 - Note - C(space_reserve) option is deprecated and may be removed in the future.
555 type: str
556 choices: [volume, snap_reserve, space_reserve]
557 target_free_space:
558 description:
559 - Determines when snapshot autodelete should stop deleting snapshots.
560 - Depending on the trigger, snapshots are deleted until the target free space percentage is reached.
561 type: int
562 delete_order:
563 description: Determines if the oldest or newest snapshot is deleted first.
564 type: str
565 choices: [newest_first, oldest_first]
566 defer_delete:
567 description: Determines what kind of snapshot to delete in the end.
568 type: str
569 choices: [scheduled, user_created, prefix, 'none']
570 prefix:
571 description:
572 - Can be set to provide the prefix string for the 'prefix' value of the 'defer_delete' option.
573 - The prefix string can be 15 characters long.
574 type: str
575 destroy_list:
576 description:
577 - A comma seperated list of services which can be destroyed if the snapshot backing that service is deleted.
578 - For 7-mode, the possible values for this option are a combination of 'lun_clone', 'vol_clone', 'cifs_share', 'file_clone' or 'none'.
579 - For cluster-mode, the possible values for this option are a combination of 'lun_clone,file_clone' (for LUN clone and/or file clone),
580 'lun_clone,sfsr' (for LUN clone and/or sfsr), 'vol_clone', 'cifs_share', or 'none'.
581 type: str
582
583 cutover_action:
584 description:
585 - Specifies the action to be taken for cutover.
586 - Possible values are 'abort_on_failure', 'defer_on_failure', 'force' and 'wait'. Default is 'defer_on_failure'.
587 choices: ['abort_on_failure', 'defer_on_failure', 'force', 'wait']
588 type: str
589 version_added: '20.5.0'
590
591 check_interval:
592 description:
593 - The amount of time in seconds to wait between checks of a volume to see if it has moved successfully.
594 default: 30
595 type: int
596 version_added: '20.6.0'
597
598 from_vserver:
599 description:
600 - The source vserver of the volume is rehosted.
601 type: str
602 version_added: '20.6.0'
603
604 auto_remap_luns:
605 description:
606 - Flag to control automatic map of LUNs.
607 type: bool
608 version_added: '20.6.0'
609
610 force_unmap_luns:
611 description:
612 - Flag to control automatic unmap of LUNs.
613 type: bool
614 version_added: '20.6.0'
615
616 force_restore:
617 description:
618 - If this field is set to "true", the Snapshot copy is restored even if the volume has one or more newer Snapshot
619 copies which are currently used as reference Snapshot copy by SnapMirror. If a restore is done in this
620 situation, this will cause future SnapMirror transfers to fail.
621 - Option should only be used along with snapshot_restore.
622 type: bool
623 version_added: '20.6.0'
624
625 preserve_lun_ids:
626 description:
627 - If this field is set to "true", LUNs in the volume being restored will remain mapped and their identities
628 preserved such that host connectivity will not be disrupted during the restore operation. I/O's to the LUN will
629 be fenced during the restore operation by placing the LUNs in an unavailable state. Once the restore operation
630 has completed, hosts will be able to resume I/O access to the LUNs.
631 - Option should only be used along with snapshot_restore.
632 type: bool
633 version_added: '20.6.0'
634
635 snapshot_restore:
636 description:
637 - Name of snapshot to restore from.
638 - Not supported on Infinite Volume.
639 type: str
640 version_added: '20.6.0'
641
642 compression:
643 description:
644 - Whether to enable compression for the volume (HDD and Flash Pool aggregates).
645 - If this option is not present, it is automatically set to true if inline_compression is true.
646 type: bool
647 version_added: '20.12.0'
648
649 inline_compression:
650 description:
651 - Whether to enable inline compression for the volume (HDD and Flash Pool aggregates, AFF platforms).
652 type: bool
653 version_added: '20.12.0'
654
655 tiering_minimum_cooling_days:
656 description:
657 - Determines how many days must pass before inactive data in a volume using the Auto or Snapshot-Only policy is
658 considered cold and eligible for tiering.
659 - This option is only supported in REST 9.8 or later.
660 type: int
661 version_added: '21.16.0'
662
663 logical_space_enforcement:
664 description:
665 - This optionally specifies whether to perform logical space accounting on the volume. When space is enforced
666 logically, ONTAP enforces volume settings such that all the physical space saved by the storage efficiency
667 features will be calculated as used.
668 - This is only supported with REST.
669 type: bool
670 version_added: '21.16.0'
671
672 logical_space_reporting:
673 description:
674 - This optionally specifies whether to report space logically on the volume. When space is reported logically,
675 ONTAP reports the volume space such that all the physical space saved by the storage efficiency features are also
676 reported as used.
677 - This is only supported with REST.
678 type: bool
679 version_added: '21.16.0'
680
681 snaplock:
682 description:
683 - Starting with ONTAP 9.10.1, snaplock.type is set at the volume level.
684 - The other suboptions can be set or modified when using REST on earlier versions of ONTAP.
685 - These option and suboptions are only supported with REST.
686 type: dict
687 version_added: 21.18.0
688 suboptions:
689 append_mode_enabled:
690 description:
691 - when enabled, all the files created with write permissions on the volume are, by default,
692 WORM appendable files. The user can append the data to a WORM appendable file but cannot modify
693 the existing contents of the file nor delete the file until it expires.
694 type: bool
695 autocommit_period:
696 description:
697 - autocommit period for SnapLock volume. All files which are not modified for a period greater than
698 the autocommit period of the volume are committed to the WORM state.
699 - duration is in the ISO-8601 duration format (eg PY, PM, PD, PTH, PTM).
700 - examples P30M, P10Y, PT1H, "none". A duration that combines different periods is not supported.
701 type: str
702 privileged_delete:
703 description:
704 - privileged-delete attribute of a SnapLock volume.
705 - On a SnapLock Enterprise (SLE) volume, a designated privileged user can selectively delete files irrespective of the retention time of the file.
706 - On a SnapLock Compliance (SLC) volume, it is always permanently_disabled.
707 type: str
708 choices: [disabled, enabled, permanently_disabled]
709 retention:
710 description:
711 - default, maximum, and minumum retention periods for files committed to the WORM state on the volume.
712 - durations are in the ISO-8601 duration format, see autocommit_period.
713 type: dict
714 suboptions:
715 default:
716 description:
717 - default retention period that is applied to files while committing them to the WORM state without an associated retention period.
718 type: str
719 maximum:
720 description:
721 - maximum allowed retention period for files committed to the WORM state on the volume.
722 type: str
723 minimum:
724 description:
725 - minimum allowed retention period for files committed to the WORM state on the volume.
726 type: str
727 type:
728 description:
729 - The SnapLock type of the volume.
730 - compliance - A SnapLock Compliance (SLC) volume provides the highest level of WORM protection and
731 an administrator cannot destroy a SLC volume if it contains unexpired WORM files.
732 - enterprise - An administrator can delete a SnapLock Enterprise (SLE) volume.
733 - non_snaplock - Indicates the volume is non-snaplock.
734 type: str
735 choices: [compliance, enterprise, non_snaplock]
736
737 max_files:
738 description:
739 - The maximum number of files (inodes) for user-visible data allowed on the volume.
740 - Note - ONTAP allocates a slightly different value, for instance 3990 when asking for 4000.
741 Tp preserve idempotency, small variations in size are ignored.
742 type: int
743 version_added: '21.18.0'
744
745 analytics:
746 description:
747 - Sets file system analytics state of the volume.
748 - Only supported with REST and requires ONTAP 9.8 or later version.
749 - Cannot enable analytics for volume that contains luns.
750 type: str
751 version_added: '22.0.0'
752 choices: ['on', 'off']
753
754 activity_tracking:
755 description:
756 - Sets activity tracking state of the volume.
757 - Only supported with REST and requires ONTAP 9.10 or later version.
758 type: str
759 version_added: '22.12.0'
760 choices: ['on', 'off']
761
762 snapshot_locking:
763 description:
764 - Specifies whether or not snapshot copy locking is enabled on the volume.
765 - Only supported with REST and requires ONTAP 9.12 or later.
766 type: bool
767 version_added: '22.12.0'
768
769 granular_data:
770 description:
771 - State of granular data on the volume.
772 - Only FlexGroup volumes support this feature. Once enabled, this setting can only be disabled by restoring a Snapshot copy.
773 - Only supported with REST and requires ONTAP 9.12 or later.
774 type: bool
775 version_added: 22.13.0
776
777 anti_ransomware:
778 description:
779 - Anti-ransomware related information of the volume.
780 - Only supported with REST and requires ONTAP 9.10 or later.
781 type: dict
782 version_added: 23.5.0
783 suboptions:
784 state:
785 description:
786 - Determines the the anti-ransomware state for the volume.
787 - C(paused) is valid only for modify operation.
788 type: str
789 choices: ['enabled', 'disabled', 'dry_run', 'paused']
790
791 lambda_config:
792 description:
793 - Configuration parameters for AWS Lambda proxy functionality.
794 - These option and suboptions are only supported with REST.
795 type: dict
796 version_added: 23.2.0
797 suboptions:
798 function_name:
799 description:
800 - The name of the AWS Lambda function to invoke.
801 type: str
802 required: true
803 aws_region:
804 description:
805 - The name of the AWS region.
806 type: str
807 required: true
808 aws_profile:
809 description:
810 - The name of the AWS profile to use for authentication.
811 type: str
812
813 notes:
814 - supports REST and ZAPI. REST requires ONTAP 9.6 or later. Efficiency with REST requires ONTAP 9.7 or later.
815 - REST is enabled when C(use_rest) is set to always.
816 - The feature_flag C(warn_or_fail_on_fabricpool_backend_change) controls whether an error is reported when
817 tiering control would require or disallow FabricPool for an existing volume with a different backend.
818 Allowed values are fail, warn, and ignore, and the default is set to fail.
819 - snapshot_restore is not idempotent, it always restores.
820 - Supports AWS Lambda proxy functionality when using REST. See the README file for examples.
821
822 '''
823
824 EXAMPLES = """
825 - name: Create FlexVol
826 netapp.ontap.na_ontap_volume:
827 state: present
828 name: ansibleVolume12
829 is_infinite: false
830 aggregate_name: ansible_aggr
831 size: 100
832 size_unit: mb
833 user_id: 1001
834 group_id: 2002
835 space_guarantee: none
836 tiering_policy: auto
837 export_policy: default
838 percent_snapshot_space: 60
839 qos_policy_group: max_performance_gold
840 vserver: ansibleVServer
841 wait_for_completion: true
842 space_slo: none
843 nvfail_enabled: false
844 comment: ansible created volume
845 tiering_object_tags: ['tag1=one', 'tag2=two', 'tag3=3', 'tag4=4']
846 hostname: "{{ netapp_hostname }}"
847 username: "{{ netapp_username }}"
848 password: "{{ netapp_password }}"
849
850 - name: Volume Delete
851 netapp.ontap.na_ontap_volume:
852 state: absent
853 name: ansibleVolume12
854 aggregate_name: ansible_aggr
855 vserver: ansibleVServer
856 hostname: "{{ netapp_hostname }}"
857 username: "{{ netapp_username }}"
858 password: "{{ netapp_password }}"
859
860 - name: Make FlexVol offline
861 netapp.ontap.na_ontap_volume:
862 state: present
863 name: ansibleVolume
864 is_infinite: false
865 is_online: false
866 vserver: ansibleVServer
867 hostname: "{{ netapp_hostname }}"
868 username: "{{ netapp_username }}"
869 password: "{{ netapp_password }}"
870
871 - name: Create Flexgroup volume manually
872 netapp.ontap.na_ontap_volume:
873 state: present
874 name: ansibleVolume
875 is_infinite: false
876 aggr_list: "{{ aggr_list }}"
877 aggr_list_multiplier: 2
878 size: 200
879 size_unit: mb
880 space_guarantee: none
881 export_policy: default
882 vserver: "{{ vserver }}"
883 hostname: "{{ netapp_hostname }}"
884 username: "{{ netapp_username }}"
885 password: "{{ netapp_password }}"
886 https: false
887 unix_permissions: 777
888 snapshot_policy: default
889 time_out: 0
890
891 - name: Create Flexgroup volume auto provsion as flex group
892 netapp.ontap.na_ontap_volume:
893 state: present
894 name: ansibleVolume
895 is_infinite: false
896 auto_provision_as: flexgroup
897 size: 200
898 size_unit: mb
899 space_guarantee: none
900 export_policy: default
901 vserver: "{{ vserver }}"
902 hostname: "{{ netapp_hostname }}"
903 username: "{{ netapp_username }}"
904 password: "{{ netapp_password }}"
905 https: false
906 unix_permissions: 777
907 snapshot_policy: default
908 time_out: 0
909
910 - name: Create FlexVol with QoS adaptive
911 netapp.ontap.na_ontap_volume:
912 state: present
913 name: ansibleVolume15
914 is_infinite: false
915 aggregate_name: ansible_aggr
916 size: 100
917 size_unit: gb
918 space_guarantee: none
919 export_policy: default
920 percent_snapshot_space: 10
921 qos_adaptive_policy_group: extreme
922 vserver: ansibleVServer
923 wait_for_completion: true
924 hostname: "{{ netapp_hostname }}"
925 username: "{{ netapp_username }}"
926 password: "{{ netapp_password }}"
927
928 - name: Modify volume dr protection (vserver of the volume must be in a snapmirror relationship)
929 netapp.ontap.na_ontap_volume:
930 state: present
931 name: ansibleVolume
932 vserver_dr_protection: protected
933 vserver: "{{ vserver }}"
934 hostname: "{{ netapp_hostname }}"
935 username: "{{ netapp_username }}"
936 password: "{{ netapp_password }}"
937 https: false
938
939 - name: Modify volume with snapshot auto delete options
940 netapp.ontap.na_ontap_volume:
941 state: present
942 name: vol_auto_delete
943 snapshot_auto_delete:
944 state: "on"
945 commitment: try
946 defer_delete: scheduled
947 target_free_space: 30
948 destroy_list: lun_clone,vol_clone
949 delete_order: newest_first
950 aggregate_name: "{{ aggr }}"
951 vserver: "{{ vserver }}"
952 hostname: "{{ netapp_hostname }}"
953 username: "{{ netapp_username }}"
954 password: "{{ netapp_password }}"
955 https: false
956
957 - name: Move volume with force cutover action
958 netapp.ontap.na_ontap_volume:
959 name: ansible_vol
960 aggregate_name: aggr_ansible
961 cutover_action: force
962 vserver: "{{ vserver }}"
963 hostname: "{{ netapp_hostname }}"
964 username: "{{ netapp_username }}"
965 password: "{{ netapp_password }}"
966 https: false
967
968 - name: Rehost volume to another vserver auto remap luns
969 netapp.ontap.na_ontap_volume:
970 name: ansible_vol
971 from_vserver: ansible
972 auto_remap_luns: true
973 vserver: "{{ vserver }}"
974 hostname: "{{ netapp_hostname }}"
975 username: "{{ netapp_username }}"
976 password: "{{ netapp_password }}"
977 https: false
978
979 - name: Rehost volume to another vserver force unmap luns
980 netapp.ontap.na_ontap_volume:
981 name: ansible_vol
982 from_vserver: ansible
983 force_unmap_luns: true
984 vserver: "{{ vserver }}"
985 hostname: "{{ netapp_hostname }}"
986 username: "{{ netapp_username }}"
987 password: "{{ netapp_password }}"
988 https: false
989
990 - name: Snapshot restore volume
991 netapp.ontap.na_ontap_volume:
992 name: ansible_vol
993 vserver: ansible
994 snapshot_restore: 2020-05-24-weekly
995 force_restore: true
996 preserve_lun_ids: true
997 hostname: "{{ netapp_hostname }}"
998 username: "{{ netapp_username }}"
999 password: "{{ netapp_password }}"
1000 https: true
1001 validate_certs: false
1002
1003 - name: Volume create using application/applications nas template
1004 netapp.ontap.na_ontap_volume:
1005 state: present
1006 name: ansibleVolume12
1007 vserver: ansibleSVM
1008 size: 100000000
1009 size_unit: b
1010 space_guarantee: none
1011 language: es
1012 percent_snapshot_space: 60
1013 unix_permissions: ---rwxrwxrwx
1014 snapshot_policy: default
1015 efficiency_policy: default
1016 comment: testing
1017 nas_application_template:
1018 nfs_access: # the mere presence of a suboption is enough to enable this new feature
1019 - access: ro
1020 - access: rw
1021 host: 10.0.0.0/8
1022 exclude_aggregates: aggr0
1023 hostname: "{{ netapp_hostname }}"
1024 username: "{{ netapp_username }}"
1025 password: "{{ netapp_password }}"
1026 https: true
1027 validate_certs: false
1028
1029 # requires Ontap collection version - 21.24.0 to use iso filter plugin.
1030 - name: volume create with snaplock set.
1031 netapp.ontap.na_ontap_volume:
1032 state: present
1033 name: "{{ snaplock_volume }}"
1034 aggregate_name: "{{ aggregate }}"
1035 size: 20
1036 size_unit: mb
1037 space_guarantee: none
1038 policy: default
1039 type: rw
1040 snaplock:
1041 type: enterprise
1042 retention:
1043 default: "{{ 60 | netapp.ontap.iso8601_duration_from_seconds }}"
1044
1045 - name: Create volume with snapshot-auto-delete options - REST
1046 netapp.ontap.na_ontap_volume:
1047 state: present
1048 name: test_vol
1049 aggregate_name: "{{ aggr }}"
1050 size: 20
1051 size_unit: mb
1052 snapshot_auto_delete:
1053 state: 'on'
1054 trigger: volume
1055 delete_order: "oldest_first"
1056 defer_delete: "user_created"
1057 commitment: "try"
1058 target_free_space: 30
1059 prefix: "my_prefix"
1060 wait_for_completion: true
1061
1062 - name: Modify volume - REST
1063 netapp.ontap.na_ontap_volume:
1064 state: present
1065 name: test_vol
1066 aggregate_name: "{{ aggr }}"
1067 snapdir_access: false
1068 snapshot_auto_delete:
1069 state: 'on'
1070 target_free_space: 25
1071
1072 - name: Modify volume tiering onject_tags - REST
1073 netapp.ontap.na_ontap_volume:
1074 state: present
1075 name: test_vol
1076 aggregate_name: "{{ aggr }}"
1077 tiering_object_tags: ['tag1=one', 'tag2=two']
1078 """
1079
1080 RETURN = """
1081 """
1082
1083 import time
1084 import traceback
1085 from ansible.module_utils.basic import AnsibleModule
1086 from ansible.module_utils._text import to_native
1087 import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils
1088 from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule
1089 from ansible_collections.netapp.ontap.plugins.module_utils.rest_application import RestApplication
1090 from ansible_collections.netapp.ontap.plugins.module_utils import rest_generic
1091 from ansible_collections.netapp.ontap.plugins.module_utils import rest_vserver
1092
1093
1094 class NetAppOntapVolume:
1095 '''Class with volume operations'''
1096
1097 def __init__(self):
1098 '''Initialize module parameters'''
1099 self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
1100 self.argument_spec.update(dict(
1101 state=dict(required=False, type='str', choices=['present', 'absent'], default='present'),
1102 name=dict(required=True, type='str'),
1103 vserver=dict(required=True, type='str'),
1104 from_name=dict(required=False, type='str'),
1105 is_infinite=dict(required=False, type='bool', default=False),
1106 is_online=dict(required=False, type='bool', default=True),
1107 size=dict(type='int', default=None),
1108 size_unit=dict(default='gb', choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'], type='str'),
1109 sizing_method=dict(choices=['add_new_resources', 'use_existing_resources'], type='str'),
1110 aggregate_name=dict(type='str', default=None),
1111 type=dict(type='str', default=None),
1112 export_policy=dict(type='str', default=None, aliases=['policy']),
1113 junction_path=dict(type='str', default=None),
1114 space_guarantee=dict(choices=['none', 'file', 'volume'], default=None),
1115 percent_snapshot_space=dict(type='int', default=None),
1116 volume_security_style=dict(choices=['mixed', 'ntfs', 'unified', 'unix']),
1117 encrypt=dict(required=False, type='bool'),
1118 efficiency_policy=dict(required=False, type='str'),
1119 unix_permissions=dict(required=False, type='str'),
1120 group_id=dict(required=False, type='int'),
1121 user_id=dict(required=False, type='int'),
1122 snapshot_policy=dict(required=False, type='str'),
1123 aggr_list=dict(required=False, type='list', elements='str'),
1124 aggr_list_multiplier=dict(required=False, type='int'),
1125 snapdir_access=dict(required=False, type='bool'),
1126 atime_update=dict(required=False, type='bool'),
1127 vol_nearly_full_threshold_percent=dict(required=False, type='int'),
1128 vol_full_threshold_percent=dict(required=False, type='int'),
1129 large_size_enabled=dict(required=False, type='bool'),
1130 auto_provision_as=dict(choices=['flexgroup'], required=False, type='str'),
1131 wait_for_completion=dict(required=False, type='bool', default=False),
1132 time_out=dict(required=False, type='int', default=180),
1133 max_wait_time=dict(required=False, type='int', default=600),
1134 language=dict(type='str', required=False),
1135 qos_policy_group=dict(required=False, type='str'),
1136 qos_adaptive_policy_group=dict(required=False, type='str'),
1137 nvfail_enabled=dict(type='bool', required=False),
1138 space_slo=dict(type='str', required=False, choices=['none', 'thick', 'semi-thick']),
1139 tiering_policy=dict(type='str', required=False, choices=['snapshot_only', 'auto', 'backup', 'none', 'all']),
1140 tiering_object_tags=dict(type='list', elements='str', required=False),
1141 vserver_dr_protection=dict(type='str', required=False, choices=['protected', 'unprotected']),
1142 comment=dict(type='str', required=False),
1143 snapshot_auto_delete=dict(type='dict', required=False),
1144 cutover_action=dict(required=False, type='str', choices=['abort_on_failure', 'defer_on_failure', 'force', 'wait']),
1145 check_interval=dict(required=False, type='int', default=30),
1146 from_vserver=dict(required=False, type='str'),
1147 auto_remap_luns=dict(required=False, type='bool'),
1148 force_unmap_luns=dict(required=False, type='bool'),
1149 force_restore=dict(required=False, type='bool'),
1150 compression=dict(required=False, type='bool'),
1151 inline_compression=dict(required=False, type='bool'),
1152 preserve_lun_ids=dict(required=False, type='bool'),
1153 snapshot_restore=dict(required=False, type='str'),
1154 nas_application_template=dict(type='dict', options=dict(
1155 use_nas_application=dict(type='bool', default=True),
1156 exclude_aggregates=dict(type='list', elements='str'),
1157 flexcache=dict(type='dict', options=dict(
1158 dr_cache=dict(type='bool'),
1159 origin_svm_name=dict(required=True, type='str'),
1160 origin_component_name=dict(required=True, type='str')
1161 )),
1162 cifs_access=dict(type='list', elements='dict', options=dict(
1163 access=dict(type='str', choices=['change', 'full_control', 'no_access', 'read']),
1164 user_or_group=dict(type='str')
1165 )),
1166 nfs_access=dict(type='list', elements='dict', options=dict(
1167 access=dict(type='str', choices=['none', 'ro', 'rw']),
1168 host=dict(type='str')
1169 )),
1170 storage_service=dict(type='str', choices=['value', 'performance', 'extreme']),
1171 tiering=dict(type='dict', options=dict(
1172 control=dict(type='str', choices=['required', 'best_effort', 'disallowed']),
1173 policy=dict(type='str', choices=['all', 'auto', 'none', 'snapshot_only']),
1174 object_stores=dict(type='list', elements='str') # create only
1175 )),
1176 cifs_share_name=dict(required=False, type='str'),
1177 snapshot_locking_enabled=dict(required=False, type='bool'),
1178 snaplock=dict(type='dict', options=dict(
1179 append_mode_enabled=dict(required=False, type='bool'),
1180 autocommit_period=dict(required=False, type='str'),
1181 retention=dict(type='dict', options=dict(
1182 default=dict(required=False, type='str'),
1183 maximum=dict(required=False, type='str'),
1184 minimum=dict(required=False, type='str')
1185 )),
1186 snaplock_type=dict(required=False, type='str', choices=['compliance', 'enterprise', 'non_snaplock'])
1187 )),
1188 )),
1189 size_change_threshold=dict(type='int', default=10),
1190 tiering_minimum_cooling_days=dict(required=False, type='int'),
1191 logical_space_enforcement=dict(required=False, type='bool'),
1192 logical_space_reporting=dict(required=False, type='bool'),
1193 snaplock=dict(type='dict', options=dict(
1194 append_mode_enabled=dict(required=False, type='bool'),
1195 autocommit_period=dict(required=False, type='str'),
1196 privileged_delete=dict(required=False, type='str', choices=['disabled', 'enabled', 'permanently_disabled']),
1197 retention=dict(type='dict', options=dict(
1198 default=dict(required=False, type='str'),
1199 maximum=dict(required=False, type='str'),
1200 minimum=dict(required=False, type='str')
1201 )),
1202 type=dict(required=False, type='str', choices=['compliance', 'enterprise', 'non_snaplock'])
1203 )),
1204 max_files=dict(required=False, type='int'),
1205 analytics=dict(required=False, type='str', choices=['on', 'off']),
1206 activity_tracking=dict(required=False, type='str', choices=['on', 'off']),
1207 tags=dict(required=False, type='list', elements='str'),
1208 snapshot_locking=dict(required=False, type='bool'),
1209 granular_data=dict(required=False, type='bool'),
1210 anti_ransomware=dict(type='dict', options=dict(
1211 state=dict(required=False, type='str', choices=['enabled', 'disabled', 'dry_run', 'paused']),
1212 )),
1213 ))
1214 self.argument_spec.update(netapp_utils.na_ontap_lambda_argument_spec())
1215 self.module = AnsibleModule(
1216 argument_spec=self.argument_spec,
1217 mutually_exclusive=[
1218 ['space_guarantee', 'space_slo'], ['auto_remap_luns', 'force_unmap_luns']
1219 ],
1220 required_if=[
1221 ['use_lambda', True, ('lambda_config',)]
1222 ],
1223 supports_check_mode=True
1224 )
1225 self.na_helper = NetAppModule(self)
1226 self.parameters = self.na_helper.check_and_set_parameters(self.module)
1227 self.volume_style = None
1228 self.volume_created = False
1229 self.issues = []
1230 self.sis_keys2zapi_get = dict(
1231 efficiency_policy='policy',
1232 compression='is-compression-enabled',
1233 inline_compression='is-inline-compression-enabled')
1234 self.sis_keys2zapi_set = dict(
1235 efficiency_policy='policy-name',
1236 compression='enable-compression',
1237 inline_compression='enable-inline-compression')
1238
1239 if self.parameters.get('size'):
1240 self.parameters['size'] = self.parameters['size'] * \
1241 netapp_utils.POW2_BYTE_MAP[self.parameters['size_unit']]
1242 self.validate_snapshot_auto_delete()
1243 self.rest_api = netapp_utils.OntapRestAPI(self.module)
1244 unsupported_rest_properties = ['cutover_action',
1245 'encrypt-destination',
1246 'force_restore',
1247 'nvfail_enabled',
1248 'preserve_lun_ids',
1249 'destroy_list',
1250 'space_slo',
1251 'vserver_dr_protection']
1252 partially_supported_rest_properties = [['efficiency_policy', (9, 7)], ['tiering_minimum_cooling_days', (9, 8)],
1253 ['analytics', (9, 8)], ['atime_update', (9, 8)], ['tiering_object_tags', (9, 8)],
1254 ['vol_nearly_full_threshold_percent', (9, 9)], ['vol_full_threshold_percent', (9, 9)],
1255 ['activity_tracking', (9, 10, 1)], ['anti_ransomware', (9, 10, 1)],
1256 ['snapshot_locking', (9, 12, 1)], ['granular_data', (9, 12, 1)],
1257 ['large_size_enabled', (9, 12, 1)], ['tags', (9, 13, 1)],
1258 ['snapdir_access', (9, 13, 1)], ['snapshot_auto_delete', (9, 13, 1)]]
1259 self.unsupported_zapi_properties = ['sizing_method', 'logical_space_enforcement', 'logical_space_reporting', 'snaplock',
1260 'analytics', 'activity_tracking', 'tags', 'vol_nearly_full_threshold_percent',
1261 'vol_full_threshold_percent', 'large_size_enabled', 'snapshot_locking', 'granular_data',
1262 'anti_ransomware', 'tiering_object_tags']
1263 self.use_rest = self.rest_api.is_rest_supported_properties(self.parameters, unsupported_rest_properties, partially_supported_rest_properties)
1264
1265 if not self.use_rest:
1266 if self.parameters.get('use_lambda'):
1267 self.module.fail_json(msg="Error: AWS Lambda proxy for ONTAP APIs is only supported with REST.")
1268 self.setup_zapi()
1269 if self.use_rest:
1270 self.rest_errors()
1271
1272 # REST API for application/applications if needed - will report an error when REST is not supported
1273 self.rest_app = self.setup_rest_application()
1274
1275 def setup_zapi(self):
1276 if netapp_utils.has_netapp_lib() is False:
1277 self.module.fail_json(msg=netapp_utils.netapp_lib_is_required())
1278
1279 for unsupported_zapi_property in self.unsupported_zapi_properties:
1280 if self.parameters.get(unsupported_zapi_property) is not None:
1281 msg = "Error: %s option is not supported with ZAPI. It can only be used with REST." % unsupported_zapi_property
1282 msg += ' use_rest: %s.' % self.parameters['use_rest']
1283 if self.rest_api.fallback_to_zapi_reason:
1284 msg += ' Conflict %s.' % self.rest_api.fallback_to_zapi_reason
1285 self.module.fail_json(msg=msg)
1286 self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver'])
1287 self.cluster = netapp_utils.setup_na_ontap_zapi(module=self.module)
1288
1289 def validate_snapshot_auto_delete(self):
1290 if 'snapshot_auto_delete' in self.parameters:
1291 for key in self.parameters['snapshot_auto_delete']:
1292 if key not in ['commitment', 'trigger', 'target_free_space', 'delete_order', 'defer_delete',
1293 'prefix', 'destroy_list', 'state']:
1294 self.module.fail_json(msg="snapshot_auto_delete option '%s' is not valid." % key)
1295
1296 def setup_rest_application(self):
1297 rest_app = None
1298 if self.na_helper.safe_get(self.parameters, ['nas_application_template', 'use_nas_application']):
1299 if not self.use_rest:
1300 msg = 'Error: nas_application_template requires REST support.'
1301 msg += ' use_rest: %s.' % self.parameters['use_rest']
1302 if self.rest_api.fallback_to_zapi_reason:
1303 msg += ' Conflict %s.' % self.rest_api.fallback_to_zapi_reason
1304 self.module.fail_json(msg=msg)
1305 # consistency checks
1306 # tiering policy is duplicated, make sure values are matching
1307 tiering_policy_nas = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'tiering', 'policy'])
1308 tiering_policy = self.na_helper.safe_get(self.parameters, ['tiering_policy'])
1309 if tiering_policy_nas is not None and tiering_policy is not None and tiering_policy_nas != tiering_policy:
1310 msg = 'Conflict: if tiering_policy and nas_application_template tiering policy are both set, they must match.'
1311 msg += ' Found "%s" and "%s".' % (tiering_policy, tiering_policy_nas)
1312 self.module.fail_json(msg=msg)
1313 # aggregate_name will force a move if present
1314 if self.parameters.get('aggregate_name') is not None:
1315 msg = 'Conflict: aggregate_name is not supported when application template is enabled.'\
1316 ' Found: aggregate_name: %s' % self.parameters['aggregate_name']
1317 self.module.fail_json(msg=msg)
1318 nfs_access = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'nfs_access'])
1319 if nfs_access is not None and self.na_helper.safe_get(self.parameters, ['export_policy']) is not None:
1320 msg = 'Conflict: export_policy option and nfs_access suboption in nas_application_template are mutually exclusive.'
1321 self.module.fail_json(msg=msg)
1322 rest_app = RestApplication(self.rest_api, self.parameters['vserver'], self.parameters['name'])
1323 return rest_app
1324
1325 def volume_get_iter(self, vol_name=None):
1326 """
1327 Return volume-get-iter query results
1328 :param vol_name: name of the volume
1329 :return: NaElement
1330 """
1331 volume_info = netapp_utils.zapi.NaElement('volume-get-iter')
1332 volume_attributes = netapp_utils.zapi.NaElement('volume-attributes')
1333 volume_id_attributes = netapp_utils.zapi.NaElement('volume-id-attributes')
1334 volume_id_attributes.add_new_child('name', vol_name)
1335 volume_id_attributes.add_new_child('vserver', self.parameters['vserver'])
1336 volume_attributes.add_child_elem(volume_id_attributes)
1337 query = netapp_utils.zapi.NaElement('query')
1338 query.add_child_elem(volume_attributes)
1339 volume_info.add_child_elem(query)
1340
1341 try:
1342 result = self.server.invoke_successfully(volume_info, True)
1343 except netapp_utils.zapi.NaApiError as error:
1344 self.module.fail_json(msg='Error fetching volume %s : %s'
1345 % (self.parameters['name'], to_native(error)),
1346 exception=traceback.format_exc())
1347 return result
1348
1349 def get_application(self, template):
1350 if self.rest_app:
1351 app, error = self.rest_app.get_application_details(template=template)
1352 self.na_helper.fail_on_error(error)
1353 # flatten component list
1354 comps = self.na_helper.safe_get(app, [template, 'application_components'])
1355 if comps:
1356 comp = comps[0]
1357 app[template].pop('application_components')
1358 app[template].update(comp)
1359 return app[template]
1360 return None
1361
1362 def get_volume_attributes(self, volume_attributes, result):
1363 # extract values from volume record
1364 attrs = dict(
1365 # The keys are used to index a result dictionary, values are read from a ZAPI object indexed by key_list.
1366 # If required is True, an error is reported if a key in key_list is not found.
1367 # We may have observed cases where the record is incomplete as the volume is being created, so it may be better to ignore missing keys
1368 # I'm not sure there is much value in omitnone, but it preserves backward compatibility
1369 # If omitnone is absent or False, a None value is recorded, if True, the key is not set
1370 encrypt=dict(key_list=['encrypt'], convert_to=bool, omitnone=True),
1371 tiering_policy=dict(key_list=['volume-comp-aggr-attributes', 'tiering-policy'], omitnone=True),
1372 export_policy=dict(key_list=['volume-export-attributes', 'policy']),
1373 aggregate_name=dict(key_list=['volume-id-attributes', 'containing-aggregate-name']),
1374 flexgroup_uuid=dict(key_list=['volume-id-attributes', 'flexgroup-uuid']),
1375 instance_uuid=dict(key_list=['volume-id-attributes', 'instance-uuid']),
1376 junction_path=dict(key_list=['volume-id-attributes', 'junction-path'], default=''),
1377 style_extended=dict(key_list=['volume-id-attributes', 'style-extended']),
1378 type=dict(key_list=['volume-id-attributes', 'type'], omitnone=True),
1379 comment=dict(key_list=['volume-id-attributes', 'comment']),
1380 max_files=dict(key_list=['volume-inode-attributes', 'files-total'], convert_to=int),
1381 atime_update=dict(key_list=['volume-performance-attributes', 'is-atime-update-enabled'], convert_to=bool),
1382 qos_policy_group=dict(key_list=['volume-qos-attributes', 'policy-group-name']),
1383 qos_adaptive_policy_group=dict(key_list=['volume-qos-attributes', 'adaptive-policy-group-name']),
1384 # style is not present if the volume is still offline or of type: dp
1385 volume_security_style=dict(key_list=['volume-security-attributes', 'style'], omitnone=True),
1386 group_id=dict(key_list=['volume-security-attributes', 'volume-security-unix-attributes', 'group-id'], convert_to=int, omitnone=True),
1387 unix_permissions=dict(key_list=['volume-security-attributes', 'volume-security-unix-attributes', 'permissions'], required=True),
1388 user_id=dict(key_list=['volume-security-attributes', 'volume-security-unix-attributes', 'user-id'], convert_to=int, omitnone=True),
1389 snapdir_access=dict(key_list=['volume-snapshot-attributes', 'snapdir-access-enabled'], convert_to=bool),
1390 snapshot_policy=dict(key_list=['volume-snapshot-attributes', 'snapshot-policy'], omitnone=True),
1391 percent_snapshot_space=dict(key_list=['volume-space-attributes', 'percentage-snapshot-reserve'], convert_to=int, omitnone=True),
1392 size=dict(key_list=['volume-space-attributes', 'size'], convert_to=int),
1393 space_guarantee=dict(key_list=['volume-space-attributes', 'space-guarantee']),
1394 space_slo=dict(key_list=['volume-space-attributes', 'space-slo']),
1395 nvfail_enabled=dict(key_list=['volume-state-attributes', 'is-nvfail-enabled'], convert_to=bool),
1396 is_online=dict(key_list=['volume-state-attributes', 'state'], convert_to='bool_online', omitnone=True),
1397 vserver_dr_protection=dict(key_list=['volume-vserver-dr-protection-attributes', 'vserver-dr-protection']),
1398 )
1399
1400 self.na_helper.zapi_get_attrs(volume_attributes, attrs, result)
1401
1402 def get_snapshot_auto_delete_attributes(self, volume_attributes, result):
1403 attrs = dict(
1404 commitment=dict(key_list=['volume-snapshot-autodelete-attributes', 'commitment']),
1405 defer_delete=dict(key_list=['volume-snapshot-autodelete-attributes', 'defer-delete']),
1406 delete_order=dict(key_list=['volume-snapshot-autodelete-attributes', 'delete-order']),
1407 destroy_list=dict(key_list=['volume-snapshot-autodelete-attributes', 'destroy-list']),
1408 is_autodelete_enabled=dict(key_list=['volume-snapshot-autodelete-attributes', 'is-autodelete-enabled'], convert_to=bool),
1409 prefix=dict(key_list=['volume-snapshot-autodelete-attributes', 'prefix']),
1410 target_free_space=dict(key_list=['volume-snapshot-autodelete-attributes', 'target-free-space'], convert_to=int),
1411 trigger=dict(key_list=['volume-snapshot-autodelete-attributes', 'trigger']),
1412 )
1413 self.na_helper.zapi_get_attrs(volume_attributes, attrs, result)
1414 if result['is_autodelete_enabled'] is not None:
1415 result['state'] = 'on' if result['is_autodelete_enabled'] else 'off'
1416 del result['is_autodelete_enabled']
1417
1418 def get_volume(self, vol_name=None):
1419 """
1420 Return details about the volume
1421 :param:
1422 name : Name of the volume
1423 :return: Details about the volume. None if not found.
1424 :rtype: dict
1425 """
1426 result = None
1427 if vol_name is None:
1428 vol_name = self.parameters['name']
1429 if self.use_rest:
1430 return self.get_volume_rest(vol_name)
1431 volume_info = self.volume_get_iter(vol_name)
1432 if self.na_helper.zapi_get_value(volume_info, ['num-records'], convert_to=int, default=0) > 0:
1433 result = self.get_volume_record_from_zapi(volume_info, vol_name)
1434 return result
1435
1436 def get_volume_record_from_zapi(self, volume_info, vol_name):
1437 volume_attributes = self.na_helper.zapi_get_value(volume_info, ['attributes-list', 'volume-attributes'], required=True)
1438 result = dict(name=vol_name)
1439 self.get_volume_attributes(volume_attributes, result)
1440 result['uuid'] = (result['instance_uuid'] if result['style_extended'] == 'flexvol'
1441 else result['flexgroup_uuid'] if result['style_extended'] is not None and result['style_extended'].startswith('flexgroup')
1442 else None)
1443
1444 # snapshot_auto_delete options
1445 auto_delete = {}
1446 self. get_snapshot_auto_delete_attributes(volume_attributes, auto_delete)
1447 result['snapshot_auto_delete'] = auto_delete
1448
1449 self.get_efficiency_info(result)
1450
1451 return result
1452
1453 def wrap_fail_json(self, msg, exception=None):
1454 for issue in self.issues:
1455 self.module.warn(issue)
1456 if self.volume_created:
1457 msg = 'Volume created with success, with missing attributes: %s' % msg
1458 self.module.fail_json(msg=msg, exception=exception)
1459
1460 def create_nas_application_component(self):
1461 '''Create application component for nas template'''
1462 required_options = ('name', 'size')
1463 for option in required_options:
1464 if self.parameters.get(option) is None:
1465 self.module.fail_json(msg='Error: "%s" is required to create nas application.' % option)
1466
1467 application_component = dict(
1468 name=self.parameters['name'],
1469 total_size=self.parameters['size'],
1470 share_count=1, # 1 is the maximum value for nas
1471 scale_out=(self.volume_style == 'flexgroup'),
1472 )
1473 name = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'storage_service'])
1474 if name is not None:
1475 application_component['storage_service'] = dict(name=name)
1476
1477 flexcache = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'flexcache'])
1478 if flexcache is not None:
1479 application_component['flexcache'] = dict(
1480 origin=dict(
1481 svm=dict(name=flexcache['origin_svm_name']),
1482 component=dict(name=flexcache['origin_component_name'])
1483 )
1484 )
1485 # scale_out should be absent or set to True for FlexCache
1486 del application_component['scale_out']
1487 dr_cache = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'flexcache', 'dr_cache'])
1488 if dr_cache is not None:
1489 application_component['flexcache']['dr_cache'] = dr_cache
1490
1491 tiering = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'tiering'])
1492 if tiering is not None or self.parameters.get('tiering_policy') is not None:
1493 application_component['tiering'] = {}
1494 if tiering is None:
1495 tiering = {}
1496 if 'policy' not in tiering:
1497 tiering['policy'] = self.parameters.get('tiering_policy')
1498 for attr in ('control', 'policy', 'object_stores'):
1499 value = tiering.get(attr)
1500 if attr == 'object_stores' and value is not None:
1501 value = [dict(name=x) for x in value]
1502 if value is not None:
1503 application_component['tiering'][attr] = value
1504
1505 snapshot_locking_enabled = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'snapshot_locking_enabled'])
1506 if snapshot_locking_enabled is not None:
1507 application_component['snapshot_locking_enabled'] = snapshot_locking_enabled
1508
1509 snaplock = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'snaplock'])
1510 if snaplock is not None:
1511 value = self.na_helper.filter_out_none_entries(snaplock)
1512 if value:
1513 application_component['snaplock'] = value
1514
1515 if self.get_qos_policy_group() is not None:
1516 application_component['qos'] = {
1517 "policy": {
1518 "name": self.get_qos_policy_group(),
1519 }
1520 }
1521 if self.parameters.get('export_policy') is not None:
1522 application_component['export_policy'] = {
1523 "name": self.parameters['export_policy'],
1524 }
1525 return application_component
1526
1527 def create_volume_body(self):
1528 '''Create body for application template'''
1529 if self.parameters.get('nas_application_template') is not None:
1530 nas = dict(application_components=[self.create_nas_application_component()])
1531 value = self.na_helper.safe_get(self.parameters, ['snapshot_policy'])
1532 if value is not None:
1533 nas['protection_type'] = {'local_policy': value}
1534 for attr in ('nfs_access', 'cifs_access'):
1535 value = self.na_helper.safe_get(self.parameters, ['nas_application_template', attr])
1536 if value is not None:
1537 # we expect value to be a list of dicts, with maybe some empty entries
1538 value = self.na_helper.filter_out_none_entries(value)
1539 if value:
1540 nas[attr] = value
1541 for attr in ('exclude_aggregates',):
1542 values = self.na_helper.safe_get(self.parameters, ['nas_application_template', attr])
1543 if values:
1544 nas[attr] = [dict(name=name) for name in values]
1545 for attr in ('cifs_share_name',):
1546 value = self.na_helper.safe_get(self.parameters, ['nas_application_template', attr])
1547 if value is not None:
1548 nas[attr] = value
1549 return self.rest_app.create_application_body("nas", nas, smart_container=True)
1550
1551 def create_application_template(self):
1552 '''Use REST application/applications template to create a volume'''
1553 body, error = self.create_volume_body()
1554 self.na_helper.fail_on_error(error)
1555 response, error = self.rest_app.create_application(body)
1556 self.na_helper.fail_on_error(error)
1557 return response
1558
1559 def wait_for_volume_online(self, sleep_time=10):
1560 # round off time_out
1561 retries = (self.parameters['time_out'] + 5) // 10
1562 is_online = None
1563 errors = []
1564 while not is_online and retries > 0:
1565 try:
1566 current = self.get_volume()
1567 is_online = None if current is None else current['is_online']
1568 except KeyError as err:
1569 # get_volume may receive incomplete data as the volume is being created
1570 errors.append(repr(err))
1571 if not is_online:
1572 time.sleep(sleep_time)
1573 retries -= 1
1574 if not is_online:
1575 errors.append("Timeout after %s seconds" % self.parameters['time_out'])
1576 self.module.fail_json(msg='Error waiting for volume %s to come online: %s' % (self.parameters['name'], str(errors)))
1577
1578 def create_volume(self):
1579 '''Create ONTAP volume'''
1580 if self.rest_app:
1581 return self.create_application_template()
1582 if self.use_rest:
1583 return self.create_volume_rest()
1584 if self.volume_style == 'flexgroup':
1585 return self.create_volume_async()
1586
1587 options = self.create_volume_options()
1588 volume_create = netapp_utils.zapi.NaElement.create_node_with_children('volume-create', **options)
1589 try:
1590 self.server.invoke_successfully(volume_create, enable_tunneling=True)
1591 except netapp_utils.zapi.NaApiError as error:
1592 size_msg = ' of size %s' % self.parameters['size'] if self.parameters.get('size') is not None else ''
1593 self.module.fail_json(msg='Error provisioning volume %s%s: %s'
1594 % (self.parameters['name'], size_msg, to_native(error)),
1595 exception=traceback.format_exc())
1596
1597 if self.parameters.get('wait_for_completion'):
1598 self.wait_for_volume_online()
1599 return None
1600
1601 def create_volume_async(self):
1602 '''
1603 create volume async.
1604 '''
1605 options = self.create_volume_options()
1606 volume_create = netapp_utils.zapi.NaElement.create_node_with_children('volume-create-async', **options)
1607 if self.parameters.get('aggr_list'):
1608 aggr_list_obj = netapp_utils.zapi.NaElement('aggr-list')
1609 volume_create.add_child_elem(aggr_list_obj)
1610 for aggr in self.parameters['aggr_list']:
1611 aggr_list_obj.add_new_child('aggr-name', aggr)
1612 try:
1613 result = self.server.invoke_successfully(volume_create, enable_tunneling=True)
1614 except netapp_utils.zapi.NaApiError as error:
1615 size_msg = ' of size %s' % self.parameters['size'] if self.parameters.get('size') is not None else ''
1616 self.module.fail_json(msg='Error provisioning volume %s%s: %s'
1617 % (self.parameters['name'], size_msg, to_native(error)),
1618 exception=traceback.format_exc())
1619 self.check_invoke_result(result, 'create')
1620 return None
1621
1622 def create_volume_options(self):
1623 '''Set volume options for create operation'''
1624 options = {}
1625 if self.volume_style == 'flexgroup':
1626 options['volume-name'] = self.parameters['name']
1627 if self.parameters.get('aggr_list_multiplier') is not None:
1628 options['aggr-list-multiplier'] = str(self.parameters['aggr_list_multiplier'])
1629 if self.parameters.get('auto_provision_as') is not None:
1630 options['auto-provision-as'] = self.parameters['auto_provision_as']
1631 if self.parameters.get('space_guarantee') is not None:
1632 options['space-guarantee'] = self.parameters['space_guarantee']
1633 else:
1634 options['volume'] = self.parameters['name']
1635 if self.parameters.get('aggregate_name') is None:
1636 self.module.fail_json(msg='Error provisioning volume %s: aggregate_name is required'
1637 % self.parameters['name'])
1638 options['containing-aggr-name'] = self.parameters['aggregate_name']
1639 if self.parameters.get('space_guarantee') is not None:
1640 options['space-reserve'] = self.parameters['space_guarantee']
1641
1642 if self.parameters.get('size') is not None:
1643 options['size'] = str(self.parameters['size'])
1644 if self.parameters.get('snapshot_policy') is not None:
1645 options['snapshot-policy'] = self.parameters['snapshot_policy']
1646 if self.parameters.get('unix_permissions') is not None:
1647 options['unix-permissions'] = self.parameters['unix_permissions']
1648 if self.parameters.get('group_id') is not None:
1649 options['group-id'] = str(self.parameters['group_id'])
1650 if self.parameters.get('user_id') is not None:
1651 options['user-id'] = str(self.parameters['user_id'])
1652 if self.parameters.get('volume_security_style') is not None:
1653 options['volume-security-style'] = self.parameters['volume_security_style']
1654 if self.parameters.get('export_policy') is not None:
1655 options['export-policy'] = self.parameters['export_policy']
1656 if self.parameters.get('junction_path') is not None:
1657 options['junction-path'] = self.parameters['junction_path']
1658 if self.parameters.get('comment') is not None:
1659 options['volume-comment'] = self.parameters['comment']
1660 if self.parameters.get('type') is not None:
1661 options['volume-type'] = self.parameters['type']
1662 if self.parameters.get('percent_snapshot_space') is not None:
1663 options['percentage-snapshot-reserve'] = str(self.parameters['percent_snapshot_space'])
1664 if self.parameters.get('language') is not None:
1665 options['language-code'] = self.parameters['language']
1666 if self.parameters.get('qos_policy_group') is not None:
1667 options['qos-policy-group-name'] = self.parameters['qos_policy_group']
1668 if self.parameters.get('qos_adaptive_policy_group') is not None:
1669 options['qos-adaptive-policy-group-name'] = self.parameters['qos_adaptive_policy_group']
1670 if self.parameters.get('nvfail_enabled') is not None:
1671 options['is-nvfail-enabled'] = str(self.parameters['nvfail_enabled'])
1672 if self.parameters.get('space_slo') is not None:
1673 options['space-slo'] = self.parameters['space_slo']
1674 if self.parameters.get('tiering_policy') is not None:
1675 options['tiering-policy'] = self.parameters['tiering_policy']
1676 if self.parameters.get('encrypt') is not None:
1677 options['encrypt'] = self.na_helper.get_value_for_bool(False, self.parameters['encrypt'], 'encrypt')
1678 if self.parameters.get('vserver_dr_protection') is not None:
1679 options['vserver-dr-protection'] = self.parameters['vserver_dr_protection']
1680 if self.parameters['is_online']:
1681 options['volume-state'] = 'online'
1682 else:
1683 options['volume-state'] = 'offline'
1684 return options
1685
1686 def rest_delete_volume(self, current):
1687 """
1688 Delete the volume using REST DELETE method (it scrubs better than ZAPI).
1689 """
1690 uuid = self.parameters['uuid']
1691 if uuid is None:
1692 self.module.fail_json(msg='Could not read UUID for volume %s in delete.' % self.parameters['name'])
1693 unmount_error = self.volume_unmount_rest(fail_on_error=False) if current.get('junction_path') else None
1694 dummy, error = rest_generic.delete_async(self.rest_api, 'storage/volumes', uuid, job_timeout=self.parameters['time_out'])
1695 self.na_helper.fail_on_error(error, previous_errors=(['Error unmounting volume: %s' % unmount_error] if unmount_error else None))
1696 if unmount_error:
1697 self.module.warn('Volume was successfully deleted though unmount failed with: %s' % unmount_error)
1698
1699 def delete_volume_async(self, current):
1700 '''Delete ONTAP volume for infinite or flexgroup types '''
1701 errors = None
1702 if current['is_online']:
1703 dummy, errors = self.change_volume_state(call_from_delete_vol=True)
1704 volume_delete = netapp_utils.zapi.NaElement.create_node_with_children(
1705 'volume-destroy-async', **{'volume-name': self.parameters['name']})
1706 try:
1707 result = self.server.invoke_successfully(volume_delete, enable_tunneling=True)
1708 self.check_invoke_result(result, 'delete')
1709 except netapp_utils.zapi.NaApiError as error:
1710 msg = 'Error deleting volume %s: %s.' % (self.parameters['name'], to_native(error))
1711 if errors:
1712 msg += ' Previous errors when offlining/unmounting volume: %s' % ' - '.join(errors)
1713 self.module.fail_json(msg=msg)
1714
1715 def delete_volume_sync(self, current, unmount_offline):
1716 '''Delete ONTAP volume for flexvol types '''
1717 options = {'name': self.parameters['name']}
1718 if unmount_offline:
1719 options['unmount-and-offline'] = 'true'
1720 volume_delete = netapp_utils.zapi.NaElement.create_node_with_children(
1721 'volume-destroy', **options)
1722 try:
1723 self.server.invoke_successfully(volume_delete, enable_tunneling=True)
1724 except netapp_utils.zapi.NaApiError as error:
1725 return error
1726 return None
1727
1728 def delete_volume(self, current):
1729 '''Delete ONTAP volume'''
1730 if self.use_rest and self.parameters['uuid'] is not None:
1731 return self.rest_delete_volume(current)
1732 if self.parameters.get('is_infinite') or self.volume_style == 'flexgroup':
1733 return self.delete_volume_async(current)
1734 errors = []
1735 error = self.delete_volume_sync(current, True)
1736 if error:
1737 errors.append('volume delete failed with unmount-and-offline option: %s' % to_native(error))
1738 error = self.delete_volume_sync(current, False)
1739 if error:
1740 errors.append('volume delete failed without unmount-and-offline option: %s' % to_native(error))
1741 if errors:
1742 self.module.fail_json(msg='Error deleting volume %s: %s'
1743 % (self.parameters['name'], ' - '.join(errors)),
1744 exception=traceback.format_exc())
1745
1746 def move_volume(self, encrypt_destination=None):
1747 '''Move volume from source aggregate to destination aggregate'''
1748 if self.use_rest:
1749 return self.move_volume_rest(encrypt_destination)
1750 volume_move = netapp_utils.zapi.NaElement.create_node_with_children(
1751 'volume-move-start', **{'source-volume': self.parameters['name'],
1752 'vserver': self.parameters['vserver'],
1753 'dest-aggr': self.parameters['aggregate_name']})
1754 if self.parameters.get('cutover_action'):
1755 volume_move.add_new_child('cutover-action', self.parameters['cutover_action'])
1756 if encrypt_destination is not None:
1757 volume_move.add_new_child('encrypt-destination', self.na_helper.get_value_for_bool(False, encrypt_destination))
1758 try:
1759 self.cluster.invoke_successfully(volume_move,
1760 enable_tunneling=True)
1761 except netapp_utils.zapi.NaApiError as error:
1762 rest_error = self.move_volume_with_rest_passthrough(encrypt_destination)
1763 if rest_error is not None:
1764 self.module.fail_json(msg='Error moving volume %s: %s - Retry failed with REST error: %s'
1765 % (self.parameters['name'], to_native(error), rest_error),
1766 exception=traceback.format_exc())
1767 if self.parameters.get('wait_for_completion'):
1768 self.wait_for_volume_move()
1769
1770 def move_volume_with_rest_passthrough(self, encrypt_destination=None):
1771 # MDV volume will fail on a move, but will work using the REST CLI pass through
1772 # vol move start -volume MDV_CRS_d6b0b313ff5611e9837100a098544e51_A -destination-aggregate data_a3 -vserver wmc66-a
1773 # if REST isn't available fail with the original error
1774 if not self.use_rest:
1775 return False
1776 # if REST exists let's try moving using the passthrough CLI
1777 api = 'private/cli/volume/move/start'
1778 body = {'destination-aggregate': self.parameters['aggregate_name'],
1779 }
1780 if encrypt_destination is not None:
1781 body['encrypt-destination'] = encrypt_destination
1782 query = {'volume': self.parameters['name'],
1783 'vserver': self.parameters['vserver']
1784 }
1785 dummy, error = self.rest_api.patch(api, body, query)
1786 return error
1787
1788 def check_volume_move_state(self, result):
1789 if self.use_rest:
1790 volume_move_status = self.na_helper.safe_get(result, ['movement', 'state'])
1791 else:
1792 volume_move_status = result.get_child_by_name('attributes-list').get_child_by_name('volume-move-info').get_child_content('state')
1793 # We have 5 states that can be returned.
1794 # warning and healthy are state where the move is still going so we don't need to do anything for thouse.
1795 # success - volume move is completed in REST.
1796 if volume_move_status in ['success', 'done']:
1797 return False
1798 # ZAPI returns failed or alert, REST returns failed or aborted.
1799 if volume_move_status in ['failed', 'alert', 'aborted']:
1800 self.module.fail_json(msg='Error moving volume %s: %s' %
1801 (self.parameters['name'], result.get_child_by_name('attributes-list').get_child_by_name('volume-move-info')
1802 .get_child_content('details')))
1803 return True
1804
1805 def wait_for_volume_move(self):
1806 volume_move_iter = netapp_utils.zapi.NaElement('volume-move-get-iter')
1807 volume_move_info = netapp_utils.zapi.NaElement('volume-move-info')
1808 volume_move_info.add_new_child('volume', self.parameters['name'])
1809 query = netapp_utils.zapi.NaElement('query')
1810 query.add_child_elem(volume_move_info)
1811 volume_move_iter.add_child_elem(query)
1812 error = self.wait_for_task_completion(volume_move_iter, self.check_volume_move_state)
1813 if error:
1814 self.module.fail_json(msg='Error getting volume move status: %s' % (to_native(error)),
1815 exception=traceback.format_exc())
1816
1817 def wait_for_volume_move_rest(self):
1818 api = "storage/volumes"
1819 query = {
1820 'name': self.parameters['name'],
1821 'movement.destination_aggregate.name': self.parameters['aggregate_name'],
1822 'fields': 'movement.state'
1823 }
1824 error = self.wait_for_task_completion_rest(api, query, self.check_volume_move_state)
1825 if error:
1826 self.module.fail_json(msg='Error getting volume move status: %s' % (to_native(error)),
1827 exception=traceback.format_exc())
1828
1829 def check_volume_encryption_conversion_state(self, result):
1830 if self.use_rest:
1831 volume_encryption_conversion_status = self.na_helper.safe_get(result, ['encryption', 'status', 'message'])
1832 else:
1833 volume_encryption_conversion_status = result.get_child_by_name('attributes-list').get_child_by_name('volume-encryption-conversion-info')\
1834 .get_child_content('status')
1835 # REST returns running or initializing, ZAPI returns running if encryption in progress.
1836 if volume_encryption_conversion_status in ['running', 'initializing']:
1837 return True
1838 # If encryprion is completed, REST do have encryption status message.
1839 if volume_encryption_conversion_status in ['Not currently going on.', None]:
1840 return False
1841 self.module.fail_json(msg='Error converting encryption for volume %s: %s' %
1842 (self.parameters['name'], volume_encryption_conversion_status))
1843
1844 def wait_for_volume_encryption_conversion(self):
1845 if self.use_rest:
1846 return self.wait_for_volume_encryption_conversion_rest()
1847 volume_encryption_conversion_iter = netapp_utils.zapi.NaElement('volume-encryption-conversion-get-iter')
1848 volume_encryption_conversion_info = netapp_utils.zapi.NaElement('volume-encryption-conversion-info')
1849 volume_encryption_conversion_info.add_new_child('volume', self.parameters['name'])
1850 volume_encryption_conversion_info.add_new_child('vserver', self.parameters['vserver'])
1851 query = netapp_utils.zapi.NaElement('query')
1852 query.add_child_elem(volume_encryption_conversion_info)
1853 volume_encryption_conversion_iter.add_child_elem(query)
1854 error = self.wait_for_task_completion(volume_encryption_conversion_iter, self.check_volume_encryption_conversion_state)
1855 if error:
1856 self.module.fail_json(msg='Error getting volume encryption_conversion status: %s' % (to_native(error)),
1857 exception=traceback.format_exc())
1858
1859 def wait_for_volume_encryption_conversion_rest(self):
1860 api = "storage/volumes"
1861 query = {
1862 'name': self.parameters['name'],
1863 'fields': 'encryption'
1864 }
1865 error = self.wait_for_task_completion_rest(api, query, self.check_volume_encryption_conversion_state)
1866 if error:
1867 self.module.fail_json(msg='Error getting volume encryption_conversion status: %s' % (to_native(error)),
1868 exception=traceback.format_exc())
1869
1870 def wait_for_task_completion(self, zapi_iter, check_state):
1871 retries = self.parameters['max_wait_time'] // (self.parameters['check_interval'] + 1)
1872 fail_count = 0
1873 while retries > 0:
1874 try:
1875 result = self.cluster.invoke_successfully(zapi_iter, enable_tunneling=True)
1876 except netapp_utils.zapi.NaApiError as error:
1877 if fail_count < 3:
1878 fail_count += 1
1879 retries -= 1
1880 time.sleep(self.parameters['check_interval'])
1881 continue
1882 return error
1883 if int(result.get_child_content('num-records')) == 0:
1884 return None
1885 # reset fail count to 0
1886 fail_count = 0
1887 retry_required = check_state(result)
1888 if not retry_required:
1889 return None
1890 time.sleep(self.parameters['check_interval'])
1891 retries -= 1
1892
1893 def wait_for_task_completion_rest(self, api, query, check_state):
1894 retries = self.parameters['max_wait_time'] // (self.parameters['check_interval'] + 1)
1895 fail_count = 0
1896 while retries > 0:
1897 record, error = rest_generic.get_one_record(self.rest_api, api, query)
1898 if error:
1899 if fail_count < 3:
1900 fail_count += 1
1901 retries -= 1
1902 time.sleep(self.parameters['check_interval'])
1903 continue
1904 return error
1905 if record is None:
1906 return None
1907 # reset fail count to 0
1908 fail_count = 0
1909 retry_required = check_state(record)
1910 if not retry_required:
1911 return None
1912 time.sleep(self.parameters['check_interval'])
1913 retries -= 1
1914
1915 def rename_volume(self):
1916 """
1917 Rename the volume.
1918
1919 Note: 'is_infinite' needs to be set to True in order to rename an
1920 Infinite Volume. Use time_out parameter to set wait time for rename completion.
1921 """
1922 if self.use_rest:
1923 return self.rename_volume_rest()
1924 vol_rename_zapi, vol_name_zapi = ['volume-rename-async', 'volume-name'] if self.parameters['is_infinite']\
1925 else ['volume-rename', 'volume']
1926 volume_rename = netapp_utils.zapi.NaElement.create_node_with_children(
1927 vol_rename_zapi, **{vol_name_zapi: self.parameters['from_name'],
1928 'new-volume-name': str(self.parameters['name'])})
1929 try:
1930 result = self.server.invoke_successfully(volume_rename, enable_tunneling=True)
1931 if vol_rename_zapi == 'volume-rename-async':
1932 self.check_invoke_result(result, 'rename')
1933 except netapp_utils.zapi.NaApiError as error:
1934 self.module.fail_json(msg='Error renaming volume %s: %s'
1935 % (self.parameters['name'], to_native(error)),
1936 exception=traceback.format_exc())
1937
1938 def resize_volume(self):
1939 """
1940 Re-size the volume.
1941
1942 Note: 'is_infinite' needs to be set to True in order to resize an
1943 Infinite Volume.
1944 """
1945 if self.use_rest:
1946 return self.resize_volume_rest()
1947
1948 vol_size_zapi, vol_name_zapi = ['volume-size-async', 'volume-name']\
1949 if (self.parameters['is_infinite'] or self.volume_style == 'flexgroup')\
1950 else ['volume-size', 'volume']
1951 volume_resize = netapp_utils.zapi.NaElement.create_node_with_children(
1952 vol_size_zapi, **{vol_name_zapi: self.parameters['name'],
1953 'new-size': str(self.parameters['size'])})
1954 try:
1955 result = self.server.invoke_successfully(volume_resize, enable_tunneling=True)
1956 if vol_size_zapi == 'volume-size-async':
1957 self.check_invoke_result(result, 'resize')
1958 except netapp_utils.zapi.NaApiError as error:
1959 self.module.fail_json(msg='Error re-sizing volume %s: %s'
1960 % (self.parameters['name'], to_native(error)),
1961 exception=traceback.format_exc())
1962 return None
1963
1964 def start_encryption_conversion(self, encrypt_destination):
1965 if encrypt_destination:
1966 if self.use_rest:
1967 return self.encryption_conversion_rest()
1968 zapi = netapp_utils.zapi.NaElement.create_node_with_children(
1969 'volume-encryption-conversion-start', **{'volume': self.parameters['name']})
1970 try:
1971 self.server.invoke_successfully(zapi, enable_tunneling=True)
1972 except netapp_utils.zapi.NaApiError as error:
1973 self.module.fail_json(msg='Error enabling encryption for volume %s: %s'
1974 % (self.parameters['name'], to_native(error)),
1975 exception=traceback.format_exc())
1976 if self.parameters.get('wait_for_completion'):
1977 self.wait_for_volume_encryption_conversion()
1978 else:
1979 self.module.warn('disabling encryption requires cluster admin permissions.')
1980 self.move_volume(encrypt_destination)
1981
1982 def change_volume_state(self, call_from_delete_vol=False):
1983 """
1984 Change volume's state (offline/online).
1985 """
1986 if self.use_rest:
1987 return self.change_volume_state_rest()
1988 if self.parameters['is_online'] and not call_from_delete_vol: # Desired state is online, setup zapi APIs respectively
1989 vol_state_zapi, vol_name_zapi, action = ['volume-online-async', 'volume-name', 'online']\
1990 if (self.parameters['is_infinite'] or self.volume_style == 'flexgroup')\
1991 else ['volume-online', 'name', 'online']
1992 else: # Desired state is offline, setup zapi APIs respectively
1993 vol_state_zapi, vol_name_zapi, action = ['volume-offline-async', 'volume-name', 'offline']\
1994 if (self.parameters['is_infinite'] or self.volume_style == 'flexgroup')\
1995 else ['volume-offline', 'name', 'offline']
1996 volume_unmount = netapp_utils.zapi.NaElement.create_node_with_children(
1997 'volume-unmount', **{'volume-name': self.parameters['name']})
1998 volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
1999 vol_state_zapi, **{vol_name_zapi: self.parameters['name']})
2000
2001 errors = []
2002 if not self.parameters['is_online'] or call_from_delete_vol: # Unmount before offline
2003 try:
2004 self.server.invoke_successfully(volume_unmount, enable_tunneling=True)
2005 except netapp_utils.zapi.NaApiError as error:
2006 errors.append('Error unmounting volume %s: %s' % (self.parameters['name'], to_native(error)))
2007 state = "online" if self.parameters['is_online'] and not call_from_delete_vol else "offline"
2008 try:
2009 result = self.server.invoke_successfully(volume_change_state, enable_tunneling=True)
2010 if self.volume_style == 'flexgroup' or self.parameters['is_infinite']:
2011 self.check_invoke_result(result, action)
2012 except netapp_utils.zapi.NaApiError as error:
2013 errors.append('Error changing the state of volume %s to %s: %s' % (self.parameters['name'], state, to_native(error)))
2014 if errors and not call_from_delete_vol:
2015 self.module.fail_json(msg=', '.join(errors), exception=traceback.format_exc())
2016 return state, errors
2017
2018 def create_volume_attribute(self, zapi_object, parent_attribute, attribute, option_name, convert_from=None):
2019 """
2020
2021 :param parent_attribute:
2022 :param child_attribute:
2023 :param value:
2024 :return:
2025 """
2026 value = self.parameters.get(option_name)
2027 if value is None:
2028 return
2029 if convert_from == int:
2030 value = str(value)
2031 elif convert_from == bool:
2032 value = self.na_helper.get_value_for_bool(False, value, option_name)
2033
2034 if zapi_object is None:
2035 parent_attribute.add_new_child(attribute, value)
2036 return
2037 if isinstance(zapi_object, str):
2038 # retrieve existing in parent, or create a new one
2039 element = parent_attribute.get_child_by_name(zapi_object)
2040 zapi_object = netapp_utils.zapi.NaElement(zapi_object) if element is None else element
2041 zapi_object.add_new_child(attribute, value)
2042 parent_attribute.add_child_elem(zapi_object)
2043
2044 def build_zapi_volume_modify_iter(self, params):
2045 vol_mod_iter = netapp_utils.zapi.NaElement('volume-modify-iter-async' if self.volume_style == 'flexgroup' or self.parameters['is_infinite']
2046 else 'volume-modify-iter')
2047
2048 attributes = netapp_utils.zapi.NaElement('attributes')
2049 vol_mod_attributes = netapp_utils.zapi.NaElement('volume-attributes')
2050 # Volume-attributes is split in to 25 sub categories
2051 # volume-inode-attributes
2052 vol_inode_attributes = netapp_utils.zapi.NaElement('volume-inode-attributes')
2053 self.create_volume_attribute(vol_inode_attributes, vol_mod_attributes, 'files-total', 'max_files', int)
2054 # volume-space-attributes
2055 vol_space_attributes = netapp_utils.zapi.NaElement('volume-space-attributes')
2056 self.create_volume_attribute(vol_space_attributes, vol_mod_attributes, 'space-guarantee', 'space_guarantee')
2057 self.create_volume_attribute(vol_space_attributes, vol_mod_attributes, 'percentage-snapshot-reserve', 'percent_snapshot_space', int)
2058 self.create_volume_attribute(vol_space_attributes, vol_mod_attributes, 'space-slo', 'space_slo')
2059 # volume-snapshot-attributes
2060 vol_snapshot_attributes = netapp_utils.zapi.NaElement('volume-snapshot-attributes')
2061 self.create_volume_attribute(vol_snapshot_attributes, vol_mod_attributes, 'snapshot-policy', 'snapshot_policy')
2062 self.create_volume_attribute(vol_snapshot_attributes, vol_mod_attributes, 'snapdir-access-enabled', 'snapdir_access', bool)
2063 # volume-export-attributes
2064 self.create_volume_attribute('volume-export-attributes', vol_mod_attributes, 'policy', 'export_policy')
2065 # volume-security-attributes
2066 if self.parameters.get('unix_permissions') is not None or self.parameters.get('group_id') is not None or self.parameters.get('user_id') is not None:
2067 vol_security_attributes = netapp_utils.zapi.NaElement('volume-security-attributes')
2068 vol_security_unix_attributes = netapp_utils.zapi.NaElement('volume-security-unix-attributes')
2069 self.create_volume_attribute(vol_security_unix_attributes, vol_security_attributes, 'permissions', 'unix_permissions')
2070 self.create_volume_attribute(vol_security_unix_attributes, vol_security_attributes, 'group-id', 'group_id', int)
2071 self.create_volume_attribute(vol_security_unix_attributes, vol_security_attributes, 'user-id', 'user_id', int)
2072 vol_mod_attributes.add_child_elem(vol_security_attributes)
2073 if params and params.get('volume_security_style') is not None:
2074 self.create_volume_attribute('volume-security-attributes', vol_mod_attributes, 'style', 'volume_security_style')
2075
2076 # volume-performance-attributes
2077 self.create_volume_attribute('volume-performance-attributes', vol_mod_attributes, 'is-atime-update-enabled', 'atime_update', bool)
2078 # volume-qos-attributes
2079 self.create_volume_attribute('volume-qos-attributes', vol_mod_attributes, 'policy-group-name', 'qos_policy_group')
2080 self.create_volume_attribute('volume-qos-attributes', vol_mod_attributes, 'adaptive-policy-group-name', 'qos_adaptive_policy_group')
2081 # volume-comp-aggr-attributes
2082 if params and params.get('tiering_policy') is not None:
2083 self.create_volume_attribute('volume-comp-aggr-attributes', vol_mod_attributes, 'tiering-policy', 'tiering_policy')
2084 # volume-state-attributes
2085 self.create_volume_attribute('volume-state-attributes', vol_mod_attributes, 'is-nvfail-enabled', 'nvfail_enabled', bool)
2086 # volume-dr-protection-attributes
2087 self.create_volume_attribute('volume-vserver-dr-protection-attributes', vol_mod_attributes, 'vserver-dr-protection', 'vserver_dr_protection')
2088 # volume-id-attributes
2089 self.create_volume_attribute('volume-id-attributes', vol_mod_attributes, 'comment', 'comment')
2090 # End of Volume-attributes sub attributes
2091 attributes.add_child_elem(vol_mod_attributes)
2092
2093 query = netapp_utils.zapi.NaElement('query')
2094 vol_query_attributes = netapp_utils.zapi.NaElement('volume-attributes')
2095 self.create_volume_attribute('volume-id-attributes', vol_query_attributes, 'name', 'name')
2096 query.add_child_elem(vol_query_attributes)
2097 vol_mod_iter.add_child_elem(attributes)
2098 vol_mod_iter.add_child_elem(query)
2099 return vol_mod_iter
2100
2101 def volume_modify_attributes(self, params):
2102 """
2103 modify volume parameter 'export_policy','unix_permissions','snapshot_policy','space_guarantee', 'percent_snapshot_space',
2104 'qos_policy_group', 'qos_adaptive_policy_group'
2105 """
2106 if self.use_rest:
2107 return self.volume_modify_attributes_rest(params)
2108 vol_mod_iter = self.build_zapi_volume_modify_iter(params)
2109 try:
2110 result = self.server.invoke_successfully(vol_mod_iter, enable_tunneling=True)
2111 except netapp_utils.zapi.NaApiError as error:
2112 error_msg = to_native(error)
2113 if 'volume-comp-aggr-attributes' in error_msg:
2114 error_msg += ". Added info: tiering option requires 9.4 or later."
2115 self.wrap_fail_json(msg='Error modifying volume %s: %s'
2116 % (self.parameters['name'], error_msg),
2117 exception=traceback.format_exc())
2118
2119 failures = result.get_child_by_name('failure-list')
2120 # handle error if modify space, policy, or unix-permissions parameter fails
2121 if failures is not None:
2122 error_msgs = [
2123 failures.get_child_by_name(return_info).get_child_content(
2124 'error-message'
2125 )
2126 for return_info in (
2127 'volume-modify-iter-info',
2128 'volume-modify-iter-async-info',
2129 )
2130 if failures.get_child_by_name(return_info) is not None
2131 ]
2132 if error_msgs and any(x is not None for x in error_msgs):
2133 self.wrap_fail_json(msg="Error modifying volume %s: %s"
2134 % (self.parameters['name'], ' --- '.join(error_msgs)),
2135 exception=traceback.format_exc())
2136 if self.volume_style == 'flexgroup' or self.parameters['is_infinite']:
2137 success = self.na_helper.safe_get(result, ['success-list', 'volume-modify-iter-async-info'])
2138 results = {}
2139 for key in ('status', 'jobid'):
2140 if success and success.get_child_by_name(key):
2141 results[key] = success[key]
2142
2143 status = results.get('status')
2144 if status == 'in_progress' and 'jobid' in results:
2145 if self.parameters['time_out'] == 0:
2146 return
2147 error = self.check_job_status(results['jobid'])
2148 if error is None:
2149 return
2150 self.wrap_fail_json(msg='Error when modifying volume: %s' % error)
2151 self.wrap_fail_json(msg='Unexpected error when modifying volume: result is: %s' % str(result.to_string()))
2152
2153 def volume_mount(self):
2154 """
2155 Mount an existing volume in specified junction_path
2156 :return: None
2157 """
2158 if self.use_rest:
2159 return self.volume_mount_rest()
2160 vol_mount = netapp_utils.zapi.NaElement('volume-mount')
2161 vol_mount.add_new_child('volume-name', self.parameters['name'])
2162 vol_mount.add_new_child('junction-path', self.parameters['junction_path'])
2163 try:
2164 self.server.invoke_successfully(vol_mount, enable_tunneling=True)
2165 except netapp_utils.zapi.NaApiError as error:
2166 self.module.fail_json(msg='Error mounting volume %s on path %s: %s'
2167 % (self.parameters['name'], self.parameters['junction_path'],
2168 to_native(error)), exception=traceback.format_exc())
2169
2170 def volume_unmount(self):
2171 """
2172 Unmount an existing volume
2173 :return: None
2174 """
2175 if self.use_rest:
2176 return self.volume_unmount_rest()
2177 vol_unmount = netapp_utils.zapi.NaElement.create_node_with_children(
2178 'volume-unmount', **{'volume-name': self.parameters['name']})
2179 try:
2180 self.server.invoke_successfully(vol_unmount, enable_tunneling=True)
2181 except netapp_utils.zapi.NaApiError as error:
2182 self.module.fail_json(msg='Error unmounting volume %s: %s'
2183 % (self.parameters['name'], to_native(error)), exception=traceback.format_exc())
2184
2185 def modify_volume(self, modify):
2186 '''Modify volume action'''
2187 # snaplock requires volume in unmount state.
2188 if modify.get('junction_path') == '':
2189 self.volume_unmount()
2190 attributes = modify.keys()
2191 for attribute in attributes:
2192 if attribute in ['space_guarantee', 'export_policy', 'unix_permissions', 'group_id', 'user_id', 'tiering_policy', 'tiering_object_tags',
2193 'snapshot_policy', 'percent_snapshot_space', 'snapdir_access', 'atime_update', 'volume_security_style',
2194 'nvfail_enabled', 'space_slo', 'qos_policy_group', 'qos_adaptive_policy_group', 'vserver_dr_protection',
2195 'comment', 'logical_space_enforcement', 'logical_space_reporting', 'tiering_minimum_cooling_days',
2196 'snaplock', 'max_files', 'analytics', 'activity_tracking', 'tags', 'snapshot_auto_delete',
2197 'vol_nearly_full_threshold_percent', 'vol_full_threshold_percent', 'large_size_enabled', 'snapshot_locking',
2198 'granular_data', 'anti_ransomware']:
2199 self.volume_modify_attributes(modify)
2200 break
2201 if 'snapshot_auto_delete' in attributes and not self.use_rest:
2202 # Rest didn't support snapshot_auto_delete prior to ONTAP 9.13.1; for supported ONTAP versions,
2203 # modification for this parameter is handled by calling volume_modify_attributes function.
2204 self.set_snapshot_auto_delete()
2205 # don't mount or unmount when offline
2206 if modify.get('junction_path'):
2207 self.volume_mount()
2208 if 'size' in attributes:
2209 self.resize_volume()
2210 if 'aggregate_name' in attributes:
2211 # keep it last, as it may take some time
2212 # handle change in encryption as part of the move
2213 # allow for encrypt/decrypt only if encrypt present in attributes.
2214 self.move_volume(modify.get('encrypt'))
2215 elif 'encrypt' in attributes:
2216 self.start_encryption_conversion(self.parameters['encrypt'])
2217
2218 def get_volume_style(self, current):
2219 '''Get volume style, infinite or standard flexvol'''
2220 if current is not None:
2221 return current.get('style_extended')
2222 if self.parameters.get('aggr_list') or self.parameters.get('aggr_list_multiplier') or self.parameters.get('auto_provision_as'):
2223 if self.use_rest and self.parameters.get('auto_provision_as') and self.parameters.get('aggr_list_multiplier') is None:
2224 self.parameters['aggr_list_multiplier'] = 1
2225 return 'flexgroup'
2226 return None
2227
2228 def get_job(self, jobid, server):
2229 """
2230 Get job details by id
2231 """
2232 job_get = netapp_utils.zapi.NaElement('job-get')
2233 job_get.add_new_child('job-id', jobid)
2234 try:
2235 result = server.invoke_successfully(job_get, enable_tunneling=True)
2236 except netapp_utils.zapi.NaApiError as error:
2237 if to_native(error.code) == "15661":
2238 # Not found
2239 return None
2240 self.wrap_fail_json(msg='Error fetching job info: %s' % to_native(error),
2241 exception=traceback.format_exc())
2242 job_info = result.get_child_by_name('attributes').get_child_by_name('job-info')
2243 return {
2244 'job-progress': job_info['job-progress'],
2245 'job-state': job_info['job-state'],
2246 'job-completion': job_info['job-completion'] if job_info.get_child_by_name('job-completion') is not None else None
2247 }
2248
2249 def check_job_status(self, jobid):
2250 """
2251 Loop until job is complete
2252 """
2253 server = self.server
2254 sleep_time = 5
2255 time_out = self.parameters['time_out']
2256 error = 'timeout'
2257
2258 if time_out <= 0:
2259 results = self.get_job(jobid, server)
2260
2261 while time_out > 0:
2262 results = self.get_job(jobid, server)
2263 # If running as cluster admin, the job is owned by cluster vserver
2264 # rather than the target vserver.
2265 if results is None and server == self.server:
2266 results = netapp_utils.get_cserver(self.server)
2267 server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results)
2268 continue
2269 if results is None:
2270 error = 'cannot locate job with id: %d' % int(jobid)
2271 break
2272 if results['job-state'] in ('queued', 'running'):
2273 time.sleep(sleep_time)
2274 time_out -= sleep_time
2275 continue
2276 if results['job-state'] in ('success', 'failure'):
2277 break
2278 else:
2279 self.wrap_fail_json(msg='Unexpected job status in: %s' % repr(results))
2280
2281 if results is not None:
2282 if results['job-state'] == 'success':
2283 error = None
2284 elif results['job-state'] in ('queued', 'running'):
2285 error = 'job completion exceeded expected timer of: %s seconds' % \
2286 self.parameters['time_out']
2287 elif results['job-completion'] is not None:
2288 error = results['job-completion']
2289 else:
2290 error = results['job-progress']
2291 return error
2292
2293 def check_invoke_result(self, result, action):
2294 '''
2295 check invoked api call back result.
2296 '''
2297 results = {}
2298 for key in ('result-status', 'result-jobid'):
2299 if result.get_child_by_name(key):
2300 results[key] = result[key]
2301
2302 status = results.get('result-status')
2303 if status == 'in_progress' and 'result-jobid' in results:
2304 if self.parameters['time_out'] == 0:
2305 return
2306 error = self.check_job_status(results['result-jobid'])
2307 if error is None:
2308 return
2309 else:
2310 self.wrap_fail_json(msg='Error when %s volume: %s' % (action, error))
2311 if status == 'failed':
2312 self.wrap_fail_json(msg='Operation failed when %s volume.' % action)
2313
2314 def set_efficiency_attributes(self, options):
2315 for key, attr in self.sis_keys2zapi_set.items():
2316 value = self.parameters.get(key)
2317 if value is not None:
2318 if self.argument_spec[key]['type'] == 'bool':
2319 value = self.na_helper.get_value_for_bool(False, value)
2320 options[attr] = value
2321 # ZAPI requires compression to be set for inline-compression
2322 if options.get('enable-inline-compression') == 'true' and 'enable-compression' not in options:
2323 options['enable-compression'] = 'true'
2324
2325 def set_efficiency_config(self):
2326 '''Set efficiency policy and compression attributes'''
2327 options = {'path': '/vol/' + self.parameters['name']}
2328 efficiency_enable = netapp_utils.zapi.NaElement.create_node_with_children('sis-enable', **options)
2329 try:
2330 self.server.invoke_successfully(efficiency_enable, enable_tunneling=True)
2331 except netapp_utils.zapi.NaApiError as error:
2332 # Error 40043 denotes an Operation has already been enabled.
2333 if to_native(error.code) != "40043":
2334 self.wrap_fail_json(msg='Error enable efficiency on volume %s: %s'
2335 % (self.parameters['name'], to_native(error)),
2336 exception=traceback.format_exc())
2337
2338 self.set_efficiency_attributes(options)
2339 efficiency_start = netapp_utils.zapi.NaElement.create_node_with_children('sis-set-config', **options)
2340 try:
2341 self.server.invoke_successfully(efficiency_start, enable_tunneling=True)
2342 except netapp_utils.zapi.NaApiError as error:
2343 self.wrap_fail_json(msg='Error setting up efficiency attributes on volume %s: %s'
2344 % (self.parameters['name'], to_native(error)),
2345 exception=traceback.format_exc())
2346
2347 def set_efficiency_config_async(self):
2348 """Set efficiency policy and compression attributes in asynchronous mode"""
2349 options = {'volume-name': self.parameters['name']}
2350 efficiency_enable = netapp_utils.zapi.NaElement.create_node_with_children('sis-enable-async', **options)
2351 try:
2352 result = self.server.invoke_successfully(efficiency_enable, enable_tunneling=True)
2353 except netapp_utils.zapi.NaApiError as error:
2354 self.wrap_fail_json(msg='Error enable efficiency on volume %s: %s'
2355 % (self.parameters['name'], to_native(error)),
2356 exception=traceback.format_exc())
2357 self.check_invoke_result(result, 'enable efficiency on')
2358
2359 self.set_efficiency_attributes(options)
2360 efficiency_start = netapp_utils.zapi.NaElement.create_node_with_children('sis-set-config-async', **options)
2361 try:
2362 result = self.server.invoke_successfully(efficiency_start, enable_tunneling=True)
2363 except netapp_utils.zapi.NaApiError as error:
2364 self.wrap_fail_json(msg='Error setting up efficiency attributes on volume %s: %s'
2365 % (self.parameters['name'], to_native(error)),
2366 exception=traceback.format_exc())
2367 self.check_invoke_result(result, 'set efficiency policy on')
2368
2369 def get_efficiency_info(self, return_value):
2370 """
2371 get the name of the efficiency policy assigned to volume, as well as compression values
2372 if attribute does not exist, set its value to None
2373 :return: update return_value dict.
2374 """
2375 sis_info = netapp_utils.zapi.NaElement('sis-get-iter')
2376 sis_status_info = netapp_utils.zapi.NaElement('sis-status-info')
2377 sis_status_info.add_new_child('path', '/vol/' + self.parameters['name'])
2378 query = netapp_utils.zapi.NaElement('query')
2379 query.add_child_elem(sis_status_info)
2380 sis_info.add_child_elem(query)
2381 try:
2382 result = self.server.invoke_successfully(sis_info, True)
2383 except netapp_utils.zapi.NaApiError as error:
2384 # Don't error out if efficiency settings cannot be read. We'll fail if they need to be set.
2385 if error.message.startswith('Insufficient privileges: user ') and error.message.endswith(' does not have read access to this resource'):
2386 self.issues.append('cannot read volume efficiency options (as expected when running as vserver): %s' % to_native(error))
2387 return
2388 self.wrap_fail_json(msg='Error fetching efficiency policy for volume %s: %s'
2389 % (self.parameters['name'], to_native(error)),
2390 exception=traceback.format_exc())
2391 for key in self.sis_keys2zapi_get:
2392 return_value[key] = None
2393 if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
2394 sis_attributes = result.get_child_by_name('attributes-list'). get_child_by_name('sis-status-info')
2395 for key, attr in self.sis_keys2zapi_get.items():
2396 value = sis_attributes.get_child_content(attr)
2397 if self.argument_spec[key]['type'] == 'bool':
2398 value = self.na_helper.get_value_for_bool(True, value)
2399 return_value[key] = value
2400
2401 def modify_volume_efficiency_config(self, efficiency_config_modify_value):
2402 if self.use_rest:
2403 return self.set_efficiency_rest()
2404 if efficiency_config_modify_value == 'async':
2405 self.set_efficiency_config_async()
2406 else:
2407 self.set_efficiency_config()
2408
2409 def set_snapshot_auto_delete(self):
2410 options = {'volume': self.parameters['name']}
2411 desired_options = self.parameters['snapshot_auto_delete']
2412 for key, value in desired_options.items():
2413 options['option-name'] = key
2414 options['option-value'] = str(value)
2415 snapshot_auto_delete = netapp_utils.zapi.NaElement.create_node_with_children('snapshot-autodelete-set-option', **options)
2416 try:
2417 self.server.invoke_successfully(snapshot_auto_delete, enable_tunneling=True)
2418 except netapp_utils.zapi.NaApiError as error:
2419 self.wrap_fail_json(msg='Error setting snapshot auto delete options for volume %s: %s'
2420 % (self.parameters['name'], to_native(error)),
2421 exception=traceback.format_exc())
2422
2423 def rehost_volume(self):
2424 volume_rehost = netapp_utils.zapi.NaElement.create_node_with_children(
2425 'volume-rehost', **{'vserver': self.parameters['from_vserver'],
2426 'destination-vserver': self.parameters['vserver'],
2427 'volume': self.parameters['name']})
2428 if self.parameters.get('auto_remap_luns') is not None:
2429 volume_rehost.add_new_child('auto-remap-luns', str(self.parameters['auto_remap_luns']))
2430 if self.parameters.get('force_unmap_luns') is not None:
2431 volume_rehost.add_new_child('force-unmap-luns', str(self.parameters['force_unmap_luns']))
2432 try:
2433 self.cluster.invoke_successfully(volume_rehost, enable_tunneling=True)
2434 except netapp_utils.zapi.NaApiError as error:
2435 self.module.fail_json(msg='Error rehosting volume %s: %s'
2436 % (self.parameters['name'], to_native(error)),
2437 exception=traceback.format_exc())
2438
2439 def snapshot_restore_volume(self):
2440 if self.use_rest:
2441 return self.snapshot_restore_volume_rest()
2442 snapshot_restore = netapp_utils.zapi.NaElement.create_node_with_children(
2443 'snapshot-restore-volume', **{'snapshot': self.parameters['snapshot_restore'],
2444 'volume': self.parameters['name']})
2445 if self.parameters.get('force_restore') is not None:
2446 snapshot_restore.add_new_child('force', str(self.parameters['force_restore']))
2447 if self.parameters.get('preserve_lun_ids') is not None:
2448 snapshot_restore.add_new_child('preserve-lun-ids', str(self.parameters['preserve_lun_ids']))
2449 try:
2450 self.server.invoke_successfully(snapshot_restore, enable_tunneling=True)
2451 except netapp_utils.zapi.NaApiError as error:
2452 self.module.fail_json(msg='Error restoring volume %s: %s'
2453 % (self.parameters['name'], to_native(error)),
2454 exception=traceback.format_exc())
2455
2456 def ignore_small_change(self, current, attribute, threshold):
2457 if attribute in current and current[attribute] != 0 and self.parameters.get(attribute) is not None:
2458 # ignore a less than XX% difference
2459 change = abs(current[attribute] - self.parameters[attribute]) * 100.0 / current[attribute]
2460 if change < threshold:
2461 self.parameters[attribute] = current[attribute]
2462 if change > 0.1:
2463 self.module.warn('resize request for %s ignored: %.1f%% is below the threshold: %.1f%%' % (attribute, change, threshold))
2464
2465 def adjust_sizes(self, current, after_create):
2466 """
2467 ignore small change in size by resetting expectations
2468 """
2469 if after_create:
2470 # For NAS application templates, apply size threshold logic instead of blindly accepting current size
2471 if self.parameters.get('nas_application_template') is not None:
2472 # Check if size change is within threshold for NAS templates
2473 if current.get('size') and self.parameters.get('size'):
2474 change = abs(current['size'] - self.parameters['size']) * 100.0 / current['size']
2475 threshold = self.parameters.get('size_change_threshold', 10)
2476
2477 if change < threshold:
2478 # Size difference is within threshold - update parameters for idempotency
2479 original_size = self.parameters['size']
2480 self.parameters['size'] = current['size']
2481 self.module.warn('NAS template overhead detected: volume size adjusted from %s to %s (%.1f%% difference, below %.1f%% threshold)'
2482 % (original_size, current['size'], change, threshold))
2483 # If change >= threshold, keep original size to trigger a resize operation
2484 else:
2485 # For regular volumes (non-NAS templates), ignore change in size immediately after create
2486 self.parameters['size'] = current['size']
2487 # inodes are not set in create
2488 return
2489 self.ignore_small_change(current, 'size', self.parameters['size_change_threshold'])
2490 self.ignore_small_change(current, 'max_files', netapp_utils.get_feature(self.module, 'max_files_change_threshold'))
2491
2492 def validate_snaplock_changes(self, current, modify=None, after_create=False):
2493 if not self.use_rest:
2494 return
2495 msg = None
2496 if modify:
2497 # prechecks when computing modify
2498 if 'type' in modify['snaplock']:
2499 msg = "Error: volume snaplock type was not set properly at creation time." if after_create else \
2500 "Error: changing a volume snaplock type after creation is not allowed."
2501 msg += ' Current: %s, desired: %s.' % (current['snaplock']['type'], self.parameters['snaplock']['type'])
2502 elif self.parameters['state'] == 'present':
2503 # prechecks before computing modify
2504 sl_dict = self.na_helper.filter_out_none_entries(self.parameters.get('snaplock', {}))
2505 sl_type = sl_dict.pop('type', 'non_snaplock')
2506 # verify type is the only option when not enabling snaplock compliance or enterprise
2507 if sl_dict and (
2508 (current is None and sl_type == 'non_snaplock') or (current and current['snaplock']['type'] == 'non_snaplock')):
2509 msg = "Error: snaplock options are not supported for non_snaplock volume, found: %s." % sl_dict
2510 # verify type is not used before 9.10.1, or allow non_snaplock as this is the default
2511 if not self.rest_api.meets_rest_minimum_version(True, 9, 10, 1):
2512 if sl_type == 'non_snaplock':
2513 self.parameters.pop('snaplock', None)
2514 else:
2515 msg = "Error: %s" % self.rest_api.options_require_ontap_version('snaplock type', '9.10.1', True)
2516 if msg:
2517 self.module.fail_json(msg=msg)
2518
2519 def set_modify_dict(self, current, after_create=False):
2520 '''Fill modify dict with changes'''
2521 octal_value = current.get('unix_permissions') if current else None
2522 if self.parameters.get('unix_permissions') is not None and self.na_helper.compare_chmod_value(octal_value, self.parameters['unix_permissions']):
2523 # don't change if the values are the same
2524 # can't change permissions if not online
2525 del self.parameters['unix_permissions']
2526 # snapshot_auto_delete's value is a dict, get_modified_attributes function doesn't support dict as value.
2527 auto_delete_info = current.pop('snapshot_auto_delete', None)
2528 anti_ransomware_info = current.pop('anti_ransomware', None)
2529 # ignore small changes in volume size or inode maximum by adjusting self.parameters['size'] or self.parameters['max_files']
2530 self.adjust_sizes(current, after_create)
2531 if 'type' in self.parameters:
2532 self.parameters['type'] = self.parameters['type'].lower()
2533 modify = self.na_helper.get_modified_attributes(current, self.parameters)
2534 if modify is not None and 'type' in modify:
2535 msg = "Error: volume type was not set properly at creation time." if after_create else \
2536 "Error: changing a volume from one type to another is not allowed."
2537 msg += ' Current: %s, desired: %s.' % (current['type'], self.parameters['type'])
2538 self.module.fail_json(msg=msg)
2539 if modify is not None and 'snaplock' in modify:
2540 self.validate_snaplock_changes(current, modify, after_create)
2541 desired_style = self.get_volume_style(None)
2542 if desired_style is not None and desired_style != self.volume_style:
2543 msg = "Error: volume backend was not set properly at creation time." if after_create else \
2544 "Error: changing a volume from one backend to another is not allowed."
2545 msg += ' Current: %s, desired: %s.' % (self.volume_style, desired_style)
2546 self.module.fail_json(msg=msg)
2547 desired_tcontrol = self.na_helper.safe_get(self.parameters, ['nas_application_template', 'tiering', 'control'])
2548 if desired_tcontrol in ('required', 'disallowed'):
2549 warn_or_fail = netapp_utils.get_feature(self.module, 'warn_or_fail_on_fabricpool_backend_change')
2550 if warn_or_fail in ('warn', 'fail'):
2551 current_tcontrol = self.tiering_control(current)
2552 if desired_tcontrol != current_tcontrol:
2553 msg = "Error: volume tiering control was not set properly at creation time." if after_create else \
2554 "Error: changing a volume from one backend to another is not allowed."
2555 msg += ' Current tiering control: %s, desired: %s.' % (current_tcontrol, desired_tcontrol)
2556 if warn_or_fail == 'fail':
2557 self.module.fail_json(msg=msg)
2558 self.module.warn("Ignored " + msg)
2559 elif warn_or_fail not in (None, 'ignore'):
2560 self.module.warn("Unexpected value '%s' for warn_or_fail_on_fabricpool_backend_change, expecting: None, 'ignore', 'fail', 'warn'"
2561 % warn_or_fail)
2562 if self.parameters.get('snapshot_auto_delete') is not None:
2563 auto_delete_modify = self.na_helper.get_modified_attributes(auto_delete_info,
2564 self.parameters['snapshot_auto_delete'])
2565 if len(auto_delete_modify) > 0:
2566 modify['snapshot_auto_delete'] = auto_delete_modify
2567 if self.parameters.get('anti_ransomware') is not None:
2568 anti_ransomware_modify = self.na_helper.get_modified_attributes(anti_ransomware_info,
2569 self.parameters['anti_ransomware'])
2570 if self.na_helper.safe_get(self.parameters, ['anti_ransomware', 'state']) is not None:
2571 if anti_ransomware_modify.get('state') is not None:
2572 anti_ransomware_modify['state'] = None
2573 if self.set_anti_ransomware_state(anti_ransomware_info) is not None:
2574 anti_ransomware_modify.update({'state': self.set_anti_ransomware_state(anti_ransomware_info)})
2575 if len(self.na_helper.filter_out_none_entries(anti_ransomware_modify)) > 0:
2576 modify['anti_ransomware'] = self.na_helper.filter_out_none_entries(anti_ransomware_modify)
2577 return modify
2578
2579 def take_modify_actions(self, modify):
2580 self.modify_volume(modify)
2581
2582 if any(modify.get(key) is not None for key in self.sis_keys2zapi_get):
2583 if self.parameters.get('is_infinite') or self.volume_style == 'flexgroup':
2584 efficiency_config_modify = 'async'
2585 else:
2586 efficiency_config_modify = 'sync'
2587 self.modify_volume_efficiency_config(efficiency_config_modify)
2588
2589 # offline volume last
2590 if modify.get('is_online') is False:
2591 self.change_volume_state()
2592
2593 """ MAPPING OF VOLUME FIELDS FROM ZAPI TO REST
2594 ZAPI = REST
2595 encrypt = encryption.enabled
2596 volume-comp-aggr-attributes.tiering-policy = tiering.policy
2597 'volume-export-attributes.policy' = nas.export_policy.name
2598 'volume-id-attributes.containing-aggregate-name' = aggregates.name
2599 'volume-id-attributes.flexgroup-uuid' = uuid (Only for FlexGroup volumes)
2600 'volume-id-attributes.instance-uuid' = uuid (Only for FlexVols)
2601 'volume-id-attributes.junction-path' = nas.path
2602 'volume-id-attributes.style-extended' = style
2603 'volume-id-attributes.type' = type
2604 'volume-id-attributes.comment' = comment
2605 'volume-performance-attributes.is-atime-update-enabled' == NO REST VERSION
2606 volume-qos-attributes.policy-group-name' = qos.policy.name
2607 'volume-qos-attributes.adaptive-policy-group-name' = qos.policy.name
2608 'volume-security-attributes.style = nas.security_style
2609 volume-security-attributes.volume-security-unix-attributes.group-id' = nas.gid
2610 'volume-security-attributes.volume-security-unix-attributes.permissions' = nas.unix_permissions
2611 'volume-security-attributes.volume-security-unix-attributes.user-id' = nas.uid
2612 'volume-snapshot-attributes.snapdir-access-enabled' == NO REST VERSION
2613 'volume-snapshot-attributes,snapshot-policy' = snapshot_policy
2614 volume-space-attributes.percentage-snapshot-reserve = space.snapshot.reserve_percent
2615 volume-space-attributes.size' = space.size
2616 'volume-space-attributes.space-guarantee' = guarantee.type
2617 volume-space-attributes.space-slo' == NO REST VERSION
2618 'volume-state-attributes.is-nvfail-enabled' == NO REST Version
2619 'volume-state-attributes.state' = state
2620 'volume-vserver-dr-protection-attributes.vserver-dr-protection' = == NO REST Version
2621 volume-snapshot-autodelete-attributes.* None exist other than space.snapshot.autodelete_enabled
2622 From get_efficiency_info function
2623 efficiency_policy = efficiency.policy.name
2624 compression = efficiency.compression
2625 inline_compression = efficiency.compression
2626 """
2627
2628 def get_volume_rest(self, vol_name):
2629 """
2630 This covers the zapi functions
2631 get_volume
2632 - volume_get_iter
2633 - get_efficiency_info
2634 """
2635 api = 'storage/volumes'
2636 params = {'name': vol_name,
2637 'svm.name': self.parameters['vserver'],
2638 'fields': 'encryption.enabled,'
2639 'tiering.policy,'
2640 'tiering.object_tags,'
2641 'nas.export_policy.name,'
2642 'aggregates.name,'
2643 'aggregates.uuid,'
2644 'uuid,'
2645 'nas.path,'
2646 'style,'
2647 'type,'
2648 'comment,'
2649 'qos.policy.name,'
2650 'nas.security_style,'
2651 'nas.gid,'
2652 'nas.unix_permissions,'
2653 'nas.uid,'
2654 'snapshot_policy,'
2655 'space.snapshot.reserve_percent,'
2656 'space.size,'
2657 'guarantee.type,'
2658 'state,'
2659 'efficiency.compression,'
2660 'snaplock,'
2661 'files.maximum,'
2662 'space.logical_space.enforcement,'
2663 'space.logical_space.reporting,'}
2664 if self.parameters.get('efficiency_policy'):
2665 params['fields'] += 'efficiency.policy.name,'
2666 if self.parameters.get('tiering_minimum_cooling_days'):
2667 params['fields'] += 'tiering.min_cooling_days,'
2668 if self.parameters.get('analytics'):
2669 params['fields'] += 'analytics,'
2670 if self.parameters.get('activity_tracking'):
2671 params['fields'] += 'activity_tracking,'
2672 if self.parameters.get('tags'):
2673 params['fields'] += '_tags,'
2674 if self.parameters.get('atime_update') is not None:
2675 params['fields'] += 'access_time_enabled,'
2676 if self.parameters.get('snapdir_access') is not None:
2677 params['fields'] += 'snapshot_directory_access_enabled,'
2678 if self.parameters.get('snapshot_auto_delete') is not None:
2679 params['fields'] += 'space.snapshot.autodelete,'
2680 if self.parameters.get('vol_nearly_full_threshold_percent') is not None:
2681 params['fields'] += 'space.nearly_full_threshold_percent,'
2682 if self.parameters.get('vol_full_threshold_percent') is not None:
2683 params['fields'] += 'space.full_threshold_percent,'
2684 if self.parameters.get('large_size_enabled') is not None:
2685 params['fields'] += 'space.large_size_enabled,'
2686 if self.parameters.get('snapshot_locking') is not None:
2687 params['fields'] += 'snapshot_locking_enabled,'
2688 if self.parameters.get('granular_data') is not None:
2689 params['fields'] += 'granular_data,'
2690 if self.parameters.get('anti_ransomware') is not None:
2691 params['fields'] += 'anti_ransomware,'
2692
2693 record, error = rest_generic.get_one_record(self.rest_api, api, params)
2694 if error:
2695 self.module.fail_json(msg=error)
2696 return self.format_get_volume_rest(record) if record else None
2697
2698 def rename_volume_rest(self):
2699 # volume-rename-async and volume-rename are the same in rest
2700 # Zapi you had to give the old and new name to change a volume.
2701 # Rest you need the old UUID, and the new name only
2702 current = self.get_volume_rest(self.parameters['from_name'])
2703 body = {
2704 'name': self.parameters['name']
2705 }
2706 dummy, error = self.volume_rest_patch(body, uuid=current['uuid'])
2707 if error:
2708 self.module.fail_json(msg='Error changing name of volume %s: %s' % (self.parameters['name'], to_native(error)),
2709 exception=traceback.format_exc())
2710
2711 def snapshot_restore_volume_rest(self):
2712 # Rest does not have force_restore or preserve_lun_id
2713 current = self.get_volume()
2714 self.parameters['uuid'] = current['uuid']
2715 body = {
2716 'restore_to.snapshot.name': self.parameters['snapshot_restore']
2717 }
2718 dummy, error = self.volume_rest_patch(body)
2719 if error:
2720 self.module.fail_json(msg='Error restoring snapshot %s in volume %s: %s' % (
2721 self.parameters['snapshot_restore'],
2722 self.parameters['name'],
2723 to_native(error)), exception=traceback.format_exc())
2724
2725 def create_volume_rest(self):
2726 body = self.create_volume_body_rest()
2727 dummy, error = rest_generic.post_async(self.rest_api, 'storage/volumes', body, job_timeout=self.parameters['time_out'])
2728 if error:
2729 self.module.fail_json(msg='Error creating volume %s: %s' % (self.parameters['name'], to_native(error)),
2730 exception=traceback.format_exc())
2731 if self.parameters.get('wait_for_completion'):
2732 self.wait_for_volume_online(sleep_time=5)
2733
2734 def create_volume_body_rest(self):
2735 body = {
2736 'name': self.parameters['name'],
2737 'svm.name': self.parameters['vserver']
2738 }
2739 # Zapi's Space-guarantee and space-reserve are the same thing in Rest
2740 if self.parameters.get('space_guarantee') is not None:
2741 body['guarantee.type'] = self.parameters['space_guarantee']
2742 # TODO: Check to see if there a difference in rest between flexgroup or not. might need to throw error
2743 body = self.aggregates_rest(body)
2744 if self.parameters.get('tags') is not None:
2745 body['_tags'] = self.parameters['tags']
2746 if self.parameters.get('size') is not None:
2747 body['size'] = self.parameters['size']
2748 if self.parameters.get('snapshot_policy') is not None:
2749 body['snapshot_policy.name'] = self.parameters['snapshot_policy']
2750 if self.parameters.get('unix_permissions') is not None:
2751 body['nas.unix_permissions'] = self.parameters['unix_permissions']
2752 if self.parameters.get('group_id') is not None:
2753 body['nas.gid'] = self.parameters['group_id']
2754 if self.parameters.get('user_id') is not None:
2755 body['nas.uid'] = self.parameters['user_id']
2756 if self.parameters.get('volume_security_style') is not None:
2757 body['nas.security_style'] = self.parameters['volume_security_style']
2758 if self.parameters.get('export_policy') is not None:
2759 body['nas.export_policy.name'] = self.parameters['export_policy']
2760 if self.parameters.get('junction_path') is not None:
2761 body['nas.path'] = self.parameters['junction_path']
2762 if self.parameters.get('comment') is not None:
2763 body['comment'] = self.parameters['comment']
2764 if self.parameters.get('type') is not None:
2765 body['type'] = self.parameters['type'].lower()
2766 if self.parameters.get('percent_snapshot_space') is not None:
2767 body['space.snapshot.reserve_percent'] = self.parameters['percent_snapshot_space']
2768 if self.parameters.get('language') is not None:
2769 body['language'] = self.parameters['language']
2770 if self.get_qos_policy_group() is not None:
2771 body['qos.policy.name'] = self.get_qos_policy_group()
2772 if self.parameters.get('tiering_policy') is not None:
2773 body['tiering.policy'] = self.parameters['tiering_policy']
2774 if self.parameters.get('tiering_object_tags') is not None:
2775 body['tiering.object_tags'] = self.parameters['tiering_object_tags']
2776 if self.parameters.get('encrypt') is not None:
2777 body['encryption.enabled'] = self.parameters['encrypt']
2778 if self.parameters.get('logical_space_enforcement') is not None:
2779 body['space.logical_space.enforcement'] = self.parameters['logical_space_enforcement']
2780 if self.parameters.get('logical_space_reporting') is not None:
2781 body['space.logical_space.reporting'] = self.parameters['logical_space_reporting']
2782 if self.parameters.get('tiering_minimum_cooling_days') is not None:
2783 body['tiering.min_cooling_days'] = self.parameters['tiering_minimum_cooling_days']
2784 if self.parameters.get('snaplock') is not None:
2785 body['snaplock'] = self.na_helper.filter_out_none_entries(self.parameters['snaplock'])
2786 if self.volume_style:
2787 body['style'] = self.volume_style
2788 if self.parameters.get('efficiency_policy') is not None:
2789 body['efficiency.policy.name'] = self.parameters['efficiency_policy']
2790 if self.get_compression():
2791 body['efficiency.compression'] = self.get_compression()
2792 if self.parameters.get('analytics'):
2793 body['analytics.state'] = self.parameters['analytics']
2794 if self.parameters.get('activity_tracking'):
2795 body['activity_tracking.state'] = self.parameters['activity_tracking']
2796 if self.parameters.get('anti_ransomware') is not None:
2797 body['anti_ransomware'] = self.na_helper.filter_out_none_entries(self.parameters['anti_ransomware'])
2798 body['state'] = self.bool_to_online(self.parameters['is_online'])
2799 return body
2800
2801 def aggregates_rest(self, body):
2802 if self.parameters.get('aggregate_name') is not None:
2803 body['aggregates'] = [{'name': self.parameters['aggregate_name']}]
2804 if self.parameters.get('aggr_list') is not None:
2805 body['aggregates'] = [{'name': name} for name in self.parameters['aggr_list']]
2806 if self.parameters.get('aggr_list_multiplier') is not None:
2807 body['constituents_per_aggregate'] = self.parameters['aggr_list_multiplier']
2808 return body
2809
2810 def volume_modify_attributes_rest(self, params):
2811 body = self.modify_volume_body_rest(params)
2812 dummy, error = self.volume_rest_patch(body)
2813 if error:
2814 self.module.fail_json(msg='Error modifying volume %s: %s' % (self.parameters['name'], to_native(error)),
2815 exception=traceback.format_exc())
2816
2817 @staticmethod
2818 def bool_to_online(item):
2819 return 'online' if item else 'offline'
2820
2821 @staticmethod
2822 def enabled_to_bool(item, reverse=False):
2823 """ convertes on/off to true/false or vice versa """
2824 if reverse:
2825 return 'on' if item else 'off'
2826 return True if item == 'on' else False
2827
2828 def modify_volume_body_rest(self, params):
2829 body = {}
2830 for key, option, transform in [
2831 ('analytics.state', 'analytics', None),
2832 ('activity_tracking.state', 'activity_tracking', None),
2833 ('guarantee.type', 'space_guarantee', None),
2834 ('space.snapshot.reserve_percent', 'percent_snapshot_space', None),
2835 ('snapshot_policy.name', 'snapshot_policy', None),
2836 ('nas.export_policy.name', 'export_policy', None),
2837 ('nas.unix_permissions', 'unix_permissions', None),
2838 ('nas.gid', 'group_id', None),
2839 ('nas.uid', 'user_id', None),
2840 # only one of these 2 options for QOS policy can be defined at most
2841 ('qos.policy.name', 'qos_policy_group', None),
2842 ('qos.policy.name', 'qos_adaptive_policy_group', None),
2843 ('comment', 'comment', None),
2844 ('space.logical_space.enforcement', 'logical_space_enforcement', None),
2845 ('space.logical_space.reporting', 'logical_space_reporting', None),
2846 ('tiering.min_cooling_days', 'tiering_minimum_cooling_days', None),
2847 ('state', 'is_online', self.bool_to_online),
2848 ('_tags', 'tags', None),
2849 ('snapshot_directory_access_enabled', 'snapdir_access', None),
2850 ('access_time_enabled', 'atime_update', None),
2851 ('space.nearly_full_threshold_percent', 'vol_nearly_full_threshold_percent', None),
2852 ('space.full_threshold_percent', 'vol_full_threshold_percent', None),
2853 ('space.large_size_enabled', 'large_size_enabled', None),
2854 ('snapshot_locking_enabled', 'snapshot_locking', None),
2855 ('granular_data', 'granular_data', None),
2856 ]:
2857 value = self.parameters.get(option)
2858 if value is not None and transform:
2859 value = transform(value)
2860 if value is not None:
2861 body[key] = value
2862
2863 # not too sure why we don't always set them
2864 # one good reason are fields that are not supported on all releases
2865 for key, option, transform in [
2866 ('nas.security_style', 'volume_security_style', None),
2867 ('tiering.policy', 'tiering_policy', None),
2868 ('tiering.object_tags', 'tiering_object_tags', None),
2869 ('files.maximum', 'max_files', None),
2870 ]:
2871 if params and params.get(option) is not None:
2872 body[key] = self.parameters[option]
2873
2874 if params and params.get('snaplock') is not None:
2875 sl_dict = self.na_helper.filter_out_none_entries(self.parameters['snaplock']) or {}
2876 # type is not allowed in patch, and we already prevented any change in type
2877 sl_dict.pop('type', None)
2878 if sl_dict:
2879 body['snaplock'] = sl_dict
2880
2881 if params and params.get('snapshot_auto_delete') is not None:
2882 for key, option, transform in [
2883 ('space.snapshot.autodelete.trigger', 'trigger', None),
2884 ('space.snapshot.autodelete.target_free_space', 'target_free_space', None),
2885 ('space.snapshot.autodelete.delete_order', 'delete_order', None),
2886 ('space.snapshot.autodelete.commitment', 'commitment', None),
2887 ('space.snapshot.autodelete.defer_delete', 'defer_delete', None),
2888 ('space.snapshot.autodelete.prefix', 'prefix', None),
2889 ('space.snapshot.autodelete.enabled', 'state', self.enabled_to_bool),
2890 ]:
2891 if params and params['snapshot_auto_delete'].get(option) is not None:
2892 if transform:
2893 body[key] = transform(self.parameters['snapshot_auto_delete'][option])
2894 else:
2895 body[key] = self.parameters['snapshot_auto_delete'][option]
2896
2897 if params and params.get('anti_ransomware') is not None:
2898 ar_dict = self.na_helper.filter_out_none_entries(params['anti_ransomware']) or {}
2899 if ar_dict:
2900 body['anti_ransomware'] = ar_dict
2901 return body
2902
2903 def set_anti_ransomware_state(self, current_info):
2904 ''' validates the anti-ransomware state modify value '''
2905 current_state = current_info.get('state')
2906 desired_state = self.na_helper.safe_get(self.parameters, ['anti_ransomware', 'state'])
2907 if current_state != desired_state:
2908 if current_state == 'enable_paused' and desired_state == 'paused':
2909 self.module.warn('Anti-ransomware is already paused on the volume; currently in enable_paused state.')
2910 return
2911 elif current_state == 'enabled' and desired_state == 'dry_run':
2912 return
2913 elif current_state == 'disable_in_progress' and desired_state == 'disabled':
2914 self.module.warn('Anti-ransomware monitoring is being disabled and a cleanup operation is in effect; currently in disable_in_progress state.')
2915 return
2916 else:
2917 return desired_state
2918 return
2919
2920 def change_volume_state_rest(self):
2921 body = {
2922 'state': self.bool_to_online(self.parameters['is_online']),
2923 }
2924 dummy, error = self.volume_rest_patch(body)
2925 if error:
2926 self.module.fail_json(msg='Error changing state of volume %s: %s' % (self.parameters['name'],
2927 to_native(error)),
2928 exception=traceback.format_exc())
2929 return body['state'], None
2930
2931 def volume_unmount_rest(self, fail_on_error=True):
2932 body = {
2933 'nas.path': '',
2934 }
2935 dummy, error = self.volume_rest_patch(body)
2936 if error and fail_on_error:
2937 self.module.fail_json(msg='Error unmounting volume %s with path "%s": %s' % (self.parameters['name'],
2938 self.parameters.get('junction_path'),
2939 to_native(error)),
2940 exception=traceback.format_exc())
2941 return error
2942
2943 def volume_mount_rest(self):
2944 body = {
2945 'nas.path': self.parameters['junction_path']
2946 }
2947 dummy, error = self.volume_rest_patch(body)
2948 if error:
2949 self.module.fail_json(msg='Error mounting volume %s with path "%s": %s' % (self.parameters['name'],
2950 self.parameters['junction_path'],
2951 to_native(error)),
2952 exception=traceback.format_exc())
2953
2954 def set_efficiency_rest(self):
2955 body = {}
2956 if self.parameters.get('efficiency_policy') is not None:
2957 body['efficiency.policy.name'] = self.parameters['efficiency_policy']
2958 if self.get_compression():
2959 body['efficiency.compression'] = self.get_compression()
2960 if not body:
2961 return
2962 dummy, error = self.volume_rest_patch(body)
2963 if error:
2964 if "Failed to modify efficiency configuration for volume" in error and "Operation is not enabled" in error \
2965 and "'code': '6881332'" in error:
2966 self.module.fail_json(msg=('You are trying to set the efficiency configuration for the volume, where efficiency is disabled. '
2967 'Please refer to module na_ontap_volume_efficiency to enable efficiency on the volume first.'))
2968 self.module.fail_json(msg='Error setting efficiency for volume %s: %s' % (self.parameters['name'], to_native(error)),
2969 exception=traceback.format_exc())
2970
2971 def encryption_conversion_rest(self):
2972 # volume-encryption-conversion-start
2973 # Set the "encryption.enabled" field to "true" to start the encryption conversion operation.
2974 body = {
2975 'encryption.enabled': True
2976 }
2977 dummy, error = self.volume_rest_patch(body)
2978 if error:
2979 self.module.fail_json(msg='Error enabling encryption for volume %s: %s' % (self.parameters['name'],
2980 to_native(error)),
2981 exception=traceback.format_exc())
2982 if self.parameters.get('wait_for_completion'):
2983 self.wait_for_volume_encryption_conversion_rest()
2984
2985 def resize_volume_rest(self):
2986 query = None
2987 if self.parameters.get('sizing_method') is not None:
2988 query = dict(sizing_method=self.parameters['sizing_method'])
2989 body = {
2990 'size': self.parameters['size']
2991 }
2992 dummy, error = self.volume_rest_patch(body, query)
2993 if error:
2994 self.module.fail_json(msg='Error resizing volume %s: %s' % (self.parameters['name'], to_native(error)),
2995 exception=traceback.format_exc())
2996
2997 def move_volume_rest(self, encrypt_destination):
2998 body = {
2999 'movement.destination_aggregate.name': self.parameters['aggregate_name'],
3000 }
3001 if encrypt_destination is not None:
3002 body['encryption.enabled'] = encrypt_destination
3003 dummy, error = self.volume_rest_patch(body)
3004 if error:
3005 self.module.fail_json(msg='Error moving volume %s: %s' % (self.parameters['name'], to_native(error)),
3006 exception=traceback.format_exc())
3007 if self.parameters.get('wait_for_completion'):
3008 self.wait_for_volume_move_rest()
3009
3010 def volume_rest_patch(self, body, query=None, uuid=None):
3011 if not uuid:
3012 uuid = self.parameters['uuid']
3013 if not uuid:
3014 self.module.fail_json(msg='Could not read UUID for volume %s in patch.' % self.parameters['name'])
3015 return rest_generic.patch_async(self.rest_api, 'storage/volumes', uuid, body, query=query, job_timeout=self.parameters['time_out'])
3016
3017 def get_qos_policy_group(self):
3018 if self.parameters.get('qos_policy_group') is not None:
3019 return self.parameters['qos_policy_group']
3020 if self.parameters.get('qos_adaptive_policy_group') is not None:
3021 return self.parameters['qos_adaptive_policy_group']
3022 return None
3023
3024 def get_compression(self):
3025 if self.parameters.get('compression') and self.parameters.get('inline_compression'):
3026 return 'both'
3027 if self.parameters.get('compression'):
3028 return 'background'
3029 if self.parameters.get('inline_compression'):
3030 return 'inline'
3031 if self.parameters.get('compression') is False and self.parameters.get('inline_compression') is False:
3032 return 'none'
3033 return None
3034
3035 def rest_errors(self):
3036 # For variable that have been merged together we should fail before we do anything
3037 if self.parameters.get('qos_policy_group') and self.parameters.get('qos_adaptive_policy_group'):
3038 self.module.fail_json(msg='Error: With Rest API qos_policy_group and qos_adaptive_policy_group are now '
3039 'the same thing, and cannot be set at the same time')
3040
3041 ontap_97_options = ['nas_application_template']
3042 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 7) and any(x in self.parameters for x in ontap_97_options):
3043 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version(ontap_97_options, version='9.7'))
3044
3045 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 9) and\
3046 self.na_helper.safe_get(self.parameters, ['nas_application_template', 'flexcache', 'dr_cache']) is not None:
3047 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version('flexcache: dr_cache', version='9.9'))
3048 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 11) and\
3049 self.na_helper.safe_get(self.parameters, ['nas_application_template', 'cifs_share_name']) is not None:
3050 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version('nas_application_template: cifs_share_name', version='9.11'))
3051 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 12) and\
3052 self.na_helper.safe_get(self.parameters, ['nas_application_template', 'snaplock']) is not None:
3053 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version('nas_application_template: snaplock', version='9.12'))
3054 if not self.rest_api.meets_rest_minimum_version(self.use_rest, 9, 13, 1) and\
3055 self.na_helper.safe_get(self.parameters, ['nas_application_template', 'snapshot_locking_enabled']) is not None:
3056 self.module.fail_json(msg='Error: %s' % self.rest_api.options_require_ontap_version('nas_application_template: \
3057 snapshot_locking_enabled', version='9.13.1'))
3058
3059 if self.na_helper.safe_get(self.parameters, ['nas_application_template', 'cifs_share_name']) is not None and\
3060 self.na_helper.safe_get(self.parameters, ['nas_application_template', 'cifs_access']) is None:
3061 self.module.fail_json(msg='Must provide CIFS access information when providing CIFS share name.')
3062
3063 if 'snapshot_auto_delete' in self.parameters:
3064 if 'destroy_list' in self.parameters['snapshot_auto_delete']:
3065 self.module.fail_json(msg="snapshot_auto_delete option 'destroy_list' is currently not supported with REST.")
3066
3067 def format_get_volume_rest(self, record):
3068 is_online = record.get('state') == 'online'
3069 # TODO FIX THIS!!!! ZAPI would only return a single aggr, REST can return more than 1.
3070 # For now i'm going to hard code this, but we need a way to show all aggrs
3071 aggregates = record.get('aggregates', None)
3072 aggr_name = aggregates[0].get('name', None) if aggregates else None
3073 rest_compression = self.na_helper.safe_get(record, ['efficiency', 'compression'])
3074 junction_path = self.na_helper.safe_get(record, ['nas', 'path'])
3075 if junction_path is None:
3076 junction_path = ''
3077 # if analytics.state is initializing it will be ON once completed.
3078 state = self.na_helper.safe_get(record, ['analytics', 'state'])
3079 analytics = 'on' if state == 'initializing' else state
3080 auto_delete_info = self.na_helper.safe_get(record, ['space', 'snapshot', 'autodelete'])
3081 if auto_delete_info is not None:
3082 auto_delete_info['state'] = self.enabled_to_bool(self.na_helper.safe_get(record, ['space', 'snapshot', 'autodelete', 'enabled']), reverse=True)
3083 del auto_delete_info['enabled']
3084 return {
3085 'tags': record.get('_tags', []),
3086 'name': record.get('name', None),
3087 'analytics': analytics,
3088 'activity_tracking': self.na_helper.safe_get(record, ['activity_tracking', 'state']),
3089 'anti_ransomware': self.na_helper.safe_get(record, ['anti_ransomware']),
3090 'encrypt': self.na_helper.safe_get(record, ['encryption', 'enabled']),
3091 'tiering_policy': self.na_helper.safe_get(record, ['tiering', 'policy']),
3092 'tiering_object_tags': self.na_helper.safe_get(record, ['tiering', 'object_tags']),
3093 'export_policy': self.na_helper.safe_get(record, ['nas', 'export_policy', 'name']),
3094 'aggregate_name': aggr_name,
3095 'aggregates': aggregates,
3096 'flexgroup_uuid': record.get('uuid', None), # this might need some additional logic
3097 'instance_uuid': record.get('uuid', None), # this might need some additional logic
3098 'junction_path': junction_path,
3099 'style_extended': record.get('style', None),
3100 'type': record.get('type', None),
3101 'comment': record.get('comment', None),
3102 'qos_policy_group': self.na_helper.safe_get(record, ['qos', 'policy', 'name']),
3103 'qos_adaptive_policy_group': self.na_helper.safe_get(record, ['qos', 'policy', 'name']),
3104 'volume_security_style': self.na_helper.safe_get(record, ['nas', 'security_style']),
3105 'group_id': self.na_helper.safe_get(record, ['nas', 'gid']),
3106 # Rest return an Int while Zapi return a string, force Rest to be an String
3107 'unix_permissions': str(self.na_helper.safe_get(record, ['nas', 'unix_permissions'])),
3108 'user_id': self.na_helper.safe_get(record, ['nas', 'uid']),
3109 'snapshot_policy': self.na_helper.safe_get(record, ['snapshot_policy', 'name']),
3110 'percent_snapshot_space': self.na_helper.safe_get(record, ['space', 'snapshot', 'reserve_percent']),
3111 'size': self.na_helper.safe_get(record, ['space', 'size']),
3112 'space_guarantee': self.na_helper.safe_get(record, ['guarantee', 'type']),
3113 'is_online': is_online,
3114 'uuid': record.get('uuid', None),
3115 'efficiency_policy': self.na_helper.safe_get(record, ['efficiency', 'policy', 'name']),
3116 'compression': rest_compression in ('both', 'background'),
3117 'inline_compression': rest_compression in ('both', 'inline'),
3118 'logical_space_enforcement': self.na_helper.safe_get(record, ['space', 'logical_space', 'enforcement']),
3119 'logical_space_reporting': self.na_helper.safe_get(record, ['space', 'logical_space', 'reporting']),
3120 'tiering_minimum_cooling_days': self.na_helper.safe_get(record, ['tiering', 'min_cooling_days']),
3121 'snaplock': self.na_helper.safe_get(record, ['snaplock']),
3122 'max_files': self.na_helper.safe_get(record, ['files', 'maximum']),
3123 # The default setting for access_time_enabled and snapshot_directory_access_enabled is true
3124 'atime_update': record.get('access_time_enabled', True),
3125 'snapdir_access': record.get('snapshot_directory_access_enabled', True),
3126 'snapshot_auto_delete': auto_delete_info,
3127 'vol_nearly_full_threshold_percent': self.na_helper.safe_get(record, ['space', 'nearly_full_threshold_percent']),
3128 'vol_full_threshold_percent': self.na_helper.safe_get(record, ['space', 'full_threshold_percent']),
3129 'large_size_enabled': self.na_helper.safe_get(record, ['space', 'large_size_enabled']),
3130 'snapshot_locking': self.na_helper.safe_get(record, ['snapshot_locking_enabled']),
3131 'granular_data': self.na_helper.safe_get(record, ['granular_data']),
3132 }
3133
3134 def is_fabricpool(self, name, aggregate_uuid):
3135 '''whether the aggregate is associated with one or more object stores'''
3136 api = 'storage/aggregates/%s/cloud-stores' % aggregate_uuid
3137 records, error = rest_generic.get_0_or_more_records(self.rest_api, api)
3138 if error:
3139 self.module.fail_json(msg="Error getting object store for aggregate: %s: %s" % (name, error))
3140 return records is not None and len(records) > 0
3141
3142 def tiering_control(self, current):
3143 '''return whether the backend meets FabricPool requirements:
3144 required: all aggregates are in a FabricPool
3145 disallowed: all aggregates are not in a FabricPool
3146 best_effort: mixed
3147 '''
3148 fabricpools = [self.is_fabricpool(aggregate['name'], aggregate['uuid'])
3149 for aggregate in current.get('aggregates', [])]
3150 if not fabricpools:
3151 return None
3152 if all(fabricpools):
3153 return 'required'
3154 if any(fabricpools):
3155 return 'best_effort'
3156 return 'disallowed'
3157
3158 def set_actions(self):
3159 """define what needs to be done"""
3160 actions = []
3161 modify = {}
3162
3163 current = self.get_volume()
3164 if current:
3165 if 'tiering_object_tags' in current and current['tiering_object_tags'] is None:
3166 current['tiering_object_tags'] = []
3167 self.volume_style = self.get_volume_style(current)
3168 if self.volume_style == 'flexgroup' and self.parameters.get('aggregate_name') is not None:
3169 self.module.fail_json(msg='Error: aggregate_name option cannot be used with FlexGroups.')
3170
3171 cd_action = self.na_helper.get_cd_action(current, self.parameters)
3172 if cd_action == 'delete' or self.parameters['state'] == 'absent':
3173 return ['delete'] if cd_action == 'delete' else [], current, modify
3174
3175 # Handling rename logic first before create
3176 if self.parameters.get('from_name'):
3177 if current:
3178 # Destination volume already exists condition
3179 self.module.warn("Destination volume '%s' already exists" % self.parameters['name'])
3180 # Check if from_name still exists - if it does, throw an error
3181 from_volume = self.get_volume(self.parameters['from_name'])
3182 if from_volume:
3183 self.module.warn("Source volume '%s' still exists - this is an error!" % self.parameters['from_name'])
3184 self.module.fail_json(msg="Error: destination volume '%s' already exists and source volume '%s' still exists. "
3185 "Cannot rename when destination already exists." % (self.parameters['name'], self.parameters['from_name']))
3186 else:
3187 # from_name doesn't exist, destination exists indicates rename already completed
3188 # This is the idempotency case
3189 if not self.module.check_mode:
3190 self.module.warn("Idempotency check: Volume '%s' already exists and '%s' no longer exists. Rename already completed."
3191 % (self.parameters['name'], self.parameters['from_name']))
3192 return [], current, modify
3193
3194 if cd_action == 'create':
3195 # report an error if the vserver does not exist (it can be also be a cluster or node vserver with REST)
3196 if self.use_rest:
3197 rest_vserver.get_vserver_uuid(self.rest_api, self.parameters['vserver'], self.module, True)
3198 actions = ['create']
3199 if self.parameters.get('from_name'):
3200 # create by renaming
3201 current = self.get_volume(self.parameters['from_name'])
3202 rename = self.na_helper.is_rename_action(current, None)
3203 if rename is None:
3204 self.module.fail_json(msg="Error renaming volume: cannot find %s" % self.parameters['from_name'])
3205 if rename:
3206 cd_action = None
3207 actions = ['rename']
3208 elif self.parameters.get('from_vserver'):
3209 # create by rehosting
3210 if self.use_rest:
3211 self.module.fail_json(msg='Error: ONTAP REST API does not support Rehosting Volumes')
3212 actions = ['rehost']
3213 self.na_helper.changed = True
3214 if self.parameters.get('snapshot_restore'):
3215 # update by restoring
3216 if 'create' in actions:
3217 self.module.fail_json(msg="Error restoring volume: cannot find parent: %s" % self.parameters['name'])
3218 # let's allow restoring after a rename or rehost
3219 actions.append('snapshot_restore')
3220 self.na_helper.changed = True
3221 self.validate_snaplock_changes(current)
3222 if cd_action is None and 'rehost' not in actions:
3223 # Ignoring modify after a rehost, as we can't read the volume properties on the remote volume
3224 # or maybe we could, using a cluster ZAPI, but since ZAPI is going away, is it worth it?
3225 modify = self.set_modify_dict(current)
3226 if modify:
3227 # ZAPI decrypts volume using volume move api and aggregate name is required.
3228 if not self.use_rest and modify.get('encrypt') is False and not self.parameters.get('aggregate_name'):
3229 self.parameters['aggregate_name'] = current['aggregate_name']
3230 if self.use_rest and modify.get('encrypt') is False and not modify.get('aggregate_name'):
3231 self.module.fail_json(msg="Error: unencrypting volume is only supported when moving the volume to another aggregate in REST.")
3232 actions.append('modify')
3233 if not modify and len(actions) == 0:
3234 self.na_helper.changed = False
3235 if self.parameters.get('nas_application_template') is not None:
3236 application = self.get_application('nas')
3237 changed = self.na_helper.changed
3238 app_component = self.create_nas_application_component() if self.parameters['state'] == 'present' else None
3239 modify_app = self.na_helper.get_modified_attributes(application, app_component)
3240 # restore current change state, as we ignore this
3241 if modify_app:
3242 self.na_helper.changed = changed
3243 return actions, current, modify
3244
3245 def apply(self):
3246 '''Call create/modify/delete operations'''
3247 actions, current, modify = self.set_actions()
3248 is_online = current.get('is_online') if current else None
3249 response = None
3250
3251 # rehost, snapshot_restore and modify actions requires volume state to be online.
3252 online_modify_options = [x for x in actions if x in ['rehost', 'snapshot_restore', 'modify']]
3253 # ignore options that requires volume shoule be online.
3254 if not modify.get('is_online') and is_online is False and online_modify_options:
3255 modify_keys = []
3256 if 'modify' in online_modify_options:
3257 online_modify_options.remove('modify')
3258 modify_keys = [key for key in modify if key != 'is_online']
3259 action_msg = 'perform action(s): %s' % online_modify_options if online_modify_options else ''
3260 modify_msg = ' and modify: %s' % modify_keys if action_msg else 'modify: %s' % modify_keys
3261 self.module.warn("Cannot %s%s when volume is offline." % (action_msg, modify_msg))
3262 modify, actions = {}, []
3263 if 'rename' in actions:
3264 # rename can be done if volume is offline.
3265 actions = ['rename']
3266 else:
3267 self.na_helper.changed = False
3268
3269 if self.na_helper.changed and not self.module.check_mode:
3270 # always online volume first before other changes.
3271 # rehost, snapshot_restore and modify requires volume in online state.
3272 if modify.get('is_online'):
3273 self.parameters['uuid'] = current['uuid']
3274 # when moving to online, include parameters that get does not return when volume is offline
3275 for field in ['volume_security_style', 'group_id', 'user_id', 'percent_snapshot_space']:
3276 if self.parameters.get(field) is not None:
3277 modify[field] = self.parameters[field]
3278 self.change_volume_state()
3279 if 'rename' in actions:
3280 self.rename_volume()
3281 if 'rehost' in actions:
3282 # REST DOES NOT have a volume-rehost equivalent
3283 self.rehost_volume()
3284 if 'snapshot_restore' in actions:
3285 self.snapshot_restore_volume()
3286 if 'create' in actions:
3287 response = self.create_volume()
3288 # if we create using ZAPI and modify only options are set (snapdir_access or atime_update), we need to run a modify.
3289 # The modify also takes care of efficiency (sis) parameters and snapshot_auto_delete.
3290 # If we create using REST application, some options are not available, we may need to run a modify.
3291 # If we create using REST and modify only options are set (snapdir_access or atime_update or snapshot_auto_delete), we need to run a modify.
3292 # For modify only options to be set after creation wait_for_completion needs to be set.
3293 # volume should be online for modify.
3294 current = self.get_volume()
3295 if current:
3296 self.volume_created = True
3297 modify = self.set_modify_dict(current, after_create=True)
3298 is_online = current.get('is_online')
3299 if modify:
3300 if is_online:
3301 actions.append('modify')
3302 else:
3303 self.module.warn("Cannot perform actions: modify when volume is offline.")
3304 # restore this, as set_modify_dict could set it to False
3305 self.na_helper.changed = True
3306 if 'delete' in actions:
3307 self.parameters['uuid'] = current['uuid']
3308 self.delete_volume(current)
3309 if 'modify' in actions:
3310 self.parameters['uuid'] = current['uuid']
3311 self.take_modify_actions(modify)
3312
3313 result = netapp_utils.generate_result(self.na_helper.changed, actions, modify, response)
3314 self.module.exit_json(**result)
3315
3316
3317 def main():
3318 '''Apply volume operations from playbook'''
3319 obj = NetAppOntapVolume()
3320 obj.apply()
3321
3322
3323 if __name__ == '__main__':
3324 main()