-
Notifications
You must be signed in to change notification settings - Fork 42
/
vssubclient.py
2976 lines (2412 loc) · 126 KB
/
vssubclient.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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- 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 operating on a Virtual Server Subclient.
VirualServerSubclient is the only class defined in this file.
VirtualServerSubclient: Derived class from the Subclient Base class, representing a
virtual server subclient, and to perform operations
on that subclient
VirtualServerSubclient:
__get_subclient_properties() -- gets the subclient related
properties of VSA subclient.
_get_subclient_properties_json() -- gets all the subclient related
properties of VSA subclient.
_get_vm_ids_and_names_dict() -- creates and returns 2 dictionaries,
along with the vm path
_parse_vm_path() -- parses the path provided by user,
and replaces the VM Display Name with
the VM ID
_json_restore_virtualServerRstOption -- setter for Virtualserver
property in restore
_json_restore_diskLevelVMRestoreOption -- setter for diskLevel restore
property in restore
_json_restore_advancedRestoreOptions -- setter for advanced restore
property in restore
_json_restore_volumeRstOption -- setter for Volume restore
property in restore
_json_vcenter_instance -- setter for vcenter instance
json in restore
_json_nics_advancedRestoreOptions -- Setter for nics list for
advanced restore option json
_process_vsa_browse_response() -- processes the browse response
received from server,and
replaces the vm id with the vm
name
_process_restore_request() -- processes the Restore Request
and replaces the VM
display name with their ID
before passing to the API
_get_disk_Extension() -- Gets the Extension of disk
provided
_get_conversion_disk_Type() -- For source Disk gets the Disk
that can be converted to and
set its destination Vendor
_prepare_filelevel_restore_json() -- internal Method can be used by
subclasses for file level
restore Json
_prepare_disk_restore_json -- internal Method can be used by
subclasses for disk level
restore Json
_check_folder_in_browse -- Internal Method to check folder
is in browse from subclient
browse() -- gets the content of the backup
for this subclient at the vm
path specified
parse_nics_xml() -- gets the list of nics for a VM
get_nics_from_browse() -- Browses the vm to get the nics
info xml, gets the nics info
using the parse_nics_xml method
and prepares the dict for nics
json
disk_level_browse() -- browses the Disks of a Virtual
Machine
guest_files_browse() -- browses the Files and Folders
inside a Virtual Machine
vm_files_browse() -- browses the Files and Folders
of a Virtual Machine
vm_files_browse_in_time() -- browses the Files and Folders
of a Virtual Machine in the time
range specified
restore_out_of_place() -- restores the VM Guest Files
specified in the paths list to
the client, at the
specified destionation location
full_vm_restore_in_place() -- restores the VM specified by the
user to the same location
_full_vm_restore_update_json_for_v2 -- modifies the restore json as per v2
subclient details and returns it
backup() -- run a backup job for the subclient
_advanced_backup_options() -- sets the advanced backup options
update_properties() -- child method to add vsa specific properties to update properties
To add a new Virtual Subclient, create a class in a new module under virtualserver sub package
The new module which is created has to named in the following manner:
1. Name the module with the name of the Virtual Server without special characters
2.Spaces alone must be replaced with underscores('_')
For eg:
The Virtual Server 'Red Hat Virtualization' is named as 'red_hat_virtualization.py'
The Virtual Server 'Hyper-V' is named as 'hyperv.py'
"""
import os
import re
from enum import Enum
import copy
import xml.etree.ElementTree as ET
from importlib import import_module
from inspect import getmembers, isclass, isabstract
import xmltodict
from cvpysdk.plan import Plans
from ..exception import SDKException
from ..subclient import Subclient
from ..constants import VSAObjects, HypervisorType
class VirtualServerSubclient(Subclient):
"""Derived class from Subclient Base class, representing a virtual server subclient,
and to perform operations on that subclient."""
def __new__(cls, backupset_object, subclient_name, subclient_id=None):
"""Decides which instance object needs to be created"""
instance_name = backupset_object._instance_object.instance_name
instance_name = re.sub('[^A-Za-z0-9_]+', '', instance_name.replace(" ", "_"))
try:
subclient_module = import_module("cvpysdk.subclients.virtualserver.{}".format(instance_name))
except ImportError:
subclient_module = import_module("cvpysdk.subclients.virtualserver.null")
classes = getmembers(subclient_module, lambda m: isclass(m) and not isabstract(m))
for name, _class in classes:
if issubclass(_class, VirtualServerSubclient) and _class.__module__.rsplit(".", 1)[-1] == instance_name:
return object.__new__(_class)
def __init__(self, backupset_object, subclient_name, subclient_id=None):
"""Initialize the Instance object for the given Virtual Server instance.
Args:
backupset_object (object) -- instance of the backupset class
subclient_name (str) -- subclient name
subclient_id (int) -- subclient id
"""
super(VirtualServerSubclient, self).__init__(
backupset_object, subclient_name, subclient_id
)
self.content_types = {
'1': 'Host',
'2': 'Resource Pool',
'4': 'Datacenter',
'9': 'Virtual Machine',
'16': 'UnprotectedVMs',
'17': 'Root',
'34': 'Tag',
'35': 'TagCategory'
}
self.filter_types = {
'1': 'Datastore',
'2': 'Virtual Disk Name/Pattern',
'3': 'Virtual Device Node',
'4': 'Container',
'5': 'Disk Label',
'6': 'Disk Type',
'9': 'Disk Tag Name/Value',
'10':'Repository'
}
self._disk_option = {
'original': 0,
'thicklazyzero': 1,
'thin': 2,
'thickeagerzero': 3
}
self._transport_mode = {
'auto': 0,
'san': 1,
'hotadd': 2,
'nbd': 5,
'nbdssl': 4
}
self._vm_names_browse = []
self._vm_ids_browse = {}
self._advanced_restore_option_list = []
self._live_sync = None
class disk_pattern(Enum):
"""
stores the disk pattern of all hypervisors
"""
name = "name"
datastore = "Datastore"
new_name = "newName"
@property
def content(self):
"""Gets the appropriate content from the Subclient relevant to the user.
Returns:
list - list of content associated with the subclient
"""
content = []
subclient_content = self._vmContent
if 'children' in subclient_content:
children = subclient_content['children']
content = self._get_content_list(children)
return content
@property
def subclient_proxy(self):
"""
Gets the List of proxies at the Subclient
Returns:
list (list) : Proxies at the subclient
"""
return self._get_subclient_proxies()
@property
def instance_proxy(self):
"""
Gets the proxy at instance level
Returns:
string (string) : Proxy at instane
"""
return self._proxyClient.get('clientName', None)
@property
def vm_filter(self):
"""Gets the appropriate filter from the Subclient relevant to the user.
Returns:
list - list of filter associated with the subclient
"""
vm_filter = []
if self._vmFilter:
subclient_filter = self._vmFilter
if 'children' in subclient_filter:
children = subclient_filter['children']
vm_filter = self._get_content_list(children)
return vm_filter
@property
def vm_diskfilter(self):
"""Gets the appropriate Diskfilter from the Subclient relevant to the user.
Returns:
list - list of Diskfilter associated with the subclient
"""
vm_diskfilter = []
if self._vmDiskFilter is not None:
subclient_diskfilter = self._vmDiskFilter
if 'filters' in subclient_diskfilter:
filters = subclient_diskfilter['filters']
for child in filters:
filter_type_id = str(child['filterType'])
filter_type = self.filter_types[str(child['filterType'])]
vm_id = child['vmGuid'] if 'vmGuid' in child else None
filter_name = child['filter']
value = child['value']
temp_dict = {
'filter': filter_name,
'filterType': filter_type,
'vmGuid': vm_id,
'filterTypeId': filter_type_id,
'value':value
}
vm_diskfilter.append(temp_dict)
else:
vm_diskfilter = self._vmDiskFilter
if len(vm_diskfilter) == 0:
vm_diskfilter = None
return vm_diskfilter
@property
def metadata(self):
"""
Get if collect files/metadata value for given subclient.
Returns status as True/False (string)
Default: False for subclient which doesnt have the property
"""
collectdetails = r'collectFileDetails'
if collectdetails in self._vsaSubclientProp:
vsasubclient_collect_details = self._vsaSubclientProp[collectdetails]
else:
vsasubclient_collect_details = False
return vsasubclient_collect_details
@content.setter
def content(self, subclient_content):
"""Creates the list of content JSON to pass to the API to add/update
content of a Virtual Server Subclient.
Args:
subclient_content (list) -- list of the content to add to the
subclient list should contain name and type
(like VSAObjects.VMName, VSAObjects.DATASTORE )
example:[
{
'type' : VSAObjects.VMNotes,
'display_name' : 'removed',
}
]
for Advance user:
where we need to have multiple constraints for a single
rule.
list should contain minimum 2 parameters (name, type,
true/False for equalsOrNotEquals) for a single
constraint
for power on/off, we need to specify one more
parameter i.e., true -on, false -off(as state variable)
example:
subclient_content = [{'allOrAnyChildren': True, 'content': [
{'equal_value': True, 'allOrAnyChildren': True, 'display_name': '*abc*', 'type': 'VMName'},
{'equal_value': False, 'allOrAnyChildren': True, 'display_name': 'xyz', 'type': 'VMName'}]},
{'allOrAnyChildren': False, 'content': [
{'equal_value': True, 'allOrAnyChildren': True, 'display_name': '*12*',
'type': 'VMName'},
{'equal_value': True, 'allOrAnyChildren': True, 'display_name': '*34*',
'type': 'VMName'}]}]
subclient_content = [
[
{
'type' : VSAObjects.VMName,
'display_name' : 'VM*'
}
],
[
{
'type' : VSAObjects.VMNotes,
'display_name' : 'removed',
},
{
'type' : VSAObjects.VMPowerState,
'state': 'false',
}
]
]
Returns:
list - list of the appropriate JSON for an agent to send to the
POST Subclient API
"""
content = []
try:
for entity in subclient_content:
virtual_server_dict = dict()
if not isinstance(entity, dict):
entity = {'content': entity}
elif 'content' not in entity:
entity = {'content': entity}
virtual_server_dict['allOrAnyChildren'] = entity.get('allOrAnyChildren', True)
virtual_server_dict['children'] = []
def add_childrens(item, multiple_rule=False):
"""
add contents in the hierarchy
Args:
item (dict) : content's current item to be added
multiple_rule (bool) : If multiple rule present or not
"""
temp = {
'allOrAnyChildren': item.get('allOrAnyChildren', True),
'equalsOrNotEquals': item.get('equal_value', True),
'name': item.get('name', ""),
'displayName': item.get('display_name', ''),
'path': '',
'type': item['type'] if (
isinstance(item['type'], int) or isinstance(item['type'], str)) else
item['type'].value
}
if item['type'] == VSAObjects.VMNotes:
temp['value'] = item['display_name']
temp['displayName'] = item['display_name']
temp['name'] = "Notes"
if (item['type'] ==
VSAObjects.VMPowerState and
item['state'] == 'true'):
temp['name'] = "PoweredState"
temp['value'] = "1"
temp['displayName'] = "Powered On"
if (item['type'] ==
VSAObjects.VMPowerState and
item['state'] == 'false'):
temp['name'] = "PoweredState"
temp['value'] = "0"
temp['displayName'] = "Powered Off"
if multiple_rule:
virtual_server_dict.get('children').append(temp)
else:
content.append(temp)
if not isinstance(entity, list):
entity = [entity]
if len(entity[0]['content']) == 1 or isinstance(entity[0]['content'], dict):
if isinstance(entity[0]['content'], list):
add_childrens(entity[0]['content'][0])
else:
add_childrens(entity[0]['content'])
else:
for items in entity:
for item in items['content']:
add_childrens(item, True)
content.append(virtual_server_dict)
except KeyError as err:
raise SDKException('Subclient', '102', '{} not given in content'.format(err))
vs_subclient_content = {
"children": content
}
self._set_subclient_properties("_vmContent", vs_subclient_content)
@vm_filter.setter
def vm_filter(self, subclient_filter):
"""Creates the list of Filter JSON to pass to the API to update the
VM_filter of a Virtual Server Subclient. i.e. it works in overwrite
mode
Args:
subclient_filter (list) -- list of the filter to add to the
subclient
Returns:
list - list of the appropriate JSON for an agent to send to the
POST Subclient API
"""
vm_filter = []
try:
for temp_dict in subclient_filter:
content_type_id = ""
for type_id, type_name in self.content_types.items():
if type_name == temp_dict['type']:
content_type_id = type_id
break
virtual_server_dict = {
'allOrAnyChildren': True,
'equalsOrNotEquals': temp_dict["equal_value"],
'name': temp_dict['id'],
'displayName': temp_dict['display_name'],
'path': temp_dict['path'],
'type': content_type_id
}
vm_filter.append(virtual_server_dict)
except KeyError as err:
raise SDKException('Subclient', '102',
'{} not given in content'.format(err))
vs_filter_content = {
"children": vm_filter
}
self._set_subclient_properties("_vmFilter", vs_filter_content)
@vm_diskfilter.setter
def vm_diskfilter(self, subclient_diskfilter):
"""Creates the list of Disk Filter JSON to pass to the API to update
the Disk_filter of a Virtual Server Subclient. i.e. it works in
overwrite mode
Args:
subclient_diskfilter (list) -- list of the Disk filter to add
to the subclient
Returns:
list - list of the appropriate JSON for an agent to send to
the POST Subclient API
"""
vm_diskfilter = []
try:
for temp_dict in subclient_diskfilter:
if temp_dict.get('filterTypeId'):
filter_type_id = temp_dict['filterTypeId']
else:
filter_type_id = \
list(filter(lambda x: self.filter_types[x].lower() == temp_dict['filtertype'].lower(),
self.filter_types))[
0]
virtual_server_dict = {
'filter': temp_dict['filter'],
'filterType': filter_type_id,
'vmGuid': temp_dict.get('vmGuid')
}
vm_diskfilter.append(virtual_server_dict)
except KeyError as err:
raise SDKException('Subclient', '102',
'{} not given in content'.format(err))
vs_diskfilter_content = {
"filters": vm_diskfilter
}
self._set_subclient_properties("_vmDiskFilter", vs_diskfilter_content)
@property
def live_sync(self):
"""Returns the instance of the VSALiveSync class"""
if not self._live_sync:
from .virtualserver.livesync.vsa_live_sync import VsaLiveSync
self._live_sync = VsaLiveSync(self)
return self._live_sync
def _get_disk_provisioning_value(self, provisioningType):
"""
Returns the provisioning code for the selected type
Args:
provisioningType (String) - Disk provisioning type
return: (int) - diskProvisionValue
"""
# Defaults to "original"
disk_provision_value = 0
provisioningType = provisioningType.replace(" ", "").lower()
if provisioningType in self._disk_option:
disk_provision_value = self._disk_option[provisioningType]
return disk_provision_value
@metadata.setter
def metadata(self, value=True):
"""
Set given value of collectFileDetails/metadata (True/false) on the subclient
Args:
value (str) True/False
"""
collectdetails = r'collectFileDetails'
if collectdetails in self._vsaSubclientProp:
self._set_subclient_properties("_vsaSubclientProp['collectFileDetails']", value)
@property
def cbtvalue(self):
"""
Get CBT value for given subclient.
Returns:
(Boolean) True/False
"""
return self._subclient_properties.get('vsaSubclientProp', {}).get("useChangedTrackingOnVM", False)
@cbtvalue.setter
def cbtvalue(self, value):
"""
Set CBT value for given subclient
Args:
value (Boolean) True/False
"""
update_properties = self.properties
update_properties["vsaSubclientProp"]['useChangedTrackingOnVM'] = value
self.update_properties(update_properties)
def update_properties(self, properties_dict):
"""
child method to add any specific attributes for vsa
Args:
properties_dict (dict): dict of all propterties of subclient
"""
properties_dict.update({
"vmFilterOperationType": "OVERWRITE",
"vmContentOperationType": "OVERWRITE",
"vmDiskFilterOperationType": "OVERWRITE"
})
super().update_properties(properties_dict)
def _get_content_list(self, children):
"""
Gets the content in list format
Args:
children (list): Content if the subclient
Returns:
content_list (list): Content of the subclient
"""
content_list = []
for child in children:
path = child['path'] if 'path' in child else None
allOrAnyChildren = child['allOrAnyChildren'] if 'allOrAnyChildren' in child else None
_temp_list = []
_temp_dict = {}
if 'children' in child:
nested_children = child['children']
for each_condition in nested_children:
display_name = each_condition['displayName']
content_type = VSAObjects(each_condition['type']).name
vm_id = each_condition['name']
temp_dict = {
'equal_value': each_condition['equalsOrNotEquals'],
'allOrAnyChildren': each_condition['allOrAnyChildren'],
'id': vm_id,
'path': path,
'display_name': display_name,
'type': content_type
}
_temp_list.append(temp_dict)
_temp_dict['allOrAnyChildren'] = allOrAnyChildren
_temp_dict['content'] = _temp_list
content_list.append(_temp_dict)
else:
display_name = child['displayName']
content_type = VSAObjects(child['type']).name
vm_id = child.get('name', '')
temp_dict = {
'equal_value': child['equalsOrNotEquals'],
'allOrAnyChildren': child.get('allOrAnyChildren', True),
'id': vm_id,
'path': path,
'display_name': display_name,
'type': content_type
}
content_list.append(temp_dict)
return content_list
def _get_subclient_properties(self):
"""Gets the subclient related properties of Virtual server subclient.
"""
self._vmDiskFilter = None
self._vmFilter = None
super(VirtualServerSubclient, self)._get_subclient_properties()
if 'vmContent' in self._subclient_properties:
self._vmContent = self._subclient_properties['vmContent']
if 'vmDiskFilter' in self._subclient_properties:
self._vmDiskFilter = self._subclient_properties['vmDiskFilter']
if 'vmFilter' in self._subclient_properties:
self._vmFilter = self._subclient_properties['vmFilter']
if 'vmBackupInfo' in self._subclient_properties:
self._vmBackupInfo = self._subclient_properties['vmBackupInfo']
if 'vsaSubclientProp' in self._subclient_properties:
self._vsaSubclientProp = self._subclient_properties['vsaSubclientProp']
def _get_subclient_content_(self):
"""
Returns the subclient content from property. Base class Abstract method
implementation
return:
VM content (dict) -- Dictionary of VM Content with all details
"""
return self.content
def _get_subclient_properties_json(self):
"""get the all subclient related properties of this subclient.
Returns:
dict - all subclient properties put inside a dict
"""
subclient_json = {
"subClientProperties":
{
"vmContent": self._vmContent,
"proxyClient": self._proxyClient,
"subClientEntity": self._subClientEntity,
"vmDiskFilter": self._vmDiskFilter,
"vmFilter": self._vmFilter,
"vmBackupInfo": self._vmBackupInfo,
"vsaSubclientProp": self._vsaSubclientProp,
# "content": self._content,
"commonProperties": self._commonProperties,
"vmContentOperationType": 1,
"vmDiskFilterOperationType": 1,
"vmFilterOperationType": 1
}
}
return subclient_json
def _disk_dict_pattern(self, name, datastore, new_name=None):
"""
set the disk dictionary of the hypervisor
Args:
name (str) -- name of the disk
datastore (str) -- datastore where the disk has to be restored
new_name (str) -- new name of the disk
Returns:
disk dictionary(dict) -- Dictionary with key name, new name , datastore
and corresponding
"""
if not new_name and not self._instance_object.instance_name == HypervisorType.GOOGLE_CLOUD.value.lower():
new_name = name
temp_disk_dict = {}
temp_disk_dict[self.disk_pattern.name.value] = name
temp_disk_dict[self.disk_pattern.datastore.value] = datastore
temp_disk_dict[self.disk_pattern.new_name.value] = new_name
return temp_disk_dict
def _json_vcenter_instance(self, value):
""" Setter for vcenter_instance JSON """
if not isinstance(value, dict):
raise SDKException('Subclient', '101')
self._virtualserver_option_restore_json["vCenterInstance"] = {
"clientName": value.get("destination_client_name", ""),
"instanceName": value.get("destination_instance", ""),
"appName": value.get("appName", "Virtual Server")
}
if value.get("destination_instance_id") and value.get("destination_client_id"):
self._virtualserver_option_restore_json["vCenterInstance"].update(
{"instanceId": value.get("destination_instance_id", 0),
"clientId": value.get("destination_client_id", 0)}
)
def _json_restore_virtualServerRstOption(self, value):
"""
setter for the Virtual server restore option in restore json
"""
if not isinstance(value, dict):
raise SDKException('Subclient', '101')
self._virtualserver_option_restore_json = {
"isDiskBrowse": value.get("disk_browse", True),
"isFileBrowse": value.get("file_browse", False),
"isVolumeBrowse": False,
"isVirtualLab": value.get("virtual_lab", False),
"esxServer": value.get("esx_server", ""),
"isAttachToNewVM": value.get("attach_to_new_vm", False),
"viewType": "DEFAULT",
"isBlockLevelReplication": value.get("block_level", False)
}
if value.get('replication_guid'):
self._virtualserver_option_restore_json['replicationGuid'] = value['replication_guid']
def _json_restore_virtualServerRstOption_filelevelrestoreoption(self, value):
"""
setter for the File level restore option for agent less restore option in restore json
"""
if not isinstance(value, dict):
raise SDKException('Subclient', '101')
return {
"serverName": value.get("server_name", ''),
"vmGuid": value.get("vm_guid", ''),
"vmName": value.get("vm_name", '')
}
def _json_restore_guest_password(self, value):
"""
setter for vm credentials for agentless restore option in restore json
"""
if not isinstance(value, dict):
raise SDKException('Subclient', '101')
return {
"userName": value.get("user_name", ''),
"password": value.get("password", '')
}
def _json_nics_advancedRestoreOptions(self, vm_to_restore, value):
"""
Setter for nics list for advanced restore option json
"""
nics_dict_from_browse = self.get_nics_from_browse(copy_precedence=value.get('copy_precedence', 0))
nics_list = []
vm_nics_list = nics_dict_from_browse[vm_to_restore]
for network_card_dict in vm_nics_list:
if self._instance_object.instance_name == HypervisorType.GOOGLE_CLOUD.value.lower():
current_project = network_card_dict.get('subnetId').split('/')[6]
if value.get('project_id') is not None:
network_card_dict['subnetId'] = value.get('subnetwork_nic')
network_card_dict['sourceNetwork'] = value.get('networks_nic')
_destnetwork = value.get("destination_network",
value.get('network',
network_card_dict['name']))
nics = {
"subnetId": network_card_dict.get('subnetId', ""),
"sourceNetwork": network_card_dict['name'],
"sourceNetworkId": network_card_dict.get('sourceNetwork', ""),
"name": (network_card_dict.get('sourceNetwork',
"") + _destnetwork) if self._instance_object.instance_name ==
HypervisorType.GOOGLE_CLOUD.value.lower() and _destnetwork else
network_card_dict['label'],
"networkName": _destnetwork if _destnetwork else '',
"destinationNetwork": _destnetwork if _destnetwork else network_card_dict['name']
}
# setting nics for azureRM instance
if value.get('destination_instance') == 'azure resource manager':
if "networkDisplayName" in value and 'networkrsg' in value and 'destsubid' in value:
nics["networkDisplayName"] = value["networkDisplayName"]
nics["networkName"] = value["networkDisplayName"].split('\\')[0]
modify_nics = value.get('subnetId', nics['subnetId']).split('/')
modify_nics[8] = nics["networkName"]
modify_nics[4] = value['networkrsg']
modify_nics[2] = value['destsubid']
modify_nics[10] = value["networkDisplayName"].split('\\')[1]
final_nics = ""
for each_info in modify_nics[1:]:
final_nics = final_nics + '/' + each_info
nics["subnetId"] = final_nics
name = ''
for each_info in modify_nics[1:9]:
name = name + '/' + each_info
nics["name"] = name
nics_list.append(nics)
return nics_list
def _json_vmip_advanced_restore_options(self, value):
"""
Setting IP for destination vm
"""
vmip = []
_asterisk = "*.*.*.*"
vm_ip = {
"sourceIP": value.get("source_ip"),
"sourceSubnet": value["source_subnet"] if value.get("source_subnet") else _asterisk,
"sourceGateway": value["source_gateway"] if value.get("source_gateway") else _asterisk,
"destinationIP": value.get("destination_ip"),
"destinationSubnet": value["destination_subnet"] if value.get("destination_subnet") else _asterisk,
"destinationGateway": value["destination_gateway"] if value.get("destination_gateway") else _asterisk,
"primaryDNS": value.get("primary_dns", ""),
"alternateDNS": value.get("alternate_dns", ""),
"primaryWins": value.get("primare_wins", ""),
"altenameWins": value.get("alternate_wins", ""),
"useDhcp": False
}
vmip.append(vm_ip)
return vmip
def _json_restore_diskLevelVMRestoreOption(self, value):
"""setter for the disk Level VM Restore Option in restore json"""
if not isinstance(value, dict):
raise SDKException('Subclient', '101')
vcenter_userpwd = ''
if 'vmware' in self._instance_object.instance_name:
vcenter_userpwd = self._instance_object._user_name
json_disklevel_option_restore = {
"esxServerName": value.get("esx_server", ""),
"vmFolderName": value.get("vm_folder", ""),
"dataCenterName": value.get("data_center", ""),
"hostOrCluster": value.get("host_cluster", ""),
"diskOption": value.get("disk_option", 0),
"vmName": "",
"transportMode": value.get("transport_mode", 0),
"passUnconditionalOverride": value.get("unconditional_overwrite", False),
"powerOnVmAfterRestore": value.get("power_on", False),
"registerWithFailoverCluster": value.get("add_to_failover", False),
"userPassword": {"userName": vcenter_userpwd or "admin"}
}
if value['in_place']:
json_disklevel_option_restore["dataStore"] = {}
if value.get('distribute_vm_workload'):
json_disklevel_option_restore["maxNumOfVMPerJob"] = value['distribute_vm_workload']
self._virtualserver_option_restore_json["diskLevelVMRestoreOption"] = json_disklevel_option_restore
def _json_restore_attach_diskLevelVMRestoreOption(self, value):
"""setter for the attach disk Level VM Restore Option in restore json"""
if not isinstance(value, dict):
raise SDKException('Subclient', '101')
json_disklevel_option_restore = {
"esxServerName": value.get("esxHost", ""),
"diskOption": value.get("disk_option", 0),
"passUnconditionalOverride": value.get("unconditional_overwrite", False),
"powerOnVmAfterRestore": value.get("power_on", False),
"transportMode": value.get("transport_mode", 0),
"userPassword": {"userName": value.get("userName",""),"password": value.get("password","")}
}
self._virtualserver_option_restore_json["diskLevelVMRestoreOption"] = json_disklevel_option_restore
def _json_restore_advancedRestoreOptions(self, value):
"""setter for the Virtual server restore option in restore json"""
if not isinstance(value, dict):
raise SDKException('Subclient', '101')
self._advanced_option_restore_json = {
"disks": value.get("disks", []),
"guid": value.get("guid", ""),
"newGuid": value.get("new_guid", ""),
"newName": value.get("new_name", ""),
"esxHost": value.get("esx_host", ""),
"projectId": value.get("project_id", ""),
"cluster": value.get("cluster", ""),
"name": value.get("name", ""),
"nics": value.get("nics", []),
"vmIPAddressOptions": value.get("vm_ip_address_options", []),
"FolderPath": value.get("FolderPath", ""),
"resourcePoolPath": value.get("ResourcePool", ""),
"volumeType": value.get("volumeType", "Auto"),
"vmCustomMetadata": value.get("vmCustomMetadata",[])
}
value_dict = {
"createPublicIP": ["createPublicIP", ["createPublicIP", ""]],
"restoreAsManagedVM": ["restoreAsManagedVM", ["restoreAsManagedVM", ""]],
"destination_os_name": ["osName", ["destination_os_name", "AUTO"]],
"resourcePoolPath": ["resourcePoolPath", ["resourcePoolPath", ""]],
"datacenter": ["datacenter", ["datacenter", ""]],
"terminationProtected": ["terminationProtected", ["terminationProtected", False]],
"securityGroups": ["securityGroups", ["securityGroups", ""]],
"keyPairList": ["keyPairList", ["keyPairList", ""]]
}
for key in value_dict:
if key in value:
inner_key = value_dict[key][0]
val1, val2 = value_dict[key][1][0], value_dict[key][1][1]
self._advanced_option_restore_json[inner_key] = value.get(val1, val2)
if "vmSize" in value:
val1, val2 = ("instanceSize", "") if not value["vmSize"] else ("vmSize", "vmSize")
self._advanced_option_restore_json["vmSize"] = value.get(val1, val2)
if "ami" in value and value["ami"] is not None:
self._advanced_option_restore_json["templateId"] = value["ami"]["templateId"]