1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name,use-dict-literal,too-many-branches,too-many-locals,line-too-long,wrong-import-position
""" A module for managing Infinibox volumes """
# Copyright: (c) 2024, Infinidat <info@infinidat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r"""
---
module: infini_vol
version_added: '2.3.0'
short_description: Create, Delete or Modify volumes on Infinibox
description:
- This module creates, deletes or modifies a volume on Infinibox.
author: David Ohlemacher (@ohlemacher)
options:
name:
description:
- Volume name.
type: str
required: false
serial:
description:
- Volume serial number.
type: str
required: false
parent_volume_name:
description:
- Specify a volume name. This is the volume parent for creating a snapshot. Required if volume_type is snapshot.
type: str
required: false
pool:
description:
- Pool that master volume will reside within. Required for creating a master volume, but not a snapshot.
type: str
required: false
size:
description:
- Volume size in MB, GB or TB units. Required for creating a master volume, but not a snapshot
type: str
required: false
snapshot_lock_expires_at:
description:
- This will cause a snapshot to be locked at the specified date-time.
Uses python's datetime format YYYY-mm-dd HH:MM:SS.ffffff, e.g. 2020-02-13 16:21:59.699700
type: str
required: false
snapshot_lock_only:
description:
- This will lock an existing snapshot but will suppress refreshing the snapshot.
type: bool
required: false
default: false
state:
description:
- Creates/Modifies master volume or snapshot when present or removes when absent.
type: str
required: false
default: present
choices: [ "stat", "present", "absent" ]
thin_provision:
description:
- Whether the master volume should be thin or thick provisioned.
type: bool
required: false
default: true
write_protected:
description:
- Specifies if the volume should be write protected. Default will be True for snapshots, False for regular volumes.
type: str
required: false
default: "Default"
choices: ["Default", "True", "False"]
volume_type:
description:
- Specifies the volume type, regular volume or snapshot.
type: str
required: false
default: master
choices: [ "master", "snapshot" ]
restore_volume_from_snapshot:
description:
- Specify true to restore a volume (parent_volume_name) from an existing snapshot specified by the name field.
- State must be set to present and volume_type must be 'snapshot'.
type: bool
required: false
default: false
extends_documentation_fragment:
- infinibox
requirements:
- capacity
"""
EXAMPLES = r"""
- name: Create new volume named foo under pool named bar
infini_vol:
name: foo
# volume_type: master # Default
size: 1TB
thin_provision: true
pool: bar
state: present
user: admin
password: secret
system: ibox001
- name: Create snapshot named foo_snap from volume named foo
infini_vol:
name: foo_snap
volume_type: snapshot
parent_volume_name: foo
state: present
user: admin
password: secret
system: ibox001
- name: Stat snapshot, also a volume, named foo_snap
infini_vol:
name: foo_snap
state: present
user: admin
password: secret
system: ibox001
- name: Remove snapshot, also a volume, named foo_snap
infini_vol:
name: foo_snap
state: absent
user: admin
password: secret
system: ibox001
"""
# RETURN = r''' # '''
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible_collections.infinidat.infinibox.plugins.module_utils.infinibox import (
HAS_INFINISDK,
api_wrapper,
check_snapshot_lock_options,
get_pool,
get_system,
get_vol_by_sn,
get_volume,
infinibox_argument_spec,
manage_snapshot_locks,
)
HAS_INFINISDK = True
try:
from infinisdk.core.exceptions import APICommandFailed
from infinisdk.core.exceptions import ObjectNotFound
except ImportError:
HAS_INFINISDK = False
HAS_CAPACITY = True
try:
from capacity import KiB, Capacity
except ImportError:
HAS_CAPACITY = False
@api_wrapper
def create_volume(module, system):
""" Create Volume """
changed = False
if not module.check_mode:
if module.params["thin_provision"]:
prov_type = "THIN"
else:
prov_type = "THICK"
pool = get_pool(module, system)
volume = system.volumes.create(
name=module.params["name"], provtype=prov_type, pool=pool
)
if module.params["size"]:
size = Capacity(module.params["size"]).roundup(64 * KiB)
volume.update_size(size)
if module.params["write_protected"] is not None:
is_write_prot = volume.is_write_protected()
desired_is_write_prot = module.params["write_protected"]
if is_write_prot != desired_is_write_prot:
volume.update_field("write_protected", desired_is_write_prot)
changed = True
return changed
@api_wrapper
def find_vol_id(module, system, vol_name):
""" Find the ID of this vol """
vol_url = f"volumes?name={vol_name}&fields=id"
vol = system.api.get(path=vol_url)
result = vol.get_json()["result"]
if len(result) != 1:
module.fail_json(f"Cannot find a volume with name '{vol_name}'")
vol_id = result[0]["id"]
return vol_id
@api_wrapper
def restore_volume_from_snapshot(module, system):
""" Use snapshot to restore a volume """
changed = False
is_restoring = module.params["restore_volume_from_snapshot"]
volume_type = module.params["volume_type"]
snap_name = module.params["name"]
snap_id = find_vol_id(module, system, snap_name)
parent_volume_name = module.params["parent_volume_name"]
parent_volume_id = find_vol_id(module, system, parent_volume_name)
# Check params
if not is_restoring:
raise AssertionError("A programming error occurred. is_restoring is not True")
if volume_type != "snapshot":
module.exit_json(msg="Cannot restore a parent volume from snapshot unless the volume type is 'snapshot'")
if not parent_volume_name:
module.exit_json(msg="Cannot restore a parent volume from snapshot unless the parent volume name is specified")
if not module.check_mode:
restore_url = f"volumes/{parent_volume_id}/restore?approved=true"
restore_data = {
"source_id": snap_id,
}
try:
system.api.post(path=restore_url, data=restore_data)
changed = True
except APICommandFailed as err:
module.fail_json(msg=f"Cannot restore volume {parent_volume_name} from {snap_name}: {err}")
return changed
@api_wrapper
def update_volume(module, volume):
""" Update Volume """
changed = False
if module.check_mode:
return changed
if module.params["size"]:
size = Capacity(module.params["size"]).roundup(64 * KiB)
if volume.get_size() != size:
volume.update_size(size)
changed = True
if module.params["thin_provision"] is not None:
provisioning = str(volume.get_provisioning())
if provisioning == "THICK" and module.params["thin_provision"]:
volume.update_provisioning("THIN")
changed = True
if provisioning == "THIN" and not module.params["thin_provision"]:
volume.update_provisioning("THICK")
changed = True
if module.params["write_protected"] is not None:
is_write_prot = volume.is_write_protected()
desired_is_write_prot = module.params["write_protected"]
if is_write_prot != desired_is_write_prot:
volume.update_field("write_protected", desired_is_write_prot)
changed = True
return changed
@api_wrapper
def delete_volume(module, volume):
""" Delete Volume. Volume could be a snapshot. """
changed = False
if not module.check_mode:
volume.delete()
changed = True
return changed
@api_wrapper
def create_snapshot(module, system):
"""Create Snapshot from parent volume"""
snapshot_name = module.params["name"]
parent_volume_name = module.params["parent_volume_name"]
try:
parent_volume = system.volumes.get(name=parent_volume_name)
except ObjectNotFound:
msg = f"Cannot create snapshot {snapshot_name}. Parent volume {parent_volume_name} not found"
module.fail_json(msg=msg)
if not parent_volume:
msg = f"Cannot find new snapshot's parent volume named {parent_volume_name}"
module.fail_json(msg=msg)
if not module.check_mode:
if module.params["snapshot_lock_only"]:
msg = "Snapshot does not exist. Cannot comply with 'snapshot_lock_only: true'."
module.fail_json(msg=msg)
check_snapshot_lock_options(module)
snapshot = parent_volume.create_snapshot(name=snapshot_name)
if module.params["write_protected"] is not None:
is_write_prot = snapshot.is_write_protected()
desired_is_write_prot = module.params["write_protected"]
if is_write_prot != desired_is_write_prot:
snapshot.update_field("write_protected", desired_is_write_prot)
manage_snapshot_locks(module, snapshot)
changed = True
return changed
@api_wrapper
def update_snapshot(module, snapshot):
""" Update/refresh snapshot. May also lock it. """
refresh_changed = False
if not module.params["snapshot_lock_only"]:
snap_is_locked = snapshot.get_lock_state() == "LOCKED"
if not snap_is_locked:
if not module.check_mode:
snapshot.refresh_snapshot()
refresh_changed = True
else:
msg = "Snapshot is locked and may not be refreshed"
module.fail_json(msg=msg)
check_snapshot_lock_options(module)
lock_changed = manage_snapshot_locks(module, snapshot)
if not module.check_mode:
if module.params["write_protected"] is not None:
is_write_prot = snapshot.is_write_protected()
desired_is_write_prot = module.params["write_protected"]
if is_write_prot != desired_is_write_prot:
snapshot.update_field("write_protected", desired_is_write_prot)
return refresh_changed or lock_changed
def handle_stat(module):
""" Handle the stat state """
system = get_system(module)
if module.params['name']:
volume = get_volume(module, system)
else:
volume = get_vol_by_sn(module, system)
if not volume:
msg = f"Volume {module.params['name']} not found. Cannot stat."
module.fail_json(msg=msg)
fields = volume.get_fields() # from_cache=True, raw_value=True)
created_at = str(fields.get("created_at", None))
has_children = fields.get("has_children", None)
lock_expires_at = str(volume.get_lock_expires_at())
lock_state = volume.get_lock_state()
mapped = str(fields.get("mapped", None))
name = fields.get("name", None)
parent_id = fields.get("parent_id", None)
provisioning = fields.get("provisioning", None)
serial = str(volume.get_serial())
size = str(volume.get_size())
updated_at = str(fields.get("updated_at", None))
used = str(fields.get("used_size", None))
volume_id = fields.get("id", None)
volume_type = fields.get("type", None)
write_protected = fields.get("write_protected", None)
if volume_type == "SNAPSHOT":
msg = "Volume snapshot stat found"
else:
msg = "Volume stat found"
result = dict(
changed=False,
name=name,
created_at=created_at,
has_children=has_children,
lock_expires_at=lock_expires_at,
lock_state=lock_state,
mapped=mapped,
msg=msg,
parent_id=parent_id,
provisioning=provisioning,
serial=serial,
size=size,
updated_at=updated_at,
used=used,
volume_id=volume_id,
volume_type=volume_type,
write_protected=write_protected,
)
module.exit_json(**result)
def handle_present(module):
""" Handle the present state """
system = get_system(module)
if module.params["name"]:
volume = get_volume(module, system)
else:
volume = get_vol_by_sn(module, system)
volume_type = module.params["volume_type"]
is_restoring = module.params["restore_volume_from_snapshot"]
if volume_type == "master":
if not volume:
changed = create_volume(module, system)
module.exit_json(changed=changed, msg="Volume created")
else:
changed = update_volume(module, volume)
if changed:
msg = "Volume updated"
else:
msg = "Volume present. No changes were required"
module.exit_json(changed=changed, msg=msg)
elif volume_type == "snapshot":
snapshot = volume
if is_restoring:
# Restore volume from snapshot
changed = restore_volume_from_snapshot(module, system)
module.exit_json(changed=changed, msg="Volume restored from snapshot")
else:
if not snapshot:
changed = create_snapshot(module, system)
module.exit_json(changed=changed, msg="Snapshot created")
else:
changed = update_snapshot(module, snapshot)
module.exit_json(changed=changed, msg="Snapshot updated")
else:
module.fail_json(msg="A programming error has occurred")
def handle_absent(module):
""" Handle the absent state """
system = get_system(module)
if module.params["name"]:
volume = get_volume(module, system)
else:
volume = get_vol_by_sn(module, system)
volume_type = module.params["volume_type"]
if volume and volume.get_lock_state() == "LOCKED":
msg = "Cannot delete snapshot. Locked."
module.fail_json(msg=msg)
if volume_type == "master":
if not volume:
module.exit_json(changed=False, msg="Volume already absent")
else:
changed = delete_volume(module, volume)
module.exit_json(changed=changed, msg="Volume removed")
elif volume_type == "snapshot":
snapshot = volume
if not snapshot:
module.exit_json(changed=False, msg="Snapshot already absent")
else:
changed = delete_volume(module, snapshot)
module.exit_json(changed=changed, msg="Snapshot removed")
else:
module.fail_json(msg="A programming error has occured")
def execute_state(module):
""" Handle each state. Handle different write_protected defaults depending on volume_type. """
if module.params["volume_type"] == "snapshot":
if module.params["write_protected"] in ["True", "true", "Default"]:
module.params["write_protected"] = True
else:
module.params["write_protected"] = False
elif module.params["volume_type"] == "master":
if module.params["write_protected"] in ["False", "false", "Default"]:
module.params["write_protected"] = False
else:
module.params["write_protected"] = True
else:
msg = f"An error has occurred handling volume_type {module.params['volume_type']} or write_protected {module.params['write_protected']} values"
module.fail_json(msg)
state = module.params["state"]
try:
if state == "stat":
handle_stat(module)
elif state == "present":
handle_present(module)
elif state == "absent":
handle_absent(module)
else:
module.fail_json(msg=f"Internal handler error. Invalid state: {state}")
finally:
system = get_system(module)
system.logout()
def check_options(module):
"""Verify module options are sane"""
name = module.params["name"]
serial = module.params["serial"]
state = module.params["state"]
size = module.params["size"]
pool = module.params["pool"]
volume_type = module.params["volume_type"]
parent_volume_name = module.params["parent_volume_name"]
if state == "stat":
if not name and not serial:
msg = "Name or serial parameter must be provided"
module.fail_json(msg)
if state in ["present", "absent"]:
if not name:
msg = "Name parameter must be provided"
module.fail_json(msg=msg)
if state == "present":
if volume_type == "master":
if parent_volume_name:
msg = "parent_volume_name should not be specified "
msg += "if volume_type is 'master'. Used for snapshots only."
module.fail_json(msg=msg)
if not size:
msg = "Size is required to create a volume"
module.fail_json(msg=msg)
elif volume_type == "snapshot":
if size or pool:
msg = "Neither pool nor size should not be specified "
msg += "for volume_type snapshot"
module.fail_json(msg=msg)
if state == "present":
if not parent_volume_name:
msg = "For state 'present' and volume_type 'snapshot', "
msg += "parent_volume_name is required"
module.fail_json(msg=msg)
else:
msg = "A programming error has occurred"
module.fail_json(msg=msg)
if not pool and volume_type == "master":
msg = "For state 'present', pool is required"
module.fail_json(msg=msg)
def main():
""" Main """
argument_spec = infinibox_argument_spec()
argument_spec.update(
dict(
name=dict(required=False, default=None),
parent_volume_name=dict(default=None, required=False, type="str"),
pool=dict(required=False),
restore_volume_from_snapshot=dict(default=False, type="bool"),
serial=dict(required=False, default=None),
size=dict(required=False, default=None),
snapshot_lock_expires_at=dict(),
snapshot_lock_only=dict(default=False, type="bool"),
state=dict(default="present", choices=["stat", "present", "absent"]),
thin_provision=dict(type="bool", default=True),
volume_type=dict(default="master", choices=["master", "snapshot"]),
write_protected=dict(default="Default", choices=["Default", "True", "False"]),
)
)
module = AnsibleModule(argument_spec, supports_check_mode=True)
if not HAS_INFINISDK:
module.fail_json(msg=missing_required_lib("infinisdk"))
if not HAS_CAPACITY:
module.fail_json(msg=missing_required_lib("capacity"))
if module.params["size"]:
try:
Capacity(module.params["size"])
except Exception: # pylint: disable=broad-exception-caught
module.fail_json(msg="size (Physical Capacity) should be defined in MB, GB, TB or PB units")
check_options(module)
execute_state(module)
if __name__ == "__main__":
main()
|