forked from JupiterOne/jupiterone-api-client-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
1276 lines (1006 loc) · 44.3 KB
/
client.py
File metadata and controls
1276 lines (1006 loc) · 44.3 KB
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
""" Python SDK for JupiterOne GraphQL API """
# pylint: disable=W0212,no-name-in-module
# see https://github.com/PyCQA/pylint/issues/409
import json
from warnings import warn
from typing import Dict, List, Union
from datetime import datetime
import time
import re
import requests
from requests.adapters import HTTPAdapter, Retry
from retrying import retry
from jupiterone.errors import (
JupiterOneClientError,
JupiterOneApiRetryError,
JupiterOneApiError,
)
from jupiterone.constants import (
J1QL_SKIP_COUNT,
J1QL_LIMIT_COUNT,
QUERY_V1,
CREATE_ENTITY,
DELETE_ENTITY,
UPDATE_ENTITY,
CREATE_RELATIONSHIP,
UPDATE_RELATIONSHIP,
DELETE_RELATIONSHIP,
CURSOR_QUERY_V1,
CREATE_INSTANCE,
INTEGRATION_JOB_VALUES,
INTEGRATION_INSTANCE_EVENT_VALUES,
ALL_PROPERTIES,
GET_ENTITY_RAW_DATA,
CREATE_SMARTCLASS,
CREATE_SMARTCLASS_QUERY,
EVALUATE_SMARTCLASS,
GET_SMARTCLASS_DETAILS,
J1QL_FROM_NATURAL_LANGUAGE,
LIST_RULE_INSTANCES,
CREATE_RULE_INSTANCE,
DELETE_RULE_INSTANCE,
UPDATE_RULE_INSTANCE,
EVALUATE_RULE_INSTANCE,
QUESTIONS,
COMPLIANCE_FRAMEWORK_ITEM,
LIST_COLLECTION_RESULTS,
GET_RAW_DATA_DOWNLOAD_URL,
FIND_INTEGRATION_DEFINITION,
INTEGRATION_INSTANCES,
INTEGRATION_INSTANCE,
UPDATE_INTEGRATION_INSTANCE,
PARAMETER,
PARAMETER_LIST,
UPSERT_PARAMETER,
)
def retry_on_429(exc):
"""Used to trigger retry on rate limit"""
return isinstance(exc, JupiterOneApiRetryError)
class JupiterOneClient:
"""Python client class for the JupiterOne GraphQL API"""
# pylint: disable=too-many-instance-attributes
DEFAULT_URL = "https://graphql.us.jupiterone.io"
SYNC_API_URL = "https://api.us.jupiterone.io"
RETRY_OPTS = {
"wait_exponential_multiplier": 1000,
"wait_exponential_max": 10000,
"stop_max_delay": 300000,
"retry_on_exception": retry_on_429,
}
def __init__(self, account: str = None, token: str = None, url: str = DEFAULT_URL, sync_url: str = SYNC_API_URL):
self.account = account
self.token = token
self.graphql_url = url
self.sync_url = sync_url
self.headers = {
"Authorization": "Bearer {}".format(self.token),
"JupiterOne-Account": self.account,
"Content-Type": "application/json"
}
@property
def account(self):
"""Your JupiterOne account ID"""
return self._account
@account.setter
def account(self, value: str):
"""Your JupiterOne account ID"""
if not value:
raise JupiterOneClientError("account is required")
self._account = value
@property
def token(self):
"""Your JupiterOne access token"""
return self._token
@token.setter
def token(self, value: str):
"""Your JupiterOne access token"""
if not value:
raise JupiterOneClientError("token is required")
self._token = value
# pylint: disable=R1710
@retry(**RETRY_OPTS)
def _execute_query(self, query: str, variables: Dict = None) -> Dict:
"""Executes query against graphql endpoint"""
data = {"query": query}
if variables:
data.update(variables=variables)
# Always ask for variableResultSize
data.update(flags={"variableResultSize": True})
# initiate requests session and implement retry logic of 5 request retries with 1 second between
s = requests.Session()
retries = Retry(total=5, backoff_factor=1, status_forcelist=[502, 503, 504])
s.mount('https://', HTTPAdapter(max_retries=retries))
response = s.post(
self.graphql_url, headers=self.headers, json=data, timeout=60
)
# It is still unclear if all responses will have a status
# code of 200 or if 429 will eventually be used to
# indicate rate limits being hit. J1 devs are aware.
if response.status_code == 200:
if response._content:
content = json.loads(response._content)
if "errors" in content:
errors = content["errors"]
if len(errors) == 1:
if "429" in errors[0]["message"]:
raise JupiterOneApiRetryError(
"JupiterOne API rate limit exceeded"
)
raise JupiterOneApiError(content.get("errors"))
return response.json()
elif response.status_code == 401:
raise JupiterOneApiError(
"401: Unauthorized. Please supply a valid account id and API token."
)
elif response.status_code in [429, 503]:
raise JupiterOneApiRetryError("JupiterOne API rate limit exceeded.")
elif response.status_code in [504]:
raise JupiterOneApiRetryError("Gateway Timeout.")
elif response.status_code in [500]:
raise JupiterOneApiError("JupiterOne API internal server error.")
else:
content = response._content
if isinstance(content, (bytes, bytearray)):
content = content.decode("utf-8")
if "application/json" in response.headers.get("Content-Type", "text/plain"):
data = json.loads(content)
content = data.get("error", data.get("errors", content))
raise JupiterOneApiError("{}:{}".format(response.status_code, content))
def _cursor_query(
self, query: str, cursor: str = None, include_deleted: bool = False
) -> Dict:
"""Performs a V1 graph query using cursor pagination
args:
query (str): Query text
cursor (str): A pagination cursor for the initial query
include_deleted (bool): Include recently deleted entities in query/search
"""
# If the query itself includes a LIMIT then we must parse that and check if we've reached
# or exceeded the required number of results.
limit_match = re.search(r"(?i)LIMIT\s+(?P<inline_limit>\d+)", query)
if limit_match:
result_limit = int(limit_match.group("inline_limit"))
else:
result_limit = False
results: List = []
while True:
variables = {"query": query, "includeDeleted": include_deleted}
if cursor is not None:
variables["cursor"] = cursor
response = self._execute_query(query=CURSOR_QUERY_V1, variables=variables)
data = response["data"]["queryV1"]["data"]
# This means it's a "TREE" query and we have everything
if "vertices" in data and "edges" in data:
return data
results.extend(data)
if result_limit and len(results) >= result_limit:
# We can stop paginating if we've collected enough results based on the requested limit
break
elif (
"cursor" in response["data"]["queryV1"]
and response["data"]["queryV1"]["cursor"] is not None
):
# We got a cursor and haven't collected enough results
cursor = response["data"]["queryV1"]["cursor"]
else:
# No cursor returned so we're done
break
# If we detected an inline LIMIT make sure we only return that many results
if result_limit:
return {"data": results[:result_limit]}
# Return everything
return {"data": results}
def _limit_and_skip_query(
self,
query: str,
skip: int = J1QL_SKIP_COUNT,
limit: int = J1QL_LIMIT_COUNT,
include_deleted: bool = False,
) -> Dict:
results: List = []
page: int = 0
while True:
variables = {
"query": f"{query} SKIP {page * skip} LIMIT {limit}",
"includeDeleted": include_deleted,
}
response = self._execute_query(query=QUERY_V1, variables=variables)
data = response["data"]["queryV1"]["data"]
# If tree query then no pagination
if "vertices" in data and "edges" in data:
return data
if len(data) < J1QL_SKIP_COUNT:
results.extend(data)
break
results.extend(data)
page += 1
return {"data": results}
def _execute_syncapi_request(self, endpoint: str, payload: Dict = None) -> Dict:
"""Executes POST request to SyncAPI endpoints"""
# initiate requests session and implement retry logic of 5 request retries with 1 second between
s = requests.Session()
retries = Retry(total=5, backoff_factor=1, status_forcelist=[502, 503, 504])
s.mount('https://', HTTPAdapter(max_retries=retries))
response = s.post(
self.sync_url + endpoint, headers=self.headers, json=payload, timeout=60
)
# It is still unclear if all responses will have a status
# code of 200 or if 429 will eventually be used to
# indicate rate limits being hit. J1 devs are aware.
if response.status_code == 200:
if response._content:
content = json.loads(response._content)
if "errors" in content:
errors = content["errors"]
if len(errors) == 1:
if "429" in errors[0]["message"]:
raise JupiterOneApiRetryError(
"JupiterOne API rate limit exceeded"
)
raise JupiterOneApiError(content.get("errors"))
return response.json()
elif response.status_code == 401:
raise JupiterOneApiError(
"401: Unauthorized. Please supply a valid account id and API token."
)
elif response.status_code in [429, 503]:
raise JupiterOneApiRetryError("JupiterOne API rate limit exceeded.")
elif response.status_code in [504]:
raise JupiterOneApiRetryError("Gateway Timeout.")
elif response.status_code in [500]:
raise JupiterOneApiError("JupiterOne API internal server error.")
else:
content = response._content
if isinstance(content, (bytes, bytearray)):
content = content.decode("utf-8")
if "application/json" in response.headers.get("Content-Type", "text/plain"):
data = json.loads(content)
content = data.get("error", data.get("errors", content))
raise JupiterOneApiError("{}:{}".format(response.status_code, content))
def query_v1(self, query: str, **kwargs) -> Dict:
"""Performs a V1 graph query
args:
query (str): Query text
skip (int): Skip entity count
limit (int): Limit entity count
cursor (str): A pagination cursor for the initial query
include_deleted (bool): Include recently deleted entities in query/search
"""
uses_limit_and_skip: bool = "skip" in kwargs.keys() or "limit" in kwargs.keys()
skip: int = kwargs.pop("skip", J1QL_SKIP_COUNT)
limit: int = kwargs.pop("limit", J1QL_LIMIT_COUNT)
include_deleted: bool = kwargs.pop("include_deleted", False)
cursor: str = kwargs.pop("cursor", None)
if uses_limit_and_skip:
warn(
"limit and skip pagination is no longer a recommended method for pagination. "
"To read more about using cursors checkout the JupiterOne documentation: "
"https://docs.jupiterone.io/features/admin/parameters#query-parameterlist",
DeprecationWarning,
stacklevel=2,
)
return self._limit_and_skip_query(
query=query, skip=skip, limit=limit, include_deleted=include_deleted
)
else:
return self._cursor_query(
query=query, cursor=cursor, include_deleted=include_deleted
)
def create_entity(self, **kwargs) -> Dict:
"""Creates an entity in graph. It will also update an existing entity.
args:
entity_key (str): Unique key for the entity
entity_type (str): Value for _type of entity
entity_class (str): Value for _class of entity
timestamp (int): Specify createdOn timestamp
properties (dict): Dictionary of key/value entity properties
"""
variables = {
"entityKey": kwargs.pop("entity_key"),
"entityType": kwargs.pop("entity_type"),
"entityClass": kwargs.pop("entity_class"),
}
timestamp: int = kwargs.pop("timestamp", None)
properties: Dict = kwargs.pop("properties", None)
if timestamp:
variables.update(timestamp=timestamp)
if properties:
variables.update(properties=properties)
response = self._execute_query(query=CREATE_ENTITY, variables=variables)
return response["data"]["createEntity"]
def delete_entity(self, entity_id: str = None) -> Dict:
"""Deletes an entity from the graph. Note this is a hard delete.
args:
entity_id (str): Entity ID for entity to delete
"""
variables = {"entityId": entity_id}
response = self._execute_query(DELETE_ENTITY, variables=variables)
return response["data"]["deleteEntity"]
def update_entity(self, entity_id: str = None, properties: Dict = None) -> Dict:
"""
Update an existing entity.
args:
entity_id (str): The _id of the entity to update
properties (dict): Dictionary of key/value entity properties
"""
variables = {"entityId": entity_id, "properties": properties}
response = self._execute_query(UPDATE_ENTITY, variables=variables)
return response["data"]["updateEntity"]
def create_relationship(self, **kwargs) -> Dict:
"""
Create a relationship (edge) between two entities (vertices).
args:
relationship_key (str): Unique key for the relationship
relationship_type (str): Value for _type of relationship
relationship_class (str): Value for _class of relationship
from_entity_id (str): Entity ID of the source vertex
to_entity_id (str): Entity ID of the destination vertex
"""
variables = {
"relationshipKey": kwargs.pop("relationship_key"),
"relationshipType": kwargs.pop("relationship_type"),
"relationshipClass": kwargs.pop("relationship_class"),
"fromEntityId": kwargs.pop("from_entity_id"),
"toEntityId": kwargs.pop("to_entity_id"),
}
properties = kwargs.pop("properties", None)
if properties:
variables["properties"] = properties
response = self._execute_query(query=CREATE_RELATIONSHIP, variables=variables)
return response["data"]["createRelationship"]
def update_relationship(self, **kwargs) -> Dict:
"""
Update a relationship (edge) between two entities (vertices).
args:
relationship_id (str): Unique _id of the relationship
properties (dict): Dictionary of key/value relationship properties
"""
now_dt = datetime.now()
variables = {
"relationshipId": kwargs.pop("relationship_id"),
"timestamp": datetime.strptime(str(now_dt), "%Y-%m-%d %H:%M:%S.%f").timestamp()
}
properties = kwargs.pop("properties", None)
if properties:
variables["properties"] = properties
response = self._execute_query(query=UPDATE_RELATIONSHIP, variables=variables)
return response["data"]["updateRelationship"]
def delete_relationship(self, relationship_id: str = None):
"""Deletes a relationship between two entities.
args:
relationship_id (str): The ID of the relationship
"""
variables = {"relationshipId": relationship_id}
response = self._execute_query(DELETE_RELATIONSHIP, variables=variables)
return response["data"]["deleteRelationship"]
def create_integration_instance(self,
instance_name: str = None,
instance_description: str = None,
integration_definition_id: str = "8013680b-311a-4c2e-b53b-c8735fd97a5c"):
"""Creates a new Custom Integration Instance.
args:
instance_name (str): The "Account name" for integration instance
instance_description (str): The "Description" for integration instance
integration_definition_id (str): The "Integration definition ID" for integration instance,
if no parameter is passed, then the Custom Integration definition ID will be used.
"""
variables = {
"instance": {
"name": instance_name,
"description": instance_description,
"integrationDefinitionId": integration_definition_id,
"pollingInterval": "DISABLED",
"config": {
"@tag": {
"Production": False,
"AccountName": True
}
},
"pollingIntervalCronExpression": {},
"ingestionSourcesOverrides": []
}
}
response = self._execute_query(CREATE_INSTANCE, variables=variables)
return response['data']['createIntegrationInstance']
def fetch_all_entity_properties(self):
"""Fetch list of aggregated property keys from all entities in the graph.
"""
response = self._execute_query(query=ALL_PROPERTIES)
return_list = []
for i in response['data']['getAllAssetProperties']:
if i.startswith(('parameter.', 'tag.')) == False:
return_list.append(i)
return return_list
def fetch_all_entity_tags(self):
"""Fetch list of aggregated property keys from all entities in the graph.
"""
response = self._execute_query(query=ALL_PROPERTIES)
return_list = []
for i in response['data']['getAllAssetProperties']:
if i.startswith(('tag.')) == True:
return_list.append(i)
return return_list
def fetch_entity_raw_data(self, entity_id: str = None):
"""Fetch the contents of raw data for a given entity in a J1 Account.
"""
variables = {
"entityId": entity_id,
"source": "integration-managed"
}
response = self._execute_query(query=GET_ENTITY_RAW_DATA, variables=variables)
return response
def start_sync_job(self, instance_id: str = None, sync_mode: str = None, source: str = None,):
"""Start a synchronization job.
args:
instance_id (str): The "integrationInstanceId" request param for synchronization job
sync_mode (str): The "syncMode" request body property for synchronization job. "DIFF", "CREATE_OR_UPDATE", or "PATCH"
source (str): The "source" request body property for synchronization job. "api" or "integration-external"
"""
endpoint = "/persister/synchronization/jobs"
data = {
"source": source,
"integrationInstanceId": instance_id,
"syncMode": sync_mode
}
response = self._execute_syncapi_request(endpoint=endpoint, payload=data)
return response
def upload_entities_batch_json(self, instance_job_id: str = None, entities_list: list = None):
"""Upload batch of entities.
args:
instance_job_id (str): The "Job ID" for the Custom Integration job
entities_list (list): List of Dictionaries containing entities data to upload
"""
endpoint = f"/persister/synchronization/jobs/{instance_job_id}/entities"
data = {
"entities": entities_list
}
response = self._execute_syncapi_request(endpoint=endpoint, payload=data)
return response
def upload_relationships_batch_json(self, instance_job_id: str = None, relationships_list: list = None):
"""Upload batch of relationships.
args:
instance_job_id (str): The "Job ID" for the Custom Integration job
relationships_list (list): List of Dictionaries containing relationships data to upload
"""
endpoint = f"/persister/synchronization/jobs/{instance_job_id}/relationships"
data = {
"relationships": relationships_list
}
response = self._execute_syncapi_request(endpoint=endpoint, payload=data)
return response
def upload_combined_batch_json(self, instance_job_id: str = None, combined_payload: Dict = None):
"""Upload batch of entities and relationships together.
args:
instance_job_id (str): The "Job ID" for the Custom Integration job.
combined_payload (list): Dictionary containing combined entities and relationships data to upload.
"""
endpoint = f"/persister/synchronization/jobs/{instance_job_id}/upload"
response = self._execute_syncapi_request(endpoint=endpoint, payload=combined_payload)
return response
def bulk_delete_entities(self, instance_job_id: str = None, entities_list: list = None):
"""Send a request to bulk delete existing entities.
args:
instance_job_id (str): The "Job ID" for the Custom Integration job.
entities_list (list): List of dictionaries containing entities _id's to be deleted.
"""
endpoint = f"/persister/synchronization/jobs/{instance_job_id}/upload"
data = {
"deleteEntities": entities_list
}
response = self._execute_syncapi_request(endpoint=endpoint, payload=data)
return response
def finalize_sync_job(self, instance_job_id: str = None):
"""Start a synchronization job.
args:
instance_job_id (str): The "Job ID" for the Custom Integration job
"""
endpoint = f"/persister/synchronization/jobs/{instance_job_id}/finalize"
data = {}
response = self._execute_syncapi_request(endpoint=endpoint, payload=data)
return response
def fetch_integration_jobs(self, instance_id: str = None):
"""Fetch Integration Job details from defined integration instance.
args:
instance_id (str): The "integrationInstanceId" of the integration to fetch jobs from.
"""
variables = {
"integrationInstanceId": instance_id,
"size": 100
}
response = self._execute_query(INTEGRATION_JOB_VALUES, variables=variables)
return response['data']['integrationJobs']
def fetch_integration_job_events(self, instance_id: str = None, instance_job_id: str = None):
"""Fetch events within an integration job run.
args:
instance_id (str): The integration Instance Id of the integration to fetch job events from.
instance_job_id (str): The integration Job ID of the integration to fetch job events from.
"""
variables = {
"integrationInstanceId": instance_id,
"jobId": instance_job_id,
"size": 1000
}
response = self._execute_query(INTEGRATION_INSTANCE_EVENT_VALUES, variables=variables)
return response['data']['integrationEvents']
def get_integration_definition_details(self, integration_type: str = None):
"""Fetch the Integration Definition Details for a given integration type.
"""
variables = {
"integrationType": integration_type,
"includeConfig": True
}
response = self._execute_query(FIND_INTEGRATION_DEFINITION, variables=variables)
return response
def fetch_integration_instances(self, definition_id: str = None):
"""Fetch all configured Instances for a given integration type.
"""
variables = {
"definitionId": definition_id,
"limit": 100
}
response = self._execute_query(INTEGRATION_INSTANCES, variables=variables)
return response
def get_integration_instance_details(self, instance_id: str = None):
"""Fetch configuration details for a single configured Integration Instance.
"""
variables = {
"integrationInstanceId": instance_id
}
response = self._execute_query(INTEGRATION_INSTANCE, variables=variables)
return response
def update_integration_instance_config_value(self,
instance_id: str = None,
config_key: str = None,
config_value: str = None):
"""Update a single config k:v pair existing on a configured Integration Instance.
"""
# fetch existing instnace configuration
instance_config = self.get_integration_instance_details(instance_id=instance_id)
config_dict = instance_config['data']['integrationInstance']['config']
if str(config_dict.get(config_key, "Not Found")) != "Not Found":
# update config key value with new provided value
config_dict[config_key] = config_value
instance_config['data']['integrationInstance']['config'] = config_dict
# remove externalId to not include in update payload
if "externalId" in instance_config["data"]["integrationInstance"]["config"]:
del instance_config["data"]["integrationInstance"]["config"][
"externalId"
]
# prepare variables GraphQL payload for updating config
instance_details = instance_config['data']['integrationInstance']
variables = {
"id": instance_details['id'],
"update": {
"pollingInterval": instance_details['pollingInterval'],
"config": instance_details['config'],
"description": instance_details['description'],
"name": instance_details['name'],
"collectorPoolId": instance_details['collectorPoolId'],
"pollingIntervalCronExpression": instance_details['pollingIntervalCronExpression'],
"ingestionSourcesOverrides": instance_details['ingestionSourcesOverrides']
}
}
# remove problem fields from previous response
if variables["update"].get("pollingIntervalCronExpression") is not None:
if "__typename" in ["update"]["pollingIntervalCronExpression"]:
del variables["update"]["pollingIntervalCronExpression"][
"__typename"
]
ingestion_sources = instance_details.get("ingestionSourcesOverrides", None)
if ingestion_sources is not None:
for ingestion_source in instance_details["ingestionSourcesOverrides"]:
ingestion_source.pop(
"__typename", None
) # Removes key if it exists, ignores if not
response = self._execute_query(UPDATE_INTEGRATION_INSTANCE, variables=variables)
return response
else:
return "Provided 'config_key' not found in existing Integration Instance config"
def create_smartclass(self, smartclass_name: str = None, smartclass_description: str = None):
"""Creates a new Smart Class within Assets.
args:
smartclass_name (str): The "Smart class name" for Smart Class to be created.
smartclass_description (str): The "Description" for Smart Class to be created.
"""
variables = {
"input": {
"tagName": smartclass_name,
"description": smartclass_description
}
}
response = self._execute_query(CREATE_SMARTCLASS, variables=variables)
return response['data']['createSmartClass']
def create_smartclass_query(self, smartclass_id: str = None, query: str = None, query_description: str = None):
"""Creates a new J1QL Query within a defined Smart Class.
args:
smartclass_id (str): The unique ID of the Smart Class the query is created within.
query (str): The J1QL for the query being created.
query_description (str): The description of the query being created.
"""
variables = {
"input": {
"smartClassId": smartclass_id,
"query": query,
"description": query_description
}
}
response = self._execute_query(CREATE_SMARTCLASS_QUERY, variables=variables)
return response['data']['createSmartClassQuery']
def evaluate_smartclass(self, smartclass_id: str = None):
"""Execute an on-demand Evaluation of a defined Smartclass.
args:
smartclass_id (str): The unique ID of the Smart Class to trigger the evaluation for.
"""
variables = {
"smartClassId": smartclass_id
}
response = self._execute_query(EVALUATE_SMARTCLASS, variables=variables)
return response['data']['evaluateSmartClassRule']
def get_smartclass_details(self, smartclass_id: str = None):
"""Fetch config details from defined Smart Class.
args:
smartclass_id (str): The unique ID of the Smart Class to fetch details from.
"""
variables = {
"id": smartclass_id
}
response = self._execute_query(GET_SMARTCLASS_DETAILS, variables=variables)
return response['data']['smartClass']
def generate_j1ql(self, natural_language_prompt: str = None):
"""Generate J1QL query syntax from natural language user input.
args:
natural_language_prompt (str): The naturalLanguageQuery prompt input to generate J1QL from.
"""
variables = {
"input": {
"naturalLanguageQuery": natural_language_prompt
}
}
response = self._execute_query(J1QL_FROM_NATURAL_LANGUAGE, variables=variables)
return response['data']['j1qlFromNaturalLanguage']
def list_alert_rules(self):
"""List all defined Alert Rules configured in J1 account
"""
results = []
data = {
"query": LIST_RULE_INSTANCES,
"flags": {
"variableResultSize": True
}
}
r = requests.post(url=self.graphql_url, headers=self.headers, json=data, verify=True).json()
results.extend(r['data']['listRuleInstances']['questionInstances'])
while r['data']['listRuleInstances']['pageInfo']['hasNextPage'] == True:
cursor = r['data']['listRuleInstances']['pageInfo']['endCursor']
# cursor query until last page fetched
data = {
"query": LIST_RULE_INSTANCES,
"variables": {
"cursor": cursor
},
"flags":{
"variableResultSize": True
}
}
r = requests.post(url=self.graphql_url, headers=self.headers, json=data, verify=True).json()
results.extend(r['data']['listRuleInstances']['questionInstances'])
return results
def get_alert_rule_details(self, rule_id: str = None):
"""Get details of a single defined Alert Rule configured in J1 account
"""
results = []
data = {
"query": LIST_RULE_INSTANCES,
"flags": {
"variableResultSize": True
}
}
r = requests.post(url=self.graphql_url, headers=self.headers, json=data, verify=True).json()
results.extend(r['data']['listRuleInstances']['questionInstances'])
while r['data']['listRuleInstances']['pageInfo']['hasNextPage'] == True:
cursor = r['data']['listRuleInstances']['pageInfo']['endCursor']
# cursor query until last page fetched
data = {
"query": LIST_RULE_INSTANCES,
"variables": {
"cursor": cursor
},
"flags":{
"variableResultSize": True
}
}
r = requests.post(url=self.graphql_url, headers=self.headers, json=data, verify=True).json()
results.extend(r['data']['listRuleInstances']['questionInstances'])
# pick result out of list of results by 'id' key
item = next((item for item in results if item['id'] == rule_id), None)
if item:
return item
else:
return 'Alert Rule not found for provided ID in configured J1 Account'
def create_alert_rule(self,
name: str = None,
description: str = None,
tags: List[str] = None,
polling_interval: str = None,
severity: str = None,
j1ql: str = None,
action_configs: Dict = None):
"""Create Alert Rule Configuration in J1 account
"""
variables = {
"instance": {
"name": name,
"description": description,
"notifyOnFailure": True,
"triggerActionsOnNewEntitiesOnly": True,
"ignorePreviousResults": False,
"operations": [
{
"when": {
"type": "FILTER",
"condition": [
"AND",
[
"queries.query0.total",
">",
0
]
]
},
"actions": [
{
"type": "SET_PROPERTY",
"targetProperty": "alertLevel",
"targetValue": severity
},
{
"type": "CREATE_ALERT"
}
]
}
],
"outputs": [
"alertLevel"
],
"pollingInterval": polling_interval,
"question": {
"queries": [
{
"query": j1ql,
"name": "query0",
"version": "v1",
"includeDeleted": False
}
]
},
"specVersion": 1,
"tags": tags,
"templates": {}
}
}
if action_configs:
variables['instance']['operations'][0]['actions'].append(action_configs)
print(variables)
response = self._execute_query(CREATE_RULE_INSTANCE, variables=variables)
return response['data']['createInlineQuestionRuleInstance']
def delete_alert_rule(self, rule_id: str = None):
"""Delete a single Alert Rule configured in J1 account
"""
variables = {
"id": rule_id
}
response = self._execute_query(DELETE_RULE_INSTANCE, variables=variables)