| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
"""Ansible module for managing Snapshots on Dell Technologies (Dell) PowerFlex""" |
| 7 |
|
| 8 |
from __future__ import absolute_import, division, print_function |
| 9 |
|
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
DOCUMENTATION = r""" |
| 13 |
module: snapshot_v2 |
| 14 |
version_added: '3.0.0' |
| 15 |
short_description: Manage Snapshots on Dell PowerFlex |
| 16 |
description: |
| 17 |
- Managing snapshots on PowerFlex Storage System includes |
| 18 |
creating, getting details, modifying the attributes and deleting snapshot. |
| 19 |
|
| 20 |
author: |
| 21 |
- Yuhao Liu (@RayLiu7) <[email protected]> |
| 22 |
|
| 23 |
extends_documentation_fragment: |
| 24 |
- dellemc.powerflex.powerflex_v2 |
| 25 |
|
| 26 |
options: |
| 27 |
snapshot_name: |
| 28 |
description: |
| 29 |
- The name of the snapshot. |
| 30 |
- Mandatory for create operation. |
| 31 |
- Specify either I(snapshot_name) or I(snapshot_id) (but not both) for any operation. |
| 32 |
type: str |
| 33 |
snapshot_id: |
| 34 |
description: |
| 35 |
- The ID of the Snapshot. |
| 36 |
type: str |
| 37 |
vol_name: |
| 38 |
description: |
| 39 |
- The name of the volume for which snapshot will be taken. |
| 40 |
- Specify either I(vol_name) or I(vol_id) while creating snapshot. |
| 41 |
type: str |
| 42 |
vol_id: |
| 43 |
description: |
| 44 |
- The ID of the volume. |
| 45 |
type: str |
| 46 |
snapshot_new_name: |
| 47 |
description: |
| 48 |
- New name of the snapshot. Used to rename the snapshot. |
| 49 |
type: str |
| 50 |
desired_retention: |
| 51 |
description: |
| 52 |
- The retention value for the Snapshot. |
| 53 |
- If the desired_retention is not mentioned during creation, snapshot |
| 54 |
will be created with unlimited retention. |
| 55 |
- Maximum supported desired retention is 31 days. |
| 56 |
type: int |
| 57 |
retention_unit: |
| 58 |
description: |
| 59 |
- The unit for retention. It defaults to C(hours), if not specified. |
| 60 |
choices: [hours, days] |
| 61 |
type: str |
| 62 |
remove_mode: |
| 63 |
description: |
| 64 |
- Removal mode for the snapshot. |
| 65 |
- It defaults to C(ONLY_ME), if not specified. |
| 66 |
choices: ['ONLY_ME', 'INCLUDING_DESCENDANTS'] |
| 67 |
type: str |
| 68 |
state: |
| 69 |
description: |
| 70 |
- State of the snapshot. |
| 71 |
choices: ['present', 'absent'] |
| 72 |
default: present |
| 73 |
type: str |
| 74 |
attributes: |
| 75 |
check_mode: |
| 76 |
description: Runs task to validate without performing action on the target |
| 77 |
machine. |
| 78 |
support: full |
| 79 |
diff_mode: |
| 80 |
description: Runs the task to report the changes made or to be made. |
| 81 |
support: full |
| 82 |
notes: |
| 83 |
- Snapshots are read-only since PowerFlex 5.0.0 |
| 84 |
""" |
| 85 |
|
| 86 |
EXAMPLES = r""" |
| 87 |
- name: Create snapshot |
| 88 |
dellemc.powerflex.snapshot_v2: |
| 89 |
hostname: "{{hostname}}" |
| 90 |
username: "{{username}}" |
| 91 |
password: "{{password}}" |
| 92 |
validate_certs: "{{validate_certs}}" |
| 93 |
snapshot_name: "ansible_snapshot" |
| 94 |
vol_name: "ansible_volume" |
| 95 |
desired_retention: 2 |
| 96 |
state: "present" |
| 97 |
|
| 98 |
- name: Get snapshot details using snapshot id |
| 99 |
dellemc.powerflex.snapshot_v2: |
| 100 |
hostname: "{{hostname}}" |
| 101 |
username: "{{username}}" |
| 102 |
password: "{{password}}" |
| 103 |
validate_certs: "{{validate_certs}}" |
| 104 |
snapshot_id: "fe6cb28200000007" |
| 105 |
state: "present" |
| 106 |
|
| 107 |
- name: Rename snapshot |
| 108 |
dellemc.powerflex.snapshot_v2: |
| 109 |
hostname: "{{hostname}}" |
| 110 |
username: "{{username}}" |
| 111 |
password: "{{password}}" |
| 112 |
validate_certs: "{{validate_certs}}" |
| 113 |
snapshot_id: "fe6cb28200000007" |
| 114 |
snapshot_new_name: "ansible_renamed_snapshot_10" |
| 115 |
state: "present" |
| 116 |
|
| 117 |
- name: Delete snapshot |
| 118 |
dellemc.powerflex.snapshot_v2: |
| 119 |
hostname: "{{hostname}}" |
| 120 |
username: "{{username}}" |
| 121 |
password: "{{password}}" |
| 122 |
validate_certs: "{{validate_certs}}" |
| 123 |
snapshot_id: "fe6cb28200000007" |
| 124 |
remove_mode: "ONLY_ME" |
| 125 |
state: "absent" |
| 126 |
""" |
| 127 |
|
| 128 |
RETURN = r""" |
| 129 |
changed: |
| 130 |
description: Whether or not the resource has changed. |
| 131 |
returned: always |
| 132 |
type: bool |
| 133 |
sample: 'false' |
| 134 |
|
| 135 |
snapshot_details: |
| 136 |
description: Details of the snapshot. |
| 137 |
returned: When snapshot exists |
| 138 |
type: dict |
| 139 |
contains: |
| 140 |
ancestorVolumeId: |
| 141 |
description: The ID of the root of the specified volume's V-Tree. |
| 142 |
type: str |
| 143 |
ancestorVolumeName: |
| 144 |
description: The name of the root of the specified volume's V-Tree. |
| 145 |
type: str |
| 146 |
creationTime: |
| 147 |
description: The creation time of the snapshot. |
| 148 |
type: int |
| 149 |
id: |
| 150 |
description: The ID of the snapshot. |
| 151 |
type: str |
| 152 |
name: |
| 153 |
description: Name of the snapshot. |
| 154 |
type: str |
| 155 |
secureSnapshotExpTime: |
| 156 |
description: Expiry time of the snapshot. |
| 157 |
type: int |
| 158 |
sizeInKb: |
| 159 |
description: Size of the snapshot. |
| 160 |
type: int |
| 161 |
sizeInGb: |
| 162 |
description: Size of the snapshot. |
| 163 |
type: int |
| 164 |
retentionInHours: |
| 165 |
description: Retention of the snapshot in hours. |
| 166 |
type: int |
| 167 |
storagePoolId: |
| 168 |
description: The ID of the Storage pool in which snapshot resides. |
| 169 |
type: str |
| 170 |
storagePoolName: |
| 171 |
description: The name of the Storage pool in which snapshot resides. |
| 172 |
type: str |
| 173 |
sample: { |
| 174 |
"accessModeLimit": "ReadOnly", |
| 175 |
"ancestorVolumeId": "cdd883cf00000002", |
| 176 |
"ancestorVolumeName": "ansible-volume-1", |
| 177 |
"autoSnapshotGroupId": null, |
| 178 |
"compressionMethod": "Invalid", |
| 179 |
"consistencyGroupId": "22f1e80c00000001", |
| 180 |
"creationTime": 1631619229, |
| 181 |
"dataLayout": "MediumGranularity", |
| 182 |
"genType": "EC", |
| 183 |
"id": "cdd883d000000004", |
| 184 |
"links": [ |
| 185 |
{ |
| 186 |
"href": "/api/instances/Volume::cdd883d000000004", |
| 187 |
"rel": "self" |
| 188 |
}, |
| 189 |
{ |
| 190 |
"href": "/api/instances/Volume::cdd883d000000004/relationships |
| 191 |
/Statistics", |
| 192 |
"rel": "/api/Volume/relationship/Statistics" |
| 193 |
}, |
| 194 |
{ |
| 195 |
"href": "/api/instances/Volume::cdd883cf00000002", |
| 196 |
"rel": "/api/parent/relationship/ancestorVolumeId" |
| 197 |
}, |
| 198 |
{ |
| 199 |
"href": "/api/instances/VTree::6e86255c00000001", |
| 200 |
"rel": "/api/parent/relationship/vtreeId" |
| 201 |
}, |
| 202 |
{ |
| 203 |
"href": "/api/instances/StoragePool::e0d8f6c900000000", |
| 204 |
"rel": "/api/parent/relationship/storagePoolId" |
| 205 |
} |
| 206 |
], |
| 207 |
"lockedAutoSnapshot": false, |
| 208 |
"lockedAutoSnapshotMarkedForRemoval": false, |
| 209 |
"managedBy": "ScaleIO", |
| 210 |
"mappedSdcInfo": null, |
| 211 |
"name": "ansible_vol_snap_1", |
| 212 |
"notGenuineSnapshot": false, |
| 213 |
"nsid": 23, |
| 214 |
"originalExpiryTime": 0, |
| 215 |
"pairIds": null, |
| 216 |
"replicationJournalVolume": false, |
| 217 |
"replicationTimeStamp": 0, |
| 218 |
"retentionInHours": 0, |
| 219 |
"retentionLevels": [], |
| 220 |
"secureSnapshotExpTime": 0, |
| 221 |
"sizeInGb": 16, |
| 222 |
"sizeInKb": 16777216, |
| 223 |
"snplIdOfAutoSnapshot": null, |
| 224 |
"snplIdOfSourceVolume": null, |
| 225 |
"storagePoolId": "e0d8f6c900000000", |
| 226 |
"storagePoolName": "pool1", |
| 227 |
"timeStampIsAccurate": false, |
| 228 |
"useRmcache": false, |
| 229 |
"volumeClass": "defaultclass", |
| 230 |
"volumeReplicationState": "UnmarkedForReplication", |
| 231 |
"volumeType": "Snapshot", |
| 232 |
"vtreeId": "6e86255c00000001" |
| 233 |
} |
| 234 |
""" |
| 235 |
|
| 236 |
from ansible.module_utils.basic import AnsibleModule |
| 237 |
from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell\ |
| 238 |
import utils |
| 239 |
from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \ |
| 240 |
import powerflex_compatibility |
| 241 |
from ansible_collections.dellemc.powerflex.plugins.module_utils.storage.dell.libraries.powerflex_base \ |
| 242 |
import PowerFlexBase |
| 243 |
from datetime import datetime, timedelta |
| 244 |
import time |
| 245 |
import copy |
| 246 |
|
| 247 |
LOG = utils.get_logger("snapshot_v2") |
| 248 |
|
| 249 |
|
| 250 |
@powerflex_compatibility(min_ver='5.0', predecessor='snapshot') |
| 251 |
class PowerFlexSnapshotV2(PowerFlexBase): |
| 252 |
"""Class with Snapshot operations""" |
| 253 |
|
| 254 |
def __init__(self): |
| 255 |
"""Define all parameters required by this module""" |
| 256 |
argument_spec = get_powerflex_snapshot_parameters() |
| 257 |
|
| 258 |
mutually_exclusive = [ |
| 259 |
["snapshot_name", "snapshot_id"], |
| 260 |
["vol_name", "vol_id"], |
| 261 |
["snapshot_id", "vol_name"], |
| 262 |
["snapshot_id", "vol_id"], |
| 263 |
] |
| 264 |
|
| 265 |
required_one_of = [["snapshot_name", "snapshot_id"]] |
| 266 |
|
| 267 |
module_params = { |
| 268 |
'argument_spec': argument_spec, |
| 269 |
'supports_check_mode': True, |
| 270 |
'mutually_exclusive': mutually_exclusive, |
| 271 |
'required_one_of': required_one_of, |
| 272 |
} |
| 273 |
|
| 274 |
super().__init__(AnsibleModule, module_params) |
| 275 |
super().check_module_compatibility() |
| 276 |
|
| 277 |
def get_storage_pool(self, storage_pool_id): |
| 278 |
"""Get storage pool details |
| 279 |
:param storage_pool_id: The storage pool id |
| 280 |
:return: Storage pool details |
| 281 |
""" |
| 282 |
|
| 283 |
try: |
| 284 |
return self.powerflex_conn.storage_pool.get( |
| 285 |
filter_fields={"id": storage_pool_id} |
| 286 |
) |
| 287 |
|
| 288 |
except Exception as e: |
| 289 |
errormsg = "Failed to get the storage pool %s with error " "%s" % ( |
| 290 |
storage_pool_id, |
| 291 |
str(e), |
| 292 |
) |
| 293 |
LOG.error(errormsg) |
| 294 |
self.module.fail_json(msg=errormsg) |
| 295 |
|
| 296 |
def get_snapshot(self, snapshot_name=None, snapshot_id=None): |
| 297 |
"""Get snapshot details |
| 298 |
:param snapshot_name: Name of the snapshot |
| 299 |
:param snapshot_id: ID of the snapshot |
| 300 |
:return: Details of snapshot if exist. |
| 301 |
""" |
| 302 |
|
| 303 |
id_or_name = snapshot_id if snapshot_id else snapshot_name |
| 304 |
|
| 305 |
try: |
| 306 |
filters = {"id": snapshot_id} |
| 307 |
if snapshot_name: |
| 308 |
filters = {"name": snapshot_name} |
| 309 |
snapshot_details = self.powerflex_conn.volume.get(filter_fields=filters) |
| 310 |
|
| 311 |
if len(snapshot_details) == 0: |
| 312 |
msg = "Snapshot with identifier %s is not found" % id_or_name |
| 313 |
LOG.error(msg) |
| 314 |
return None |
| 315 |
|
| 316 |
if len(snapshot_details) > 1: |
| 317 |
errormsg = ( |
| 318 |
"Multiple instances of snapshot " |
| 319 |
"exist with name {0}".format(snapshot_name) |
| 320 |
) |
| 321 |
self.module.fail_json(msg=errormsg) |
| 322 |
|
| 323 |
|
| 324 |
self.add_ancestor(snapshot_details) |
| 325 |
|
| 326 |
|
| 327 |
self.add_size_in_gb(snapshot_details) |
| 328 |
|
| 329 |
|
| 330 |
self.add_storage_pool_name(snapshot_details) |
| 331 |
|
| 332 |
|
| 333 |
self.add_retention_in_hours(snapshot_details) |
| 334 |
|
| 335 |
|
| 336 |
if any([self.module.params["vol_name"], self.module.params["vol_id"]]): |
| 337 |
self.match_vol_details(snapshot_details[0]) |
| 338 |
return snapshot_details[0] |
| 339 |
except Exception as e: |
| 340 |
errormsg = "Failed to get the snapshot %s with error %s" % ( |
| 341 |
id_or_name, |
| 342 |
str(e), |
| 343 |
) |
| 344 |
LOG.error(errormsg) |
| 345 |
self.module.fail_json(msg=errormsg) |
| 346 |
|
| 347 |
def add_retention_in_hours(self, snapshot_details): |
| 348 |
if ( |
| 349 |
"secureSnapshotExpTime" in snapshot_details[0] |
| 350 |
and "creationTime" in snapshot_details[0] |
| 351 |
): |
| 352 |
if snapshot_details[0]["secureSnapshotExpTime"] != 0: |
| 353 |
expiry_obj = datetime.fromtimestamp( |
| 354 |
snapshot_details[0]["secureSnapshotExpTime"] |
| 355 |
) |
| 356 |
creation_obj = datetime.fromtimestamp( |
| 357 |
snapshot_details[0]["creationTime"] |
| 358 |
) |
| 359 |
|
| 360 |
td_hour = int( |
| 361 |
round(get_datetime_diff_in_minutes(expiry_obj, creation_obj) / 60) |
| 362 |
) |
| 363 |
snapshot_details[0]["retentionInHours"] = td_hour |
| 364 |
else: |
| 365 |
snapshot_details[0]["retentionInHours"] = 0 |
| 366 |
|
| 367 |
def add_storage_pool_name(self, snapshot_details): |
| 368 |
if ( |
| 369 |
"storagePoolId" in snapshot_details[0] |
| 370 |
and snapshot_details[0]["storagePoolId"] |
| 371 |
): |
| 372 |
sp = self.get_storage_pool(snapshot_details[0]["storagePoolId"]) |
| 373 |
if len(sp) > 0: |
| 374 |
snapshot_details[0]["storagePoolName"] = sp[0]["name"] |
| 375 |
|
| 376 |
def add_size_in_gb(self, snapshot_details): |
| 377 |
if "sizeInKb" in snapshot_details[0] and snapshot_details[0]["sizeInKb"]: |
| 378 |
snapshot_details[0]["sizeInGb"] = utils.get_size_in_gb( |
| 379 |
snapshot_details[0]["sizeInKb"], "KB" |
| 380 |
) |
| 381 |
|
| 382 |
def add_ancestor(self, snapshot_details): |
| 383 |
if ( |
| 384 |
"ancestorVolumeId" in snapshot_details[0] |
| 385 |
and snapshot_details[0]["ancestorVolumeId"] |
| 386 |
): |
| 387 |
vol = self.get_volume(vol_id=snapshot_details[0]["ancestorVolumeId"]) |
| 388 |
snapshot_details[0]["ancestorVolumeName"] = vol["name"] |
| 389 |
|
| 390 |
def match_vol_details(self, snapshot): |
| 391 |
"""Match the given volume details with the response |
| 392 |
:param snapshot: The snapshot details |
| 393 |
""" |
| 394 |
vol_name = self.module.params["vol_name"] |
| 395 |
vol_id = self.module.params["vol_id"] |
| 396 |
|
| 397 |
try: |
| 398 |
if vol_name and vol_name != snapshot["ancestorVolumeName"]: |
| 399 |
errormsg = ( |
| 400 |
"Given volume name do not match with the " |
| 401 |
"corresponding snapshot details." |
| 402 |
) |
| 403 |
self.module.fail_json(msg=errormsg) |
| 404 |
|
| 405 |
if vol_id and vol_id != snapshot["ancestorVolumeId"]: |
| 406 |
errormsg = ( |
| 407 |
"Given volume ID do not match with the " |
| 408 |
"corresponding snapshot details." |
| 409 |
) |
| 410 |
self.module.fail_json(msg=errormsg) |
| 411 |
except Exception as e: |
| 412 |
errormsg = ( |
| 413 |
"Failed to match volume details with the snapshot " |
| 414 |
"with error %s" % str(e) |
| 415 |
) |
| 416 |
LOG.error(errormsg) |
| 417 |
self.module.fail_json(msg=errormsg) |
| 418 |
|
| 419 |
def get_volume(self, vol_name=None, vol_id=None): |
| 420 |
"""Get the volume id |
| 421 |
:param vol_name: The name of the volume |
| 422 |
:param vol_id: The ID of the volume |
| 423 |
:return: The volume details |
| 424 |
""" |
| 425 |
|
| 426 |
try: |
| 427 |
if vol_name: |
| 428 |
vol_details = self.powerflex_conn.volume.get( |
| 429 |
filter_fields={"name": vol_name} |
| 430 |
) |
| 431 |
else: |
| 432 |
vol_details = self.powerflex_conn.volume.get( |
| 433 |
filter_fields={"id": vol_id} |
| 434 |
) |
| 435 |
|
| 436 |
if len(vol_details) == 0: |
| 437 |
error_msg = "Unable to find volume with name {0}".format(vol_name) |
| 438 |
self.module.fail_json(msg=error_msg) |
| 439 |
return vol_details[0] |
| 440 |
except Exception as e: |
| 441 |
errormsg = "Failed to get the volume %s with error " "%s" % ( |
| 442 |
vol_name, |
| 443 |
str(e), |
| 444 |
) |
| 445 |
LOG.error(errormsg) |
| 446 |
self.module.fail_json(msg=errormsg) |
| 447 |
|
| 448 |
def get_system_id(self): |
| 449 |
"""Get system id""" |
| 450 |
|
| 451 |
try: |
| 452 |
resp = self.powerflex_conn.system.get() |
| 453 |
|
| 454 |
if len(resp) == 0: |
| 455 |
self.module.fail_json(msg="No system exist on the given host.") |
| 456 |
|
| 457 |
if len(resp) > 1: |
| 458 |
self.module.fail_json( |
| 459 |
msg="Multiple systems exist on the " "given host." |
| 460 |
) |
| 461 |
return resp[0]["id"] |
| 462 |
except Exception as e: |
| 463 |
msg = "Failed to get system id with error %s" % str(e) |
| 464 |
LOG.error(msg) |
| 465 |
self.module.fail_json(msg=msg) |
| 466 |
|
| 467 |
def create_snapshot(self, snapshot_name, vol_id, system_id, retention): |
| 468 |
"""Create snapshot |
| 469 |
:param snapshot_name: The name of the snapshot |
| 470 |
:param vol_id: The ID of the source volume |
| 471 |
:param system_id: The system id |
| 472 |
:param retention: The retention for the snapshot |
| 473 |
:return: Boolean indicating if create operation is successful |
| 474 |
""" |
| 475 |
LOG.debug("Creating Snapshot") |
| 476 |
|
| 477 |
try: |
| 478 |
if not self.module.check_mode: |
| 479 |
self.powerflex_conn.system.create_snapshot( |
| 480 |
system_id=system_id, |
| 481 |
snapshot_defs=[{"volumeId": vol_id, "snapshotName": snapshot_name}], |
| 482 |
retention_period=retention, |
| 483 |
) |
| 484 |
|
| 485 |
return True |
| 486 |
except Exception as e: |
| 487 |
errormsg = "Create snapshot %s operation failed with " "error %s" % ( |
| 488 |
snapshot_name, |
| 489 |
str(e), |
| 490 |
) |
| 491 |
LOG.error(errormsg) |
| 492 |
self.module.fail_json(msg=errormsg) |
| 493 |
|
| 494 |
def modify_retention(self, snapshot_id, new_retention): |
| 495 |
"""Modify snapshot retention |
| 496 |
:param snapshot_id: The snapshot id |
| 497 |
:param new_retention: Desired retention of the snapshot |
| 498 |
:return: Boolean indicating if modifying retention is successful |
| 499 |
""" |
| 500 |
|
| 501 |
try: |
| 502 |
if not self.module.check_mode: |
| 503 |
self.powerflex_conn.volume.set_retention_period(snapshot_id, new_retention) |
| 504 |
return True |
| 505 |
except Exception as e: |
| 506 |
errormsg = ( |
| 507 |
"Modify retention of snapshot %s operation failed " |
| 508 |
"with error %s" % (snapshot_id, str(e)) |
| 509 |
) |
| 510 |
LOG.error(errormsg) |
| 511 |
self.module.fail_json(msg=errormsg) |
| 512 |
|
| 513 |
def rename_snapshot(self, snapshot_id, new_name): |
| 514 |
"""Rename snapshot |
| 515 |
:param snapshot_id: The snapshot id |
| 516 |
:param new_name: The new name of the snapshot |
| 517 |
:return: Boolean indicating if rename operation is successful |
| 518 |
""" |
| 519 |
|
| 520 |
try: |
| 521 |
if not self.module.check_mode: |
| 522 |
self.powerflex_conn.volume.rename(snapshot_id, new_name) |
| 523 |
return True |
| 524 |
except Exception as e: |
| 525 |
errormsg = "Rename snapshot %s operation failed with " "error %s" % ( |
| 526 |
snapshot_id, |
| 527 |
str(e), |
| 528 |
) |
| 529 |
LOG.error(errormsg) |
| 530 |
self.module.fail_json(msg=errormsg) |
| 531 |
|
| 532 |
def delete_snapshot(self, snapshot_id, remove_mode): |
| 533 |
"""Delete snapshot |
| 534 |
:param snapshot_id: The snapshot id |
| 535 |
:param remove_mode: Removal mode for the snapshot |
| 536 |
:return: Boolean indicating if delete operation is successful |
| 537 |
""" |
| 538 |
|
| 539 |
try: |
| 540 |
if not self.module.check_mode: |
| 541 |
self.powerflex_conn.volume.delete(snapshot_id, remove_mode) |
| 542 |
return True |
| 543 |
except Exception as e: |
| 544 |
errormsg = "Delete snapshot %s operation failed with " "error %s" % ( |
| 545 |
snapshot_id, |
| 546 |
str(e), |
| 547 |
) |
| 548 |
LOG.error(errormsg) |
| 549 |
self.module.fail_json(msg=errormsg) |
| 550 |
|
| 551 |
def validate_desired_retention(self, desired_retention, retention_unit): |
| 552 |
"""Validates the specified desired retention. |
| 553 |
:param desired_retention: Desired retention of the snapshot |
| 554 |
:param retention_unit: Retention unit for snapshot |
| 555 |
""" |
| 556 |
|
| 557 |
if desired_retention is not None: |
| 558 |
if retention_unit == "hours" and ( |
| 559 |
desired_retention < 1 or desired_retention > 744 |
| 560 |
): |
| 561 |
self.module.fail_json( |
| 562 |
msg="Please provide a valid integer as the" |
| 563 |
" desired retention between 1 and 744." |
| 564 |
) |
| 565 |
elif retention_unit == "days" and ( |
| 566 |
desired_retention < 1 or desired_retention > 31 |
| 567 |
): |
| 568 |
self.module.fail_json( |
| 569 |
msg="Please provide a valid integer as the" |
| 570 |
" desired retention between 1 and 31." |
| 571 |
) |
| 572 |
|
| 573 |
def validate_parameters(self): |
| 574 |
"""Validate the input parameters""" |
| 575 |
|
| 576 |
desired_retention = self.module.params["desired_retention"] |
| 577 |
retention_unit = self.module.params["retention_unit"] |
| 578 |
|
| 579 |
param_list = [ |
| 580 |
"snapshot_name", |
| 581 |
"snapshot_id", |
| 582 |
"vol_name", |
| 583 |
"vol_id", |
| 584 |
"snapshot_new_name", |
| 585 |
] |
| 586 |
for param in param_list: |
| 587 |
if ( |
| 588 |
self.module.params[param] is not None |
| 589 |
and len(self.module.params[param].strip()) == 0 |
| 590 |
): |
| 591 |
error_msg = "Please provide valid %s" % param |
| 592 |
self.module.fail_json(msg=error_msg) |
| 593 |
|
| 594 |
if (retention_unit is not None) and not desired_retention: |
| 595 |
self.module.fail_json( |
| 596 |
msg="retention_unit can only be specified along with desired_retention" |
| 597 |
) |
| 598 |
|
| 599 |
def get_diff_after(self, snapshot_params, snapshot_details, modify_dict): |
| 600 |
"""Get diff between playbook input and snapshot details |
| 601 |
:param snapshot_params: Dictionary of parameters input from playbook |
| 602 |
:param snapshot_details: Dictionary of snapshot details |
| 603 |
:return: Dictionary of parameters of differences""" |
| 604 |
|
| 605 |
if snapshot_params["state"] == "absent": |
| 606 |
return {} |
| 607 |
diff_dict = {} |
| 608 |
if snapshot_details is None: |
| 609 |
diff_dict = {"snapshot_name": snapshot_params["snapshot_name"]} |
| 610 |
if snapshot_params["vol_name"]: |
| 611 |
diff_dict["ancestorVolumeName"] = snapshot_params["vol_name"] |
| 612 |
if snapshot_params["vol_id"]: |
| 613 |
diff_dict["ancestorVolumeId"] = snapshot_params["vol_id"] |
| 614 |
if snapshot_params["desired_retention"]: |
| 615 |
diff_dict["retentionInHours"] = ( |
| 616 |
snapshot_params["desired_retention"] |
| 617 |
if snapshot_params["retention_unit"] != "days" |
| 618 |
else snapshot_params["desired_retention"] * 24 |
| 619 |
) |
| 620 |
else: |
| 621 |
diff_dict = copy.deepcopy(snapshot_details) |
| 622 |
for key in modify_dict.keys(): |
| 623 |
diff_dict[key] = modify_dict[key] |
| 624 |
return diff_dict |
| 625 |
|
| 626 |
def perform_module_operation(self): |
| 627 |
""" |
| 628 |
Perform different actions on snapshot based on parameters passed in |
| 629 |
the playbook |
| 630 |
""" |
| 631 |
snapshot_name = self.module.params["snapshot_name"] |
| 632 |
snapshot_id = self.module.params["snapshot_id"] |
| 633 |
vol_name = self.module.params["vol_name"] |
| 634 |
vol_id = self.module.params["vol_id"] |
| 635 |
snapshot_new_name = self.module.params["snapshot_new_name"] |
| 636 |
desired_retention = self.module.params["desired_retention"] |
| 637 |
retention_unit = self.module.params["retention_unit"] |
| 638 |
remove_mode = self.module.params["remove_mode"] |
| 639 |
state = self.module.params["state"] |
| 640 |
|
| 641 |
|
| 642 |
changed = False |
| 643 |
result = dict(changed=False, snapshot_details={}) |
| 644 |
|
| 645 |
self.validate_parameters() |
| 646 |
|
| 647 |
retention_unit = self.get_retention_unit(desired_retention, retention_unit) |
| 648 |
|
| 649 |
self.validate_desired_retention(desired_retention, retention_unit) |
| 650 |
|
| 651 |
snapshot_details = self.get_snapshot(snapshot_name, snapshot_id) |
| 652 |
|
| 653 |
modify_dict = None |
| 654 |
if snapshot_details: |
| 655 |
modify_dict = self.check_snapshot_modified( |
| 656 |
snapshot_details, snapshot_new_name, desired_retention, retention_unit |
| 657 |
) |
| 658 |
|
| 659 |
before_dict = snapshot_details if snapshot_details is not None else {} |
| 660 |
diff_dict = {} |
| 661 |
diff_dict = self.get_diff_after(self.module.params, snapshot_details, modify_dict) |
| 662 |
if self.module._diff: |
| 663 |
result["diff"] = dict(before=before_dict, after=diff_dict) |
| 664 |
|
| 665 |
if state == "present" and not snapshot_details: |
| 666 |
self.validate_create( |
| 667 |
snapshot_name, |
| 668 |
snapshot_id, |
| 669 |
vol_name, |
| 670 |
vol_id, |
| 671 |
snapshot_new_name, |
| 672 |
remove_mode, |
| 673 |
) |
| 674 |
changed = self.create_snapshot_with_detail( |
| 675 |
snapshot_name, vol_name, vol_id, desired_retention, retention_unit |
| 676 |
) |
| 677 |
|
| 678 |
if state == "present" and snapshot_details and modify_dict: |
| 679 |
changed = self.modify_val( |
| 680 |
snapshot_new_name, |
| 681 |
desired_retention, |
| 682 |
retention_unit, |
| 683 |
snapshot_details, |
| 684 |
modify_dict, |
| 685 |
) |
| 686 |
snapshot_name = snapshot_new_name if snapshot_new_name else snapshot_name |
| 687 |
|
| 688 |
if state == "absent" and snapshot_details: |
| 689 |
remove_mode = "ONLY_ME" if remove_mode is None else remove_mode |
| 690 |
changed = self.delete_snapshot(snapshot_details["id"], remove_mode) |
| 691 |
|
| 692 |
if state == "present": |
| 693 |
snapshot_details = self.get_snapshot(snapshot_name, snapshot_id) |
| 694 |
result["snapshot_details"] = snapshot_details |
| 695 |
|
| 696 |
result["changed"] = changed |
| 697 |
self.module.exit_json(**result) |
| 698 |
|
| 699 |
def get_retention_unit(self, desired_retention, retention_unit): |
| 700 |
if desired_retention and not retention_unit: |
| 701 |
retention_unit = "hours" |
| 702 |
return retention_unit |
| 703 |
|
| 704 |
def modify_val( |
| 705 |
self, |
| 706 |
snapshot_new_name, |
| 707 |
desired_retention, |
| 708 |
retention_unit, |
| 709 |
snapshot_details, |
| 710 |
modify_dict, |
| 711 |
): |
| 712 |
changed = False |
| 713 |
if "name" in modify_dict: |
| 714 |
changed = self.rename_snapshot(snapshot_details["id"], snapshot_new_name) |
| 715 |
if "retentionInHours" in modify_dict: |
| 716 |
retention = calculate_retention(desired_retention, retention_unit) |
| 717 |
changed = self.modify_retention(snapshot_details["id"], retention) |
| 718 |
return changed |
| 719 |
|
| 720 |
def create_snapshot_with_detail( |
| 721 |
self, snapshot_name, vol_name, vol_id, desired_retention, retention_unit |
| 722 |
): |
| 723 |
if vol_name: |
| 724 |
vol = self.get_volume(vol_name=vol_name) |
| 725 |
vol_id = vol["id"] |
| 726 |
|
| 727 |
retention = 0 |
| 728 |
if desired_retention: |
| 729 |
retention = calculate_retention(desired_retention, retention_unit) |
| 730 |
|
| 731 |
system_id = self.get_system_id() |
| 732 |
|
| 733 |
changed = self.create_snapshot(snapshot_name, vol_id, system_id, retention) |
| 734 |
return changed |
| 735 |
|
| 736 |
def validate_create( |
| 737 |
self, |
| 738 |
snapshot_name, |
| 739 |
snapshot_id, |
| 740 |
vol_name, |
| 741 |
vol_id, |
| 742 |
snapshot_new_name, |
| 743 |
remove_mode, |
| 744 |
): |
| 745 |
if snapshot_id: |
| 746 |
self.module.fail_json( |
| 747 |
msg="Creation of snapshot is allowed " |
| 748 |
"using snapshot_name only, " |
| 749 |
"snapshot_id given." |
| 750 |
) |
| 751 |
|
| 752 |
if snapshot_name is None or len(snapshot_name.strip()) == 0: |
| 753 |
self.module.fail_json(msg="Please provide valid snapshot name.") |
| 754 |
|
| 755 |
if vol_name is None and vol_id is None: |
| 756 |
self.module.fail_json( |
| 757 |
msg="Please provide volume details to create new snapshot" |
| 758 |
) |
| 759 |
|
| 760 |
if snapshot_new_name is not None: |
| 761 |
self.module.fail_json( |
| 762 |
msg="snapshot_new_name is not required while creating snapshot" |
| 763 |
) |
| 764 |
|
| 765 |
if remove_mode: |
| 766 |
self.module.fail_json( |
| 767 |
msg="remove_mode is not required while creating snapshot" |
| 768 |
) |
| 769 |
|
| 770 |
def check_snapshot_modified( |
| 771 |
self, |
| 772 |
snapshot=None, |
| 773 |
snapshot_new_name=None, |
| 774 |
desired_retention=None, |
| 775 |
retention_unit=None, |
| 776 |
): |
| 777 |
"""Check if snapshot modification is required |
| 778 |
:param snapshot: Snapshot details |
| 779 |
:param snapshot_new_name: New name of the snapshot |
| 780 |
:param desired_retention: Desired retention of the snapshot |
| 781 |
:param retention_unit: Retention unit for snapshot |
| 782 |
:return: Dictionary containing the attributes of Snapshot which are to be |
| 783 |
updated |
| 784 |
""" |
| 785 |
modify_dict = {} |
| 786 |
|
| 787 |
if snapshot_new_name is not None and snapshot_new_name != snapshot["name"]: |
| 788 |
modify_dict["name"] = snapshot_new_name |
| 789 |
|
| 790 |
expiration_timestamp = None |
| 791 |
snap_creation_timestamp = get_snap_creation_time(snapshot) |
| 792 |
|
| 793 |
if desired_retention: |
| 794 |
expiration_timestamp = get_expiration_timestamp( |
| 795 |
desired_retention, retention_unit, snap_creation_timestamp |
| 796 |
) |
| 797 |
|
| 798 |
if ( |
| 799 |
"secureSnapshotExpTime" in snapshot |
| 800 |
and expiration_timestamp |
| 801 |
and snapshot["secureSnapshotExpTime"] != expiration_timestamp |
| 802 |
): |
| 803 |
existing_timestamp = snapshot["secureSnapshotExpTime"] |
| 804 |
new_timestamp = expiration_timestamp |
| 805 |
|
| 806 |
info_message = ( |
| 807 |
"The existing timestamp is: %s and the new " |
| 808 |
"timestamp is: %s" % (existing_timestamp, new_timestamp) |
| 809 |
) |
| 810 |
LOG.info(info_message) |
| 811 |
|
| 812 |
existing_time_obj = datetime.fromtimestamp(existing_timestamp) |
| 813 |
new_time_obj = datetime.fromtimestamp(new_timestamp) |
| 814 |
|
| 815 |
td = get_datetime_diff_in_minutes(existing_time_obj, new_time_obj) |
| 816 |
|
| 817 |
LOG.info("Time difference: %s", td) |
| 818 |
|
| 819 |
|
| 820 |
if td > 2: |
| 821 |
modify_dict["retentionInHours"] = ( |
| 822 |
desired_retention |
| 823 |
if retention_unit != "days" |
| 824 |
else desired_retention * 24 |
| 825 |
) |
| 826 |
|
| 827 |
return modify_dict |
| 828 |
|
| 829 |
|
| 830 |
def get_datetime_diff_in_minutes(dt1, dt2): |
| 831 |
""" |
| 832 |
Calculates the difference in two datetime objects. |
| 833 |
Args: |
| 834 |
dt1 (datetime): The first datetime object. |
| 835 |
dt2 (datetime): The second datetime object. |
| 836 |
Returns: |
| 837 |
int: The difference in minutes between dt1 and dt2. |
| 838 |
Raises: |
| 839 |
TypeError: If dt1 or dt2 are None. |
| 840 |
""" |
| 841 |
if dt1 is None: |
| 842 |
raise ValueError("First datetime cannot be None") |
| 843 |
if dt2 is None: |
| 844 |
raise ValueError("Second datetime cannot be None") |
| 845 |
if not isinstance(dt1, datetime): |
| 846 |
raise TypeError( |
| 847 |
f"First parameter is not a datetime object, it is {type(dt1).__name__}." |
| 848 |
) |
| 849 |
if not isinstance(dt2, datetime): |
| 850 |
raise TypeError( |
| 851 |
f"Second parameter not a datetime object, it is {type(dt2).__name__}." |
| 852 |
) |
| 853 |
|
| 854 |
if dt1 > dt2: |
| 855 |
td = dt1 - dt2 |
| 856 |
else: |
| 857 |
td = dt2 - dt1 |
| 858 |
return int(round(td.total_seconds() / 60)) |
| 859 |
|
| 860 |
|
| 861 |
def get_expiration_timestamp( |
| 862 |
desired_retention, retention_unit, snap_creation_timestamp |
| 863 |
): |
| 864 |
if retention_unit == "hours": |
| 865 |
expiration_timestamp = datetime.fromtimestamp( |
| 866 |
snap_creation_timestamp |
| 867 |
) + timedelta(hours=desired_retention) |
| 868 |
expiration_timestamp = time.mktime(expiration_timestamp.timetuple()) |
| 869 |
else: |
| 870 |
expiration_timestamp = datetime.fromtimestamp( |
| 871 |
snap_creation_timestamp |
| 872 |
) + timedelta(days=desired_retention) |
| 873 |
expiration_timestamp = time.mktime(expiration_timestamp.timetuple()) |
| 874 |
return expiration_timestamp |
| 875 |
|
| 876 |
|
| 877 |
def get_snap_creation_time(snapshot): |
| 878 |
snap_creation_timestamp = None |
| 879 |
if "creationTime" in snapshot: |
| 880 |
snap_creation_timestamp = snapshot["creationTime"] |
| 881 |
return snap_creation_timestamp |
| 882 |
|
| 883 |
|
| 884 |
def calculate_retention(desired_retention=None, retention_unit=None): |
| 885 |
""" |
| 886 |
:param desired_retention: Desired retention of the snapshot |
| 887 |
:param retention_unit: Retention unit for snapshot |
| 888 |
:return: Retention in minutes |
| 889 |
""" |
| 890 |
|
| 891 |
retention = 0 |
| 892 |
if retention_unit == "days": |
| 893 |
retention = desired_retention * 24 * 60 |
| 894 |
else: |
| 895 |
retention = desired_retention * 60 |
| 896 |
return retention |
| 897 |
|
| 898 |
|
| 899 |
def get_powerflex_snapshot_parameters(): |
| 900 |
"""This method provide parameter required for the Ansible snapshot |
| 901 |
module on PowerFlex""" |
| 902 |
return dict( |
| 903 |
snapshot_name=dict(), |
| 904 |
snapshot_id=dict(), |
| 905 |
vol_name=dict(), |
| 906 |
vol_id=dict(), |
| 907 |
snapshot_new_name=dict(), |
| 908 |
desired_retention=dict(type="int"), |
| 909 |
retention_unit=dict(choices=["hours", "days"]), |
| 910 |
remove_mode=dict(choices=["ONLY_ME", "INCLUDING_DESCENDANTS"]), |
| 911 |
state=dict( |
| 912 |
type="str", choices=["present", "absent"], default="present" |
| 913 |
), |
| 914 |
) |
| 915 |
|
| 916 |
|
| 917 |
def main(): |
| 918 |
"""Create PowerFlex Snapshot object and perform actions on it |
| 919 |
based on user input from playbook""" |
| 920 |
obj = PowerFlexSnapshotV2() |
| 921 |
obj.perform_module_operation() |
| 922 |
|
| 923 |
|
| 924 |
if __name__ == "__main__": |
| 925 |
main() |