-
Notifications
You must be signed in to change notification settings - Fork 42
/
inventory_manager.py
1190 lines (852 loc) · 43.4 KB
/
inventory_manager.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.
# --------------------------------------------------------------------------
"""Main file for performing operations on inventory manager app under Activate.
Inventories, Inventory, Assets & Asset are the four classes defined in this file
Inventories: class for representing all inventories in the commcell
Inventory: class for representing a single inventory in the commcell
Assets: class for representing all assets in an inventory
Asset: class to represent single asset in an inventory
Inventories:
__init__() -- initialise object of the Inventories class
_get_inventories() -- Gets all inventories in the commcell
_response_not_success() -- parses through the exception response, and raises SDKException
refresh() -- refresh the Inventories from the commcell
get_properties() -- returns the properties for given inventory name
has_inventory() -- Checks if a given inventory name exists in the commcell or not
get() -- returns the Inventory class object for given inventory name
add() -- add inventory to the commcell
delete() -- delete inventory from the commcell
Inventory:
__init__() -- initialise object of the Inventory class
_response_not_success() -- parses through the exception response, and raises SDKException
_get_inventory_properties() -- Gets all the properties of this inventory
_get_schedule_object() -- returns the schedule class object associated to this inventory
_get_data_source_handler_object() -- returns the datasource and default handler object for this inventory
_get_permission() -- returns the security associations for this inventory
refresh() -- refresh the properties of the inventory
get_assets() -- returns the Assets class object for this inventory
share() -- shares inventory with other user or user group
start_collection() -- starts collection job on this inventory
get_inventory_data() -- returns data from inventory
Inventory Attributes
-----------------
**properties** -- returns properties of the inventory
**index_server_name** -- returns the index server name associated with this inventory
**_index_server_cloud_id** -- returns the index server cloudid associated with this inventory
**inventory_name** -- returns the inventory name
**inventory_id** -- returns the inventory id
**security_associations** -- returns the security associations blob of this inventory
**schedule** -- returns the schedule object associated with this inventory
**data_source** -- returns the DataSource object associated with this inventory
**handler** -- returns the default handler object for this inventory
Assets:
__init__() -- initialise object of the Assets class
refresh() -- refresh the assets associated with inventory
add() -- adds asset to the inventory
get() -- returns the instance of Asset class based on given asset name
has_asset() -- returns whether given asset exists or not in inventory
delete() -- deletes the asset from the inventory
_get_assets_properties() -- returns the assets properties
_response_not_success() -- parses through the exception response, and raises SDKException
Assets Attributes:
----------------
**assets** -- returns the assets details as json
Asset:
__init__() -- initialise object of the Asset class
_get_properties() -- returns the properties of the asset
_response_not_success() -- parses through the exception response, and raises SDKException
refresh() -- refresh the asset associated with inventory
get_job_history() -- returns the job history details of this asset
get_job_status() -- returns the latest job status details of this asset
get_asset_prop() -- returns the asset property value for the given property name
Asset Attributes:
-----------------
**asset_id** -- returns the id of asset
**asset_name** -- returns the name of asset
**asset_type** -- returns the type of asset
**crawl_start_time** -- returns the last crawl start time of asset
**asset_props** -- returns the properties(name/value pair) of asset
**asset_status** -- returns the status of asset
**inventory_id** -- returns the inventory id of this asset
"""
import copy
from ..activateapps.constants import InventoryConstants
from ..schedules import Schedules
from ..exception import SDKException
class Inventories():
"""Class for representing all inventories in the commcell."""
def __init__(self, commcell_object):
"""Initializes an instance of the Inventories class.
Args:
commcell_object (object) -- instance of the commcell class
Returns:
object - instance of the Inventories class
"""
self._commcell_object = commcell_object
self._update_response_ = commcell_object._update_response_
self._cvpysdk_object = commcell_object._cvpysdk_object
self._services = commcell_object._services
self._inventories = None
self._API_INVENTORIES = self._services['EDISCOVERY_INVENTORIES']
self._API_DELETE_INVENTORY = self._services['EDISCOVERY_INVENTORY']
self.refresh()
def _response_not_success(self, response):
"""Helper function to raise an exception when reponse status is not 200 (OK).
Args:
response (object) -- response class object,
received upon running an API request, using the `requests` python package
"""
raise SDKException('Response', '101', self._update_response_(response.text))
def _get_inventories(self):
"""Gets all inventories from the commcell
Args:
None
Return:
list(dict) -- list Containing inventory details dict
Raises:
SDKException:
if response is empty
if response is not success
"""
output = {}
flag, response = self._cvpysdk_object.make_request(
'GET', self._API_INVENTORIES
)
if flag:
if response.json() and 'inventories' in response.json():
inventories = response.json()['inventories']
for inventory in inventories:
output[inventory['displayName'].lower()] = inventory
return output
raise SDKException('Inventory', '103')
self._response_not_success(response)
def add(self, inventory_name, index_server, name_server=None):
"""Adds inventory to the commcell with given inputs
Args:
inventory_name (str) -- Name of the inventory
index_server (str) -- Index server name
name_server (list) -- Name server assets which needs to be added to inventory
Returns:
object -- Instance of Inventory Class
Raises:
SDKException:
if input data type is not valid
if failed to add inventory
if Index Server doesn't exists in commcell
"""
if not isinstance(inventory_name, str) or not isinstance(index_server, str):
raise SDKException('Inventory', '101')
req_json = copy.deepcopy(InventoryConstants.INVENTORY_ADD_REQUEST_JSON)
if name_server:
req_json['identityServers'] = name_server
req_json['name'] = inventory_name
if not self._commcell_object.index_servers.has(index_server):
raise SDKException('Inventory', '102', "Given index server name not exists on this commcell")
index_server_obj = self._commcell_object.index_servers.get(index_server)
req_json['indexServer']['cloudId'] = index_server_obj.cloud_id
req_json['indexServer']['displayName'] = index_server_obj.cloud_name
flag, response = self._cvpysdk_object.make_request(
'POST', self._API_INVENTORIES, req_json
)
if flag:
if response.json():
if 'errorCode' in response.json() and response.json()['errorCode'] != 0:
raise SDKException(
'Inventory',
'102',
f"Failed to create inventory with error [{response.json()['errorMessage']}]")
elif 'name' in response.json():
inventory = response.json()['name']
inventory_id = response.json()['id']
self.refresh()
return Inventory(self._commcell_object, inventory_name, inventory_id)
raise SDKException('Inventory', '102', f"Failed to create inventory with response - {response.json()}")
raise SDKException('Inventory', '105')
self._response_not_success(response)
def delete(self, inventory_name):
"""Deletes the inventory from the commcell
Args:
inventory_name (str) -- Inventory name to be deleted
Returns:
None
Raises:
SDKException:
if unable to find inventory
if failed to delete inventory
if input type is not valid
"""
if not isinstance(inventory_name, str):
raise SDKException('Inventory', '101')
if not self.has_inventory(inventory_name):
raise SDKException('Inventory', '106')
flag, response = self._cvpysdk_object.make_request(
'DELETE', self._API_DELETE_INVENTORY % self._inventories[inventory_name.lower()]['id']
)
if flag:
if response.json():
if 'errorCode' in response.json() and response.json()['errorCode'] != 0:
raise SDKException(
'Inventory',
'102',
f"Failed to Delete inventory with error [{response.json()['errorMessage']}]")
self.refresh()
else:
raise SDKException('Inventory', '107')
else:
self._response_not_success(response)
def refresh(self):
"""Refresh the inventories associated with the commcell."""
self._inventories = self._get_inventories()
def get_properties(self, inventory_name):
"""Returns a properties of the specified Inventory
Args:
inventory_name (str) -- name of the inventory
Returns:
dict - properties for the given inventory name
"""
return self._inventories[inventory_name.lower()]
def has_inventory(self, inventory_name):
"""Checks if a inventory exists in the commcell with the input name.
Args:
inventory_name (str) -- name of the inventory
Returns:
bool - boolean output to specify whether the inventory exists in the commcell or not
Raises:
SDKException:
if type of the inventory name argument is not string
"""
if not isinstance(inventory_name, str):
raise SDKException('Inventory', '101')
return self._inventories and inventory_name.lower() in map(str.lower, self._inventories)
def get(self, inventory_name):
"""Returns a Inventory object for the given inventory name.
Args:
inventory_name (str) -- name of the inventory
Returns:
obj -- Object of Inventory class
Raises:
SDKException:
if inventory doesn't exists in commcell
if inventory_name is not of type string
"""
if not isinstance(inventory_name, str):
raise SDKException('Inventory', '101')
if self.has_inventory(inventory_name):
inventory_id = self._inventories[inventory_name.lower()]['id']
return Inventory(self._commcell_object, inventory_name, inventory_id)
raise SDKException('Inventory', '106')
class Inventory():
"""Class for performing operations on a single inventory"""
def __init__(self, commcell_object, inventory_name, inventory_id=None):
"""Initialize an object of the Inventory class.
Args:
commcell_object (object) -- instance of the commcell class
inventory_name (str) -- name of the Inventory
inventory_id (str) -- id of Inventory
default: None
Returns:
object - instance of the Inventory class
"""
self._commcell_object = commcell_object
self._update_response_ = commcell_object._update_response_
self._services = commcell_object._services
self._cvpysdk_obj = self._commcell_object._cvpysdk_object
self._inventory_id = None
self._inventory_name = inventory_name
self._inventory_props = None
self._index_server_name = None
self._index_server_cloud_id = None
self._security_associations = None
self._schedule = None
self._data_source = None
self._handler = None
self._API_GET_INVENTORY_DETAILS = self._services['EDISCOVERY_INVENTORY']
self._API_SECURITY_ENTITY = self._services['ENTITY_SECURITY_ASSOCIATION']
self._API_GET_DEFAULT_HANDLER = self._services['EDISCOVERY_GET_DEFAULT_HANDLER']
self._API_PERMISSION = self._services['V4_ACTIVATE_DS_PERMISSION']
self._API_CRAWL = self._services['V4_INVENTORY_CRAWL']
if not inventory_id:
self._inventory_id = self._commcell_object.activate.inventory_manager().get(inventory_name).inventory_id
else:
self._inventory_id = inventory_id
self.refresh()
def _response_not_success(self, response):
"""Helper function to raise an exception when reponse status is not 200 (OK).
Args:
response (object) -- response class object,
received upon running an API request, using the `requests` python package
"""
raise SDKException('Response', '101', self._update_response_(response.text))
def _get_permission(self):
"""returns security association blob for this inventory
Args:
None
Returns:
dict -- Security association blob
"""
flag, response = self._cvpysdk_obj.make_request(
'GET', self._API_PERMISSION % self._inventory_id
)
if flag:
if response.json() and 'securityAssociations' in response.json():
return response.json()['securityAssociations']
raise SDKException('Inventory', '102', "Inventory permission fetch failed")
self._response_not_success(response)
def _get_inventory_properties(self):
""" Get inventory properties from the commcell
Args:
None
Returns:
dict -- Properties of inventory
"""
flag, response = self._cvpysdk_obj.make_request(
'GET', self._API_GET_INVENTORY_DETAILS % self._inventory_id
)
if flag:
if response.json():
inventory_props = response.json()
self._index_server_name = inventory_props['indexServer']['displayName']
self._index_server_cloud_id = inventory_props['indexServer']['cloudId']
self._inventory_name = inventory_props['displayName']
return inventory_props
raise SDKException('Inventory', '104')
self._response_not_success(response)
def refresh(self):
"""Refresh the inventory details for associated object"""
self._inventory_props = self._get_inventory_properties()
self._schedule = self._get_schedule_object()
self._data_source, self._handler = self._get_data_source_handler_object()
self._security_associations = self._get_permission()
def get_assets(self):
"""Returns the Assets class instance for this inventory
Args:
None
Returns:
object -- Instance of Assets class
"""
return Assets(self._commcell_object, self.inventory_name, self.inventory_id)
def start_collection(self):
"""Starts collection job on this inventory
Args:
None
Return:
None
Raises:
SDKException:
if failed to start collection job
"""
flag, response = self._cvpysdk_obj.make_request(
'PUT', self._API_CRAWL % self._inventory_id
)
if flag:
if response.json():
if 'errorCode' in response.json() and response.json()['errorCode'] != 0:
raise SDKException(
'Inventory',
'102',
f"Failed to start crawl on inventory with error [{response.json()['errorMessage']}]")
return
else:
raise SDKException('Inventory', '102', "Unknown response while starting collection job on inventory")
else:
self._response_not_success(response)
def share(self, user_or_group_name, allow_edit_permission=False, is_user=True, ops_type=1):
"""Shares inventory with given user or user group in commcell
Args:
user_or_group_name (str) -- Name of user or group
is_user (bool) -- Denotes whether this is user or group name
default : True(User)
allow_edit_permission (bool) -- whether to give edit permission or not to user or group
ops_type (int) -- Operation type
Default : 1 (Add)
Supported : 1 (Add)
3 (Delete)
Returns:
None
Raises:
SDKException:
if unable to update security associations
if response is empty or not success
"""
if not isinstance(user_or_group_name, str):
raise SDKException('Inventory', '101')
request_json = copy.deepcopy(InventoryConstants.INVENTORY_SHARE_REQUEST_JSON)
external_user = False
association_response = None
if ops_type == 1 and len(self.security_associations) > 1:
association_request_json = copy.deepcopy(InventoryConstants.INVENTORY_SHARE_REQUEST_JSON)
del association_request_json['securityAssociations']
association_request_json['entityAssociated']['entity'][0]['seaDataSourceId'] = int(self.inventory_id)
# get security blob for this data source type entity - 132
flag, response = self._cvpysdk_obj.make_request(
'GET', self._API_SECURITY_ENTITY % (132, int(self.inventory_id)), association_request_json
)
if flag:
if response.json() and 'securityAssociations' in response.json():
association_response = response.json(
)['securityAssociations'][0]['securityAssociations']['associations']
else:
raise SDKException('Inventory', '102', 'Failed to get existing security associations')
else:
response_string = self._commcell_object._update_response_(response.text)
raise SDKException('Response', '101', response_string)
if '\\' in user_or_group_name:
external_user = True
if is_user:
user_obj = self._commcell_object.users.get(user_or_group_name)
user_id = user_obj.user_id
request_json['securityAssociations']['associations'][0]['userOrGroup'][0]['userId'] = int(user_id)
request_json['securityAssociations']['associations'][0]['userOrGroup'][0]['_type_'] = 13
request_json['securityAssociations']['associations'][0]['userOrGroup'][0]['userName'] = user_or_group_name
elif external_user:
request_json['securityAssociations']['associations'][0]['userOrGroup'][0]['groupId'] = 0
request_json['securityAssociations']['associations'][0]['userOrGroup'][0]['_type_'] = 62
request_json['securityAssociations']['associations'][0]['userOrGroup'][0][
'externalGroupName'] = user_or_group_name
else:
grp_obj = self._commcell_object.user_groups.get(user_or_group_name)
grp_id = grp_obj.user_group_id
request_json['securityAssociations']['associations'][0]['userOrGroup'][0]['userGroupId'] = int(grp_id)
request_json['securityAssociations']['associations'][0]['userOrGroup'][0]['_type_'] = 15
request_json['securityAssociations']['associations'][0]['userOrGroup'][0][
'userGroupName'] = user_or_group_name
request_json['entityAssociated']['entity'][0]['seaDataSourceId'] = self.inventory_id
request_json['securityAssociations']['associationsOperationType'] = ops_type
if allow_edit_permission:
request_json['securityAssociations']['associations'][0]['properties']['categoryPermission']['categoriesPermissionList'].append(
InventoryConstants.EDIT_CATEGORY_PERMISSION)
# Associate existing associations to the request
if ops_type == 1 and len(self.security_associations) > 1:
request_json['securityAssociations']['associations'].extend(association_response)
flag, response = self._cvpysdk_obj.make_request(
'PUT', self._API_PERMISSION % self._inventory_id, request_json
)
if flag:
if response.json():
error_code = response.json()['errorCode']
if error_code != 0:
error_message = response.json()['errorString']
raise SDKException(
'Inventory',
'102', error_message)
# update association list by refreshing inventory
self.refresh()
else:
raise SDKException('Inventory', '111')
else:
response_string = self._commcell_object._update_response_(response.text)
raise SDKException('Response', '101', response_string)
def _get_data_source_handler_object(self):
"""returns the data source and handler object associated with this inventory
Args:
None
Returns:
obj,obj -- Instance of DataSource object,Instance of Handler object
Raises:
SDKException:
if failed to get datasource or handler details
"""
flag, response = self._cvpysdk_obj.make_request(
'GET', self._API_GET_DEFAULT_HANDLER % self.inventory_id)
if flag:
if response.json() and 'handlerInfos' in response.json():
handler_list = response.json()['handlerInfos']
if not isinstance(handler_list, list):
raise SDKException('Inventory', '102', "Failed to get Datasource/Handler details")
handler_details = handler_list[0]
ds_name = handler_details['dataSourceName']
handler_name = handler_details['handlerName']
ds_obj = self._commcell_object.datacube.datasources.get(ds_name)
handler_obj = ds_obj.ds_handlers.get(handler_name)
return ds_obj, handler_obj
raise SDKException('Inventory', '102', 'Unknown response while fetching datasource details')
response_string = self._commcell_object._update_response_(response.text)
raise SDKException('Response', '101', response_string)
def _get_schedule_object(self):
"""Returns the schedule class object of schedule associated to this inventory
Args:
None
Returns:
object -- Instance of Schedule class
Raises:
SDKException:
if failed to find schedule
"""
return Schedules(self).get()
def get_inventory_data(self, handler_filter=""):
""" Executes handler for fetching data from inventory
Args:
handler_filter (str) -- Filter which needs to applied for handler execution
Returns:
dict -- Dictionary of values fetched from handler execution
Raises:
SDKExpception:
if error in fetching handler data
if input is not valid
"""
if not isinstance(handler_filter, str):
raise SDKException('Inventory', '101')
if not self._handler:
raise SDKException('Inventory', '102', 'No handler object initialised')
return self._handler.get_handler_data(handler_filter=handler_filter)
@property
def properties(self):
"""Returns the properties of this inventory as dict"""
return self._inventory_props
@property
def index_server_name(self):
"""Returns the index server name associated with this inventory"""
return self._index_server_name
@property
def index_server_cloud_id(self):
"""Returns the index server id associated with this inventory"""
return self._index_server_cloud_id
@property
def inventory_id(self):
"""Returns the inventory id associated with this inventory"""
return self._inventory_id
@property
def inventory_name(self):
"""Returns the inventory name associated with this inventory"""
return self._inventory_name
@property
def security_associations(self):
"""Returns the security blob associated with this inventory"""
return self._security_associations
@property
def schedule(self):
"""Returns the schedule class object for schedule associated with this inventory"""
return self._schedule
@property
def data_source(self):
"""Returns the DataSource class object for datasource associated with this inventory"""
return self._data_source
@property
def handler(self):
"""Returns the Handler class object for default handler associated with this inventory"""
return self._handler
class Assets():
"""Class to represent all assets in an inventory"""
def __init__(self, commcell_object, inventory_name, inventory_id=None):
"""Initialize an object of the Assets class.
Args:
commcell_object (object) -- instance of the commcell class
inventory_name (str) -- name of the Inventory
inventory_id (str) -- id of Inventory
default: None
Returns:
object - instance of the Assets class
"""
self._commcell_object = commcell_object
self._update_response_ = commcell_object._update_response_
self._services = commcell_object._services
self._cvpysdk_obj = self._commcell_object._cvpysdk_object
self._inventory_id = None
self._inventory_name = inventory_name
if not inventory_id:
self._inventory_id = self._commcell_object.activate.inventory_manager().get(inventory_name).inventory_id
else:
self._inventory_id = inventory_id
self._assets = None
self._API_ASSETS = self._services['EDISCOVERY_ASSETS']
self._API_ASSET = self._services['EDISCOVERY_ASSET']
self.refresh()
def _get_assets_properties(self):
"""gets the assets properties from inventory
Args:
None
Returns:
dict -- containing asset properties
"""
flag, response = self._cvpysdk_obj.make_request(
'GET', self._API_ASSETS % self._inventory_id)
if flag:
if response.json() and 'assets' in response.json():
assets = {}
for asset in response.json()['assets']:
name = asset['name'].lower()
assets[name] = asset
return assets
else:
raise SDKException('Inventory', '102', "Unknown response while fetching assets on inventory")
else:
self._response_not_success(response)
def refresh(self):
"""Refresh the assets details associated with this inventory"""
self._assets = self._get_assets_properties()
def _response_not_success(self, response):
"""Helper function to raise an exception when reponse status is not 200 (OK).
Args:
response (object) -- response class object,
received upon running an API request, using the `requests` python package
"""
raise SDKException('Response', '101', self._update_response_(response.text))
def has_asset(self, asset_name):
"""Checks whether given asset exists in inventory or not
Args:
asset_name (str) -- Name of the asset
Returns:
bool -- true if asset exists else false
"""
return self._assets and asset_name.lower() in self._assets
def get(self, asset_name):
"""Returns the asset object
Args:
asset_name (str) -- Name of the asset
Returns:
object -- Instance of Asset class
Raises:
SDKException:
if input is not valid
if asset doesn't exists in inventory
"""
if not isinstance(asset_name, str):
raise SDKException('Inventory', '101')
if not self.has_asset(asset_name):
raise SDKException('Inventory', '109')
return Asset(self._commcell_object, self._inventory_name, asset_name, self._inventory_id)
def add(self, asset_name, asset_type=InventoryConstants.AssetType.IDENTITY_SERVER, **kwargs):
"""Adds asset to the inventory
Args:
asset_name (str) -- Name of the asset
asset_type (Enum) -- type of asset (Refer to InventoryConstants.AssetType class)
kwargs for FILE SERVER type Asset:
fqdn -- File server FQDN
os -- File Server OS type
(Default:Windows)
ip -- File server IP
country_code -- Country code (ISO 3166 2-letter code)
Returns:
object -- Instance of Asset class
Raises:
SDKException:
if input is not valid
if failed to add asset to inventory
"""
if not isinstance(asset_name, str) or not isinstance(asset_type, InventoryConstants.AssetType):
raise SDKException('Inventory', '101')
request_json = {}
if asset_type.value == InventoryConstants.AssetType.FILE_SERVER.value:
for prop in InventoryConstants.ASSET_FILE_SERVER_PROPERTY:
prop_name = InventoryConstants.FIELD_PROPS_MAPPING[prop]
default_value = ""
if prop_name not in kwargs:
# always use asset name as file server name
if prop == InventoryConstants.FIELD_PROPERTY_NAME:
default_value = asset_name
if prop == InventoryConstants.FIELD_PROPERTY_OS:
default_value = "Windows"
request_json[prop] = kwargs.get(prop_name, default_value)
else:
request_json = copy.deepcopy(InventoryConstants.IDENTITY_SERVER_ASSET_ADD_TO_INVENTORY_JSON)
request_json['identityServers'] = [asset_name]
flag, response = self._cvpysdk_obj.make_request(
'PUT', self._API_ASSETS % self._inventory_id, request_json)
if flag:
if response.json():
if 'errorCode' in response.json() and response.json()['errorCode'] != 0:
raise SDKException(
'Inventory',
'102',
f"Failed to add asset to inventory with error [{response.json()['errorMessage']}]")
self.refresh()
return Asset(self._commcell_object, self._inventory_name, asset_name, self._inventory_id)
raise SDKException('Inventory', '108')
self._response_not_success(response)
def delete(self, asset_name):
"""Delete the asset from the inventory
Args:
asset_name (str) -- Name of the asset
Returns:
None
Raises:
SDKException:
if input is not valid
if failed to delete the asset
if unable to find this asset in inventory
"""
if not isinstance(asset_name, str):
raise SDKException('Inventory', '101')
if not self.has_asset(asset_name):
raise SDKException('Inventory', '109')
flag, response = self._cvpysdk_obj.make_request(
'DELETE', self._API_ASSET % (self._inventory_id, self._assets[asset_name.lower()]['id']))
if flag:
if response.json():
if 'errorCode' in response.json() and response.json()['errorCode'] != 0:
raise SDKException(
'Inventory',
'102',
f"Failed to delete asset from inventory with error [{response.json()['errorMessage']}]")
self.refresh()
return
raise SDKException('Inventory', '110')
self._response_not_success(response)
@property
def assets(self):
"""Returns the assets details associated with this inventory"""
return self._assets
class Asset():
"""Class to represent single asset in an inventory"""
def __init__(self, commcell_object, inventory_name, asset_name, inventory_id=None):
"""Initialize an object of the Asset class.
Args:
commcell_object (object) -- instance of the commcell class
inventory_name (str) -- name of the Inventory