/
array_management.py
666 lines (542 loc) · 25.3 KB
/
array_management.py
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# --------------------------------------------------------------------------
"""
File for performing IntelliSnap and Array Management operations on Commcell via REST API
ArrayManagement: Class for handling all Array Management Operations
ArrayManagement:
__init__() -- initialize instance of the ArrayManagement class
_snap_operation() -- Common Method for Snap Operations
mount() -- Method for mount operation
unmount() -- Method for unmount operation
delete() -- Method for delete operation
force_delete() -- Method for force delete operation
revert() -- Method for revert operation
reconcile() -- Method for recon operation
add_array() -- Method to add array
delete_array() -- Method to delete array
edit_array() -- Method to Update Snap Configuration and Array Access Node MA
for the given Array
"""
from __future__ import unicode_literals
from .job import Job
from .exception import SDKException
import base64
class ArrayManagement(object):
"""Class for representing all the array management activities with the commcell."""
def __init__(self, commcell_object):
""" Initialize the ArrayManagement class instance for performing Snap related operations
Args:
commcell_object (object) -- instance of the Commcell class
Returns:
object - instance of the ArrayManagement class
"""
self._commcell_object = commcell_object
self._SNAP_OPS = self._commcell_object._services['SNAP_OPERATIONS']
self.storage_arrays = self._commcell_object._services['STORAGE_ARRAYS']
def _snap_operation(self,
operation,
volume_id=None,
client_name=None,
mountpath=None,
do_vssprotection=True,
control_host=None,
flags=None,
reconcile=False,
user_credentials=None,
server_name=None,
instance_details=None):
""" Common Method for Snap Operations
Args :
operation (int) -- snap Operation value
0- mount, 1-unmount, 2-delete, 3-revert
volume_id (list) -- volume id's of the snap backup job
client_name (str) -- name of the destination client, default: None
MountPath (str) -- MountPath for Snap operation, default: None
do_vssprotection (bool) -- Performs VSS protected snapshot mount
control_host (int) -- Control host for the Snap recon operation,
defaullt: None
flags (int) -- value to define when snap operation to be forced
1 - to force unmount
2 - to force delete
reconcile (bool) -- Uses Reconcile json if true
user_credentials (dict) -- dict containing userName of vcenter
eg: user_credentials = {"userName":"vcentername"}
server_name (str) -- vcenter name for mount operation
instance_details (dict) -- dict containing apptypeId, InstanceId, InstanceName
eg: instance_details = {
"apptypeId": 106,
"instanceId": 7,
"instanceName": "VMWare"
}
Return :
object : Job object of Snap Operation job
"""
if client_name is None:
client_id = 0
else:
client_id = int(self._commcell_object.clients.get(client_name).client_id)
if flags is None:
flags = 0
if user_credentials is None:
user_credentials = {}
server_name = ""
server_type = 0
instance_details = {}
else:
server_type = 1
if reconcile:
request_json = {
"reserveField": 0,
"doVSSProtection": 0,
"serverName": "",
"controlHostId": control_host,
"CopyId": 0,
"smArrayId": "",
"destClientId": 0,
"destPath": "",
"serverType": 0,
"operation": operation,
"userCredentials": {},
"scsiServer": {
"_type_": 3
}
}
else:
request_json = {
"reserveField": 0,
"serverType": 0,
"operation": operation,
"userCredentials": {},
"volumes": [],
"appId": instance_details
}
for i in range(len(volume_id)):
if i == 0:
request_json['volumes'].append({'doVSSProtection': int(do_vssprotection),
'destClientId': client_id,
'destPath': mountpath,
'serverType': server_type,
'flags': flags,
'serverName': server_name,
'userCredentials': user_credentials,
'volumeId':int(volume_id[i][0]),
'CommCellId': self._commcell_object.commcell_id})
else:
request_json['volumes'].append({'volumeId':int(volume_id[i][0]),
'CommCellId': self._commcell_object.commcell_id})
flag, response = self._commcell_object._cvpysdk_object.make_request(
'POST', self._SNAP_OPS, request_json)
if flag:
if response.json():
if "jobId" in response.json():
return Job(self._commcell_object, response.json()['jobId'])
elif "errorCode" in response.json():
error_message = response.json()['errorMessage']
o_str = 'job for Snap Operation failed\nError: "{0}"'.format(error_message)
raise SDKException('Snap', '102', o_str)
else:
raise SDKException('Snap', '102')
def mount(self, volume_id, client_name, mountpath, do_vssprotection=True,
user_credentials=None, server_name=None, instance_details=None):
""" Mounts Snap of the given volume id
Args:
volume_id (int) -- volume id of the snap backup job
client_name (str) -- name of the destination client, default: None
MountPath (str) -- MountPath for Snap operation, default: None
do_vssprotection (int) -- Performs VSS protected mount
user_credentials (dict) -- dict containing userName of vcenter
server_name (str) -- vcenter name for mount operation
instance_details (dict) -- dict containing apptypeId, InstanceId, InstanceName
"""
return self._snap_operation(0, volume_id,
client_name,
mountpath,
do_vssprotection,
user_credentials=user_credentials,
server_name=server_name,
instance_details=instance_details)
def unmount(self, volume_id):
""" UnMounts Snap of the given volume id
Args:
volume_id (int) -- volume id of the snap backup job
"""
return self._snap_operation(1, volume_id)
def force_unmount(self, volume_id):
""" Force UnMounts Snap of the given volume id
Args:
volume_id (int) -- volume id of the snap backup job
"""
return self._snap_operation(1, volume_id, flags=1)
def delete(self, volume_id):
""" Deletes Snap of the given volume id
Args:
volume_id (int) -- volume id of the snap backup job
"""
return self._snap_operation(2, volume_id)
def force_delete(self, volume_id):
""" Deletes Snap of the given volume id
Args:
volume_id (int) -- volume id of the snap backup job
"""
return self._snap_operation(2, volume_id, flags=2)
def revert(self, volume_id):
""" Reverts Snap of the given volume id
Args:
volume_id (int) -- volume id of the snap backup job
"""
return self._snap_operation(3, volume_id)
def reconcile(self, control_host):
""" Runs Reconcile Snap of the given control host id
Args:
control_host (int) -- control host id of the array
"""
return self._snap_operation(7, control_host=control_host, reconcile=True)
def add_array(self,
vendor_name,
array_name,
username,
password,
vendor_id,
config_data,
control_host=None,
array_access_node=None,
is_ocum=False):
"""This method will help in adding array entry in the array management
Args :
vendor_name (str) -- vendor name
array_name (str) -- name of the array
username (str) -- username of the array
password (str) -- password to access array
vendor_id (int) -- vendor id of the array
config_data (list) -- SNap configs list to be updated
control_host (str) -- control host of the array
array_access_node (list) -- Array Access Node MediaAgent's Name list
is_ocum (bool) -- used for netapp to specify whether
to use Primary file server or OCUM
Return :
errorMessage (string) : Error message
"""
snap_configs = {}
assocType = 0
if config_data is not None:
assocType = 3
request_json_service = self.storage_arrays + '/Vendors/{0}'.format(vendor_id)
flag, snap_configs = self._commcell_object._cvpysdk_object.make_request(
'GET', request_json_service
)
snap_configs = snap_configs.json()
for m_config, value in config_data.items():
for config in snap_configs['configs']['configList']:
if int(config['masterConfigId']) == int(m_config):
config['value'] = str(value)
else:
snap_configs['configs'] = {}
selectedMAs = []
if array_access_node is not None:
for node in array_access_node:
client_id = int(self._commcell_object.clients.get(node).client_id)
node_dict = {
"arrayControllerId":0,
"mediaAgent":{
"name": node,
"id": client_id
},
"arrCtrlOptions":[
{
"isEnabled": True,
"arrCtrlOption":{
"name":"Pruning",
"id": 262144
}
}
]
}
selectedMAs.append(node_dict)
if password is not None:
password = base64.encodebytes(password.encode()).decode()
request_json = {
"clientId": 0,
"flags": 0,
"assocType": assocType,
"copyId": 0,
"appId": 0,
"selectedMAs":selectedMAs,
"hostDG": {
"doNotMoveDevices": True,
"isOverridden": False,
"hostDGName": "",
"useOnlySpouseDevices": False,
"flags": 0,
"deviceGroupOption": 0
},
"arrayDG": {
"isOverridden": False,
"arrayDGName": "",
"flags": 0,
"disableDG": False,
"useDevicesFromThisDG": False
},
"configs": snap_configs['configs'],
"array": {
"name": "",
"id": 0
},
"vendor": {
"name": "",
"id": 0
},
"info": {
"passwordEdit": False,
"offlineReason": "",
"arrayType": 0,
"flags": 0,
"description": "",
"ctrlHostName": control_host,
"offlineCode": 0,
"isEnabled": True,
"arrayInfoType": 0,
"uniqueIdentifier": "",
"securityAssociations": {
"processHiddenPermission": 0
},
"userPswd": {
"userName": username,
"password": password,
},
"arraySecurity": {},
"arrayName": {
"name": array_name,
"id": 0
},
"vendor": {
"name": vendor_name,
"id": 0
},
"client": {
"name": "",
"id": 0
}
}
}
array_type_dict1 = {
"info": {
"arrayType": 2
}
}
array_type_dict2 = {
"info": {
"arrayType": 1
}
}
array_type_dict3 = {
"info": {
"arrayType": 0
}
}
if vendor_name == "NetApp":
request_json["info"].update(array_type_dict1["info"]),
if vendor_name == "NetApp" and is_ocum:
request_json["info"].update(array_type_dict2["info"]),
else:
request_json["info"].update(array_type_dict3["info"]),
flag, response = self._commcell_object._cvpysdk_object.make_request(
'POST', self.storage_arrays, request_json
)
if response.json() and 'errorCode' in response.json():
error_code = response.json()['errorCode']
error_message = response.json()['errorMessage']
if error_code != 0:
if error_code in [1, 10]:
raise SDKException('StorageArray', '101')
error_message = response.json().get('errorMessage', '')
o_str = 'Error: "{0}"'.format(error_message)
raise SDKException('StorageArray', '102', o_str)
return error_message
else:
raise SDKException('StorageArray', '102')
def delete_array(self, control_host_array):
"""This method Deletes an array from the array management
Args :
control_host_array (str) -- Control Host id of the array
Return :
errorMessage (str) -- Error message after the execution
"""
storagearrays_delete_service = self.storage_arrays + '/{0}'.format(control_host_array)
flag, response = self._commcell_object._cvpysdk_object.make_request(
'DELETE', storagearrays_delete_service
)
if response.json():
error_code = response.json()['errorCode']
error_message = response.json()['errorMessage']
if error_code != 0:
raise SDKException('StorageArray', '103', error_message)
return error_message
def edit_array(self,
control_host_id,
config_data,
config_update_level,
level_id,
array_access_node):
"""Method to Update Snap Configuration and Array access nodes for the given Array
Args:
control_host_id (int) -- Control Host Id of the Array
Config_data (dict) -- Master config Id and the config value in dict format
config_update_level (str) -- update level for the Snap config
ex: "array", "subclient", "copy", "client"
level_id (int) -- level Id where the config needs to be
added/updated
array_access_node (dict) -- Array Access Node MA's in dict format with
operation mode
default: None
Ex: {"snapautotest3" : "add", "linuxautomation1" : "add", "snapautofc1" : "delete"}
"""
copy_level_id = app_level_id = client_level_id = 0
if config_update_level == "array":
config_update_level = 3
request_json_service = self.storage_arrays + '/{0}'.format(control_host_id)
elif config_update_level == "copy":
config_update_level = 6
copy_level_id = level_id
request_json_service = self.storage_arrays + '/{0}?copyId={1}&assocType={2}'.format(
control_host_id, copy_level_id, config_update_level)
elif config_update_level == "subclient":
config_update_level = 9
app_level_id = level_id
request_json_service = self.storage_arrays + '/{0}?appId={1}&assocType={2}'.format(
control_host_id, app_level_id, config_update_level)
elif config_update_level == "client":
config_update_level = 8
client_level_id = level_id
request_json_service = self.storage_arrays + '/{0}?clientId={1}&assocType={2}'.format(
control_host_id, client_level_id, config_update_level)
else:
config_update_level = 3
request_json_service = self.storage_arrays + '/{0}'.format(control_host_id)
flag, request_json = self._commcell_object._cvpysdk_object.make_request(
'GET', request_json_service)
request_json = request_json.json()
update_dict = {
"add": False,
"forceAdd": False,
"assocType": config_update_level,
"copyId": copy_level_id,
"appId": app_level_id,
"clientId": client_level_id
}
request_json.update(update_dict)
if config_data is not None:
for m_config, value in config_data.items():
for config in request_json['configList']['configList']:
if config['masterConfigId'] == int(m_config):
if isinstance(value, dict):
for alias, mode in value.items():
if mode == "add":
config_values_dict = {
"name": str(alias),
"id": 0
}
aliasPresent = False
for alias_name in config['values']:
if alias_name['name'] == alias:
aliasPresent = True
if not aliasPresent:
config['values'].append(config_values_dict)
if mode != "add" and mode != "delete":
for alias_name in config['values']:
if alias_name['name'] == mode:
alias_name['name'] = alias
if mode == "delete":
for alias_name in range(len(config['values'])):
if config['values'][alias_name]['name'] == alias:
del config['values'][alias_name]
break
if config_update_level != "array":
config['isOverridden'] = True
else:
config['value'] = str(value)
if config_update_level != "array":
config['isOverridden'] = True
if array_access_node is not None:
for access_node, mode in array_access_node.items():
client_id = int(self._commcell_object.clients.get(access_node).client_id)
if mode == "add":
if "selectedMAs" in request_json:
update_dict = {
"arrayControllerId": 0,
"mediaAgent": {
"name": access_node,
"id": client_id
},
"arrCtrlOptions": [
{
"isEnabled": True,
"arrCtrlOption": {
"name": "Pruning",
"id": 262144
}
}
]
}
isNodePresent = False
for nodes in request_json['selectedMAs']:
if nodes['mediaAgent']['id'] == int(client_id):
isNodePresent = True
if not isNodePresent:
request_json['selectedMAs'].append(update_dict)
else:
update_dict = {
"selectedMAs": [
{
"arrayControllerId": 0,
"mediaAgent": {
"name": access_node,
"id": client_id
},
"arrCtrlOptions": [
{
"isEnabled": True,
"arrCtrlOption": {
"name": "Pruning",
"id": 262144
}
}
]
}
]}
request_json.update(update_dict)
elif mode == "delete":
client_id = int(self._commcell_object.clients.get(access_node).client_id)
if "selectedMAs" in request_json:
for controller in range(len(request_json['selectedMAs'])):
if request_json['selectedMAs'][controller]['mediaAgent']['id'] == int(client_id):
del request_json['selectedMAs'][controller]
break
request_json['configs'] = request_json.pop('configList')
del request_json['info']['region']
flag, response = self._commcell_object._cvpysdk_object.make_request(
'PUT', self.storage_arrays, request_json
)
if response.json() and 'errorCode' in response.json():
error_code = response.json()['errorCode']
if error_code != 0:
if error_code == 1:
raise SDKException('StorageArray', '101')
error_message = response.json().get('errorMessage', '')
o_str = 'Failed to update Snap Configs\nError: "{0}"'.format(error_message)
raise SDKException('StorageArray', '103', o_str)
else:
raise SDKException('StorageArray', '103')