-
Notifications
You must be signed in to change notification settings - Fork 42
/
ediscovery_utils.py
3248 lines (2466 loc) · 130 KB
/
ediscovery_utils.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 ediscovery clients & ediscovery data sources.
'EdiscoveryClients','EdiscoveryClientOperations' ,'EdiscoveryDataSources' , 'EdiscoveryDataSource' are the 4 classes defined in this file
EdiscoveryClients: Class for getting ediscovery clients details for different apps in activate
EdiscoveryClientOperations : Class for performing operations on Ediscovery client
EdiscoveryDataSources: Class to represent all datasources associated with ediscovery client
EdiscoveryDataSource: Class to represent single data source associated with edisocvery client
EdiscoveryClients:
__init__() -- initialise object of the EdiscoveryClients class
_response_not_success() -- parses through the exception response, and raises SDKException
get_ediscovery_clients() -- returns the ediscovery clients details
get_ediscovery_client_group_details() - returns the ediscovery client group details
get_ediscovery_projects() -- returns the ediscovery projects details
add() -- Adds ediscovery client
delete() -- deletes ediscovery client
EdiscoveryClientOperations:
__init__() -- initialise object of the EdiscoveryClientOperations class
_response_not_success() -- parses through the exception response, and raises SDKException
_get_associations() -- returns the associations blob for this client
_do_stream_download() -- does stream download of exported csv file to local machine
form_search_params() -- returns the search params dict for searching/exporting
refresh() -- refresh the ediscovery client properties
share() -- shares client with given user name or group name
export() -- do export to CSV on data
start_job() -- starts collection job on ediscovery client
get_job_status() -- returns the job status of ediscovery client job
get_job_history() -- returns the job history details of this ediscovery client
wait_for_collection_job() -- waits for collection job to finish
wait_for_export() -- waits for export to csv operation to finish
get_ediscovery_client_details() -- returns the ediscovery client details
get_ediscovery_project_details() -- returns the ediscovery project properties
search() -- returns the search response containing document details
get_handler_id() -- returns the handler id for this Ediscovery client
schedule() -- Creates or modifies the schedule associated with ediscovery client
do_document_task() -- does document related tasks like consent/comment
configure_task() -- does task configuration for this edisocvery client
task_workflow_operation() -- calls workflow operation for task
EdiscoveryClientOperations Attributes:
--------------------------------------
**associations** -- returns the blob of associated entities for this client
EdiscoveryDataSources:
__init__() -- initialise object of the EdiscoveryDataSources class
_response_not_success() -- parses through the exception response, and raises SDKException
_get_data_sources_details() -- returns the data sources details associated with ediscovery client
_get_data_source_names() -- returns separate list of data source display names & data source names
associated with client
_parse_client_response_for_data_source -- returns list of values for field names for data sources
from client response
_get_data_source_properties() -- parses client response and returns deta sources properties
has_data_source() -- checks whether given data source exists in this client or not
get() -- returns the EdiscoveryDataSource class object for given data source name
delete() -- deletes the given data source associated with client
add_fs_data_source() -- adds file system data source
refresh() -- refresh the data sources details associated with client
get_datasource_document_count() -- returns the document count for specified data source
EdiscoveryDataSources Attributes:
----------------------------------
**data_sources** -- returns the list of data sources names associated with this client
**ediscovery_client_props** -- returns the Ediscovery client properties response for associated client
**total_documents** -- returns the total documents count from all data sources
**client_id** -- returns associated client id for all these data sources
**client_targetapp** -- returns the source details of client (FSO/SDG)
EdiscoveryDataSource:
__init__() -- initialise object of the EdiscoveryDataSource class
_response_not_success() -- parses through the exception response, and raises SDKException
_get_data_source_properties() -- returns the properties of data source
_get_property_value() -- returns the value for the property name
_form_files_list() -- returns list of dict containing files details
_form_request_options() -- returns the options for review request
refresh() -- refresh the datasource properties
get_job_history() -- returns the job history for this data source
get_active_jobs() -- returns the active jobs for this data source
search() -- returns the search response containing document details
export() -- do export to CSV on data
wait_for_export() -- waits for export to csv operation to finish
tag_items() -- applies tag to the documents
review_action() -- do review action for documents
start_collection() -- starts collection job on this data source
EdiscoveryDataSource Attributes:
---------------------------------
**crawl_type_name** -- returns the crawl type enum name for this data source
**crawl_type** -- returns the crawl type for this data source
**core_id** -- returns the data source core id attribute
**computed_core_name** -- returns the computed core name of this datasource
**core_name** -- returns the core name attribute of this data source
**cloud_id** -- returns the index server cloud id associated with this data source
**data_source_props** -- returns dict containing data source properties
**data_source_id** -- returns the id of data source
**data_source_type** -- returns the type of data source
**data_source_name** -- returns the display name of data source
**plan_id** -- returns the associated DC plan id
**data_source_type_id** -- returns the data source type id value
**client_id** -- returns the client id to which data source belongs too
**total_documents** -- returns the total document count on this data source
**sensitive_files_count** -- returns the total sensitive files count
**name** -- returns the actual name for this data source
**index_server_node_client_id** -- returns the associated Index server node client id on which the collection
exists
"""
import copy
import time
import json
import os
from ..activateapps.entity_manager import EntityManagerTypes
from ..activateapps.constants import InventoryConstants, EdiscoveryConstants, TargetApps, RequestConstants
from ..exception import SDKException
class EdiscoveryClients():
"""Class for getting ediscovery clients details for different apps in activate"""
def __init__(self, commcell_object, class_object):
"""Initializes an instance of the EdiscoveryClients class.
Args:
commcell_object (object) -- instance of the commcell class
class_object (object) -- instance of FsoServers/FsoServerGroups/FsoServerGroup class
Returns:
object - instance of the EdiscoveryClients class
"""
self._commcell_object = commcell_object
self._cvpysdk_object = commcell_object._cvpysdk_object
self._services = commcell_object._services
self._class_obj = class_object
self._ds_type = None
self._client_group = None
self._limit = None
self._offset = None
self._sort_by = None
self._sort_dir = None
self._client_group_filter = None
self._include_doc = None
self._ediscovery_sub_type = None
self._API_GET_EDISCOVERY_CLIENTS = copy.deepcopy(self._services['EDISCOVERY_V2_GET_CLIENTS'])
self._API_GET_EDISCOVERY_CLIENT_GROUPS = self._services['EDISCOVERY_V2_GET_CLIENT_GROUP_DETAILS']
self._API_GET_EDISCOVERY_CLIENTS_V1 = copy.deepcopy(self._services['EDISCOVERY_CLIENTS'])
self._API_CREATE_CLIENT = copy.deepcopy(self._services['EDISCOVERY_CREATE_CLIENT'])
self._API_DELETE_CLIENT = copy.deepcopy((self._services['EDISCOVERY_DELETE_CLIENT']))
from .file_storage_optimization import FsoServers, FsoServerGroups, FsoServerGroup
from .sensitive_data_governance import Projects
if isinstance(class_object, FsoServers):
self._ds_type = 5
self._client_group = 0
self._limit = 0
self._offset = 0
self._sort_by = 1
self._sort_dir = 0
elif isinstance(class_object, FsoServerGroups):
self._ds_type = 5
self._client_group = 1
self._limit = 0
self._offset = 0
self._sort_by = 1
self._sort_dir = 0
elif isinstance(class_object, FsoServerGroup):
self._ds_type = 5
self._client_group = 0
self._client_group_filter = class_object.server_group_id
self._limit = 0
self._offset = 0
self._sort_by = 1
self._sort_dir = 0
self._include_doc = 1
elif isinstance(class_object, Projects):
self._ediscovery_sub_type = 2
else:
raise SDKException('EdiscoveryClients', '102', 'Not a supported caller for this class')
def delete(self, client_id):
"""Deletes the ediscovery client
Args:
client_id (int) -- Client id
Returns:
None
Raises:
SDKException:
if input is not valid
if failed to delete client
if response is empty or not success
"""
if not isinstance(client_id, int):
raise SDKException('EdiscoveryClients', '101')
flag, response = self._cvpysdk_object.make_request(
'DELETE', self._API_DELETE_CLIENT % client_id)
if flag:
if response.json() and 'response' in response.json():
response = response.json()['response'][0]
if 'errorCode' in response and response['errorCode'] != 0:
raise SDKException(
'EdiscoveryClients',
'102',
f"Delete operation failed on client - {response['errorCode']}")
return
raise SDKException('EdiscoveryClients', '120')
self._response_not_success(response)
def add(self, client_name, inventory_name, plan_name):
"""Adds ediscovery client
Args:
client_name (str) -- Name of the client
inventory_name (str) -- Name of inventory
plan_name (str) -- Plan name to associate with this client
Returns:
int -- client id
Raises:
SDKException:
if input is not valid
if failed to create client
if response is empty or not success
"""
if not isinstance(client_name, str) or not isinstance(inventory_name, str) or not isinstance(plan_name, str):
raise SDKException('EdiscoveryClients', '101')
if not self._commcell_object.activate.inventory_manager().has_inventory(inventory_name):
raise SDKException('EdiscoveryClients', '102', 'Invalid inventory name')
if not self._commcell_object.plans.has_plan(plan_name):
raise SDKException('EdiscoveryClients', '102', 'Invalid plan name')
plan_obj = self._commcell_object.plans.get(plan_name)
inv_obj = self._commcell_object.activate.inventory_manager().get(inventory_name)
req_json = copy.deepcopy(EdiscoveryConstants.CREATE_CLIENT_REQ_JSON)
req_json['entity']['clientName'] = client_name
req_json['clientInfo']['plan']['planId'] = int(plan_obj.plan_id)
req_json['clientInfo']['edgeDrivePseudoClientProperties']['eDiscoveryInfo']['inventoryDataSource']['seaDataSourceId'] = int(
inv_obj.inventory_id)
flag, response = self._cvpysdk_object.make_request(
'POST', self._API_CREATE_CLIENT, req_json)
if flag:
if response.json() and 'response' in response.json():
response = response.json()['response']
if 'errorCode' in response and response['errorCode'] != 0:
raise SDKException(
'EdiscoveryClients',
'102',
f"Add operation failed on client - {response['errorCode']}")
if 'entity' in response:
return response['entity'].get('clientId', 0)
raise SDKException('EdiscoveryClients', '119')
self._response_not_success(response)
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._commcell_object._update_response_(response.text))
def get_ediscovery_client_group_details(self):
"""returns the ediscovery client group details for the app
Args:
None
Returns:
dict -- Containing client group details
Raises;
SDKException:
if failed to get client group details
if response is empty
if response is not success
"""
flag, response = self._cvpysdk_object.make_request(
'GET', self._API_GET_EDISCOVERY_CLIENT_GROUPS %
(self._client_group_filter, self._include_doc))
if flag:
if response.json() and 'nodeList' in response.json():
return response.json()
raise SDKException('EdiscoveryClients', '106')
self._response_not_success(response)
def get_ediscovery_clients(self):
"""returns the ediscovery clients details for the app
Args:
None
Returns:
dict -- Containing client details
Raises;
SDKException:
if failed to get client details
if response is empty
if response is not success
"""
api = self._API_GET_EDISCOVERY_CLIENTS % (
self._ds_type, self._client_group, self._limit, self._offset, self._sort_by, self._sort_dir)
if self._client_group_filter:
api = api + f"&clientGroupFilter={self._client_group_filter}"
flag, response = self._cvpysdk_object.make_request('GET', api)
output = {}
if flag:
if response.json() and 'nodeList' in response.json():
for node in response.json()['nodeList']:
if 'clientEntity' in node:
output[node['clientEntity'].get('displayName', 'NA').lower()] = node
return output
raise SDKException('EdiscoveryClients', '106')
self._response_not_success(response)
def get_ediscovery_projects(self):
"""returns the ediscovery projects details for the app
Args:
None
Returns:
dict -- Containing project details
Raises;
SDKException:
if failed to get project details
if response is empty
if response is not success
"""
if not self._ediscovery_sub_type:
raise SDKException('EdiscoveryClients', '102', 'Ediscovery subtype not initialized')
api = self._API_GET_EDISCOVERY_CLIENTS_V1 % self._ediscovery_sub_type
flag, response = self._cvpysdk_object.make_request('GET', api)
output = {}
if flag:
if response.json() and 'eDiscoveryClientProp' in response.json():
projects = response.json()['eDiscoveryClientProp']
for project in projects:
project['clientId'] = project['eDiscoveryClient']['clientId']
output[project['eDiscoveryClient']['clientName'].lower()] = project
return output
raise SDKException('EdiscoveryClients', '117')
self._response_not_success(response)
class EdiscoveryClientOperations():
"""Class for performing operations on ediscovery client."""
def __init__(self, commcell_object, class_object):
"""Initializes an instance of the EdiscoveryClientOperations class.
Args:
commcell_object (object) -- instance of the commcell class
class_object (object) -- instance of Inventory/Asset/FsoServer
/EdiscoveryDataSource/EdiscoveryDataSources/FsoServerGroup class
Returns:
object - instance of the EdiscoveryClientOperations class
"""
self._commcell_object = commcell_object
self._cvpysdk_object = commcell_object._cvpysdk_object
self._services = commcell_object._services
self._class_obj = class_object
self._type = None
self._operation = None
self._client_id = None
self._data_source_id = None
self._ds_type_names = None
self._include_doc_count = None
self._limit = None
self._offset = None
self._sort_by = None
self._sort_dir = None
self._app_type = None
self._associations = None
self._search_entity_type = None
self._search_entity_id = None
self._client_entity_type = 3
self._request_type = None
self._request_review_set_id = None
self._request_app = None
self._API_CRAWL = self._services['EDISCOVERY_CRAWL']
self._API_JOBS_HISTORY = self._services['EDISCOVERY_JOBS_HISTORY']
self._API_JOB_STATUS = self._services['EDISCOVERY_JOB_STATUS']
self._API_CLIENT_DETAILS = self._services['EDISCOVERY_V2_GET_CLIENT_DETAILS']
self._API_SECURITY_ENTITY = self._services['ENTITY_SECURITY_ASSOCIATION']
self._API_SECURITY = self._services['EDISCOVERY_SECURITY_ASSOCIATION']
self._API_SEARCH = self._services['EDISCOVERY_DYNAMIC_FEDERATED']
self._API_GET_DEFAULT_HANDLER = self._services['EDISCOVERY_GET_DEFAULT_HANDLER']
self._API_EXPORT = self._services['EDISCOVERY_EXPORT']
self._API_EXPORT_STATUS = self._services['EDISCOVERY_EXPORT_STATUS']
self._CREATE_POLICY = self._services['CREATE_UPDATE_SCHEDULE_POLICY']
self._API_GET_EDISCOVERY_CLIENT_DETAILS_V1 = copy.deepcopy(self._services['EDISCOVERY_CLIENT_DETAILS'])
self._API_DOC_TASK = self._services['EDISCOVERY_REQUEST_DOCUMENT_MARKER']
self._API_CONFIGURE_TASK = self._services['EDISCOVERY_CONFIGURE_TASK']
self._API_TASK_WORKFLOW = self._services['EDICOVERY_TASK_WORKFLOW']
from .file_storage_optimization import FsoServer, FsoServerGroup
from .sensitive_data_governance import Project
from .request_manager import Request
if isinstance(class_object, FsoServer):
self._client_id = class_object.server_id
self._include_doc_count = 1
self._limit = self._offset = 0
self._sort_by = 2
self._sort_dir = 0
self._ds_type_names = f"{EdiscoveryConstants.DS_FILE},{EdiscoveryConstants.DS_CLOUD_STORAGE}"
self._data_source_id = 0 # invoke on all data sources
self._type = 1 # Client
self._operation = 0
self._app_type = 1
self._search_entity_type = 3
self._search_entity_id = self._client_id
elif isinstance(class_object, EdiscoveryDatasource):
self._search_entity_type = 132
self._search_entity_id = class_object.data_source_id
self._data_source_id = class_object.data_source_id
self._type = 1 # Client
self._operation = 2 # incremental job by default
self._client_id = class_object.client_id
elif isinstance(class_object, EdiscoveryDataSources):
self._client_id = class_object.client_id
self._include_doc_count = 1
self._limit = self._offset = 0
self._sort_by = 2
self._sort_dir = 0
if class_object.client_targetapp == TargetApps.FSO.value:
# based on caller, set appropriate ds types supported for that
self._ds_type_names = f"{EdiscoveryConstants.DS_FILE},{EdiscoveryConstants.DS_CLOUD_STORAGE}"
elif isinstance(class_object, FsoServerGroup):
self._search_entity_type = 28
self._search_entity_id = class_object.server_group_id
elif isinstance(class_object, Project):
self._client_id = class_object.project_id
self._app_type = 2 # for sharing, app type param
self._search_entity_type = 188
self._search_entity_id = class_object.project_id
elif isinstance(class_object, Request):
self._client_id = class_object.request_id
self._request_type = class_object.request_type
self._request_review_set_id = class_object.review_set_id
self._request_app = class_object.request_app
else:
raise SDKException('EdiscoveryClients', '101')
self.refresh()
def refresh(self):
"""refresh ediscovery client properties"""
self._associations = self._get_associations()
def schedule(self, schedule_name, pattern_json, ops_type=2):
"""Creates or modifies the schedule associated with ediscovery client
Args:
schedule_name (str) -- Schedule name
pattern_json (dict) -- Schedule pattern dict
(Refer to Create_schedule_pattern in schedule.py)
ops_type (int) -- Operation type
Default : 2 (Add)
Supported : 2 (Add/Modify)
Raises:
SDKException:
if input is not valid
if failed to create/modify schedule
"""
if not isinstance(schedule_name, str) or not isinstance(pattern_json, dict):
raise SDKException('EdiscoveryClients', '101')
if ops_type not in [2]:
raise SDKException('EdiscoveryClients', '102', "Schedule operation type provided is not supported")
request_json = copy.deepcopy(EdiscoveryConstants.SERVER_LEVEL_SCHEDULE_JSON)
request_json['taskInfo']['associations'][0]['clientId'] = int(self._client_id)
request_json['taskInfo']['task'][
'taskName'] = f"Cvpysdk created Schedule -{schedule_name} for Server id - {self._client_id}"
request_json['taskInfo']['subTasks'][0]['subTask'][
'subTaskName'] = schedule_name
request_json['taskInfo']['subTasks'][0]['pattern'] = pattern_json
request_json['taskInfo']['subTasks'][0]['options']['adminOpts']['contentIndexingOption']['operationType'] = ops_type
flag, response = self._commcell_object._cvpysdk_object.make_request(
'POST', self._CREATE_POLICY, request_json
)
if flag:
if response.json():
if "taskId" in response.json():
task_id = str(response.json()["taskId"])
if task_id:
return
elif "errorCode" in response.json():
error_code = str(response.json()['errorCode'])
error_message = response.json()['errorMessage']
if error_code == "0":
return
else:
raise SDKException(
'EdiscoveryClients',
'102',
f"Schedule operation failed on server - {error_code} - {error_message}")
else:
raise SDKException('Response', '102')
else:
raise SDKException('Response', '102')
else:
response_string = self._commcell_object._update_response_(
response.text)
raise SDKException('Response', '101', response_string)
def form_search_params(
self,
criteria=None,
attr_list=None,
params=None,
query="*:*",
key="key",
is_separate_attr=False):
"""returns the search params dict based on input
Args:
criteria (str) -- containing criteria for query
Example :
Size:[10 TO 1024]
FileName:09_23*
attr_list (set) -- Column names to be returned in results.
Acts as 'fl' in query
params (dict) -- Any other params which needs to be passed
Example : { "start" : "0" }
query (str) -- query to be performed (acts as q param in query)
default:None (Means *:*)
key (str) -- key name to be used in request (default:key)
is_separate_attr (bool) -- specifies whether attribute list needs to formed as separate key-value
Returns:
dict -- Containing searchparams details
Example : {
"searchParams": [
{
"key": "wt",
"value": "json"
},
{
"key": "defType",
"value": "edismax"
},
{
"key": "q",
"value": "*:*"
},
{
"key": "fq",
"value": "(contentid:949c3b53ce4dd72a82b8e67039eeddef)"
},
{
"key": "fl",
"value": "contentid,CreatedTime,Url,ClientId"
}
]
}
"""
search_params = copy.deepcopy(EdiscoveryConstants.DYNAMIC_FEDERATED_SEARCH_PARAMS)
search_params['searchParams'].append(
{key: "wt", "value": "json"})
search_params['searchParams'].append(
{key: "defType", "value": "edismax"})
search_params['searchParams'].append({key: "q", "value": query})
if criteria:
fq_dict = {
key: "fq",
"value": criteria
}
search_params['searchParams'].append(fq_dict)
if attr_list:
if is_separate_attr:
for attr in attr_list:
fl_dict = {
key: "fl",
"value": attr
}
search_params['searchParams'].append(fl_dict)
else:
fl_list = ','.join(attr_list)
fl_dict = {
key: "fl",
"value": fl_list
}
search_params['searchParams'].append(fl_dict)
if params:
for dkey, value in params.items():
custom_dict = {
key: str(dkey),
"value": str(value)
}
search_params['searchParams'].append(custom_dict)
return search_params
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._commcell_object._update_response_(response.text))
def _do_stream_download(self, guid, file_name, download_location):
"""does stream download to file to local machine
Args:
guid (str) -- Download GUID
download_location (str) -- path on local machine to download requested file
file_name (str) -- File name for download
Returns:
Str -- File path containing downloaded file
Raise:
SDKException:
if failed to do stream download
"""
request = copy.deepcopy(EdiscoveryConstants.EXPORT_DOWNLOAD_REQ)
request['responseFileName'] = file_name
for param in request['fileParams']:
if param['id'] == 2:
param['name'] = guid
flag, response = self._cvpysdk_object.make_request(
'POST', self._services['DOWNLOAD_PACKAGE'], request
)
if flag:
error_list = response.json().get('errList')
file_content = response.json().get('fileContent', {})
if error_list:
raise SDKException('EdiscoveryClients', '102', 'Error: {0}'.format(error_list))
file_name = file_content.get('fileName', file_name)
request_id = file_content['requestId']
# full path of the file on local machine to be downloaded
download_path = os.path.join(download_location, file_name)
# execute request to get the stream of content
# using request id returned in the previous response
request['requestId'] = request_id
flag1, response1 = self._cvpysdk_object.make_request(
'POST',
self._services['DOWNLOAD_VIA_STREAM'],
request,
stream=True
)
# download chunks of 1MB each
chunk_size = 1024 ** 2
if flag1:
with open(download_path, "wb") as file_pointer:
for content in response1.iter_content(chunk_size=chunk_size):
file_pointer.write(content)
else:
self._response_not_success(response1)
else:
self._response_not_success(response)
return download_path
def get_handler_id(self, handler_name="default"):
"""returns the id of given handler name
Args:
handler_name (str) -- Handler name(Default: default)
Returns:
int -- Handler id
Raises:
SDKException:
if failed to find handler
if response is empty
"""
if not isinstance(self._class_obj, EdiscoveryDatasource):
return 0
flag, response = self._cvpysdk_object.make_request(
'GET', self._API_GET_DEFAULT_HANDLER % self._data_source_id)
if flag:
if response.json() and 'handlerInfos' in response.json():
handler_list = response.json()['handlerInfos']
if not isinstance(handler_list, list):
raise SDKException('EdiscoveryClients', '102', "Failed to get Datasource/Handler details")
for handler in handler_list:
if handler['handlerName'].lower() == handler_name.lower():
return handler['handlerId']
else:
raise SDKException('EdiscoveryClients', '102', 'No Handler found with given name')
raise SDKException('EdiscoveryClients', '102', 'Unknown response while fetching datasource details')
self._response_not_success(response)
def export(self, criteria=None, attr_list=None, params=None):
"""do export to CSV on data
Args:
criteria (str) -- containing criteria for query
(Default : None - Exports all docs)
Example :
1) Size filter --> Size:[10 TO 1024]
2) File name filter --> FileName_idx:09_23*
attr_list (set) -- Column names to be returned in results.
Acts as 'fl' in query
params (dict) -- Any other params which needs to be passed
Example : { "start" : "0" }
Returns:
str -- export operation token
Raises:
SDKException:
if failed to perform export
"""
if criteria and not isinstance(criteria, str):
raise SDKException('EdiscoveryClients', '101')
search_params = self.form_search_params(criteria=criteria, attr_list=attr_list,
params=params)
flag, response = self._cvpysdk_object.make_request(
'POST', self._API_EXPORT % self.get_handler_id(), search_params
)
if flag:
if response.json():
response = response.json()
if 'errorCode' in response and response['errorCode'] != 0:
raise SDKException(
'EdiscoveryClients',
'102',
f"Export failed with error : {response.get('errLogMessage','')}")
elif 'customMap' in response and 'name' in response['customMap']:
return response['customMap']['name']
raise SDKException('EdiscoveryClients', '102', f"Failed to search with response - {response.json()}")
raise SDKException('EdiscoveryClients', '113')
self._response_not_success(response)
def search(self, criteria=None, attr_list=None, params=None):
"""do searches on data source and returns document details
Args:
criteria (str) -- containing criteria for query
(Default : None - returns all docs)
Example :
1) Size filter --> Size:[10 TO 1024]
2) File name filter --> FileName_idx:09_23*
attr_list (set) -- Column names to be returned in results.
Acts as 'fl' in query
params (dict) -- Any other params which needs to be passed
Example : { "start" : "0" }
Returns:
int,list(dict),dict -- Containing document count, document details & facet details(if any)
Raises:
SDKException:
if failed to perform search
"""
if criteria and not isinstance(criteria, str):
raise SDKException('EdiscoveryClients', '101')
search_params = self.form_search_params(criteria=criteria, attr_list=attr_list,
params=params)
flag, response = self._cvpysdk_object.make_request(
'POST', self._API_SEARCH % (self._search_entity_type, self._search_entity_id), search_params
)
if flag:
if response.json():
if 'errorCode' in response.json() and response.json()['errorCode'] != 0:
raise SDKException(
'EdiscoveryClients',
'102',
f"Failed to perform search - {response.json().get('errLogMessage','')}")
if 'response' in response.json() and 'docs' in response.json()['response']:
if 'facets' not in response.json():
return response.json()['response']['numFound'], response.json()['response']['docs'], {}
return response.json()['response']['numFound'], response.json()[
'response']['docs'], response.json()['facets']
raise SDKException('EdiscoveryClients', '102', f"Failed to search with response - {response.json()}")
raise SDKException('EdiscoveryClients', '112')
self._response_not_success(response)
def _get_associations(self):
"""returns the associations for this client
Args:
None
Returns:
Dict -- Containing associations details
Raises: