-
Notifications
You must be signed in to change notification settings - Fork 173
/
Copy pathgraph_magic.py
1680 lines (1473 loc) · 79.2 KB
/
graph_magic.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
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
from __future__ import print_function # Python 2/3 compatibility
import argparse
import logging
import json
import time
import datetime
import os
import uuid
from enum import Enum
from json import JSONDecodeError
from graph_notebook.network.opencypher.OCNetwork import OCNetwork
import ipywidgets as widgets
from SPARQLWrapper import SPARQLWrapper
from botocore.session import get_session
from gremlin_python.driver.protocol import GremlinServerError
from IPython.core.display import HTML, display_html, display
from IPython.core.magic import (Magics, magics_class, cell_magic, line_magic, line_cell_magic, needs_local_scope)
from ipywidgets.widgets.widget_description import DescriptionStyle
from requests import HTTPError
import graph_notebook
from graph_notebook.configuration.generate_config import generate_default_config, DEFAULT_CONFIG_LOCATION, \
AuthModeEnum, Configuration
from graph_notebook.decorators.decorators import display_exceptions, magic_variables
from graph_notebook.magics.ml import neptune_ml_magic_handler, generate_neptune_ml_parser
from graph_notebook.magics.streams import StreamViewer
from graph_notebook.neptune.client import ClientBuilder, Client, VALID_FORMATS, PARALLELISM_OPTIONS, PARALLELISM_HIGH, \
LOAD_JOB_MODES, MODE_AUTO, FINAL_LOAD_STATUSES, SPARQL_ACTION, FORMAT_CSV, FORMAT_OPENCYPHER, FORMAT_NTRIPLE, \
FORMAT_NQUADS, FORMAT_RDFXML, FORMAT_TURTLE
from graph_notebook.network import SPARQLNetwork
from graph_notebook.network.gremlin.GremlinNetwork import parse_pattern_list_str, GremlinNetwork
from graph_notebook.visualization.rows_and_columns import sparql_get_rows_and_columns, opencypher_get_rows_and_columns
from graph_notebook.visualization.template_retriever import retrieve_template
from graph_notebook.configuration.get_config import get_config, get_config_from_dict
from graph_notebook.seed.load_query import get_data_sets, get_queries, normalize_model_name
from graph_notebook.widgets import Force
from graph_notebook.options import OPTIONS_DEFAULT_DIRECTED, vis_options_merge
from graph_notebook.magics.metadata import build_sparql_metadata_from_query, build_gremlin_metadata_from_query, \
build_opencypher_metadata_from_query
sparql_table_template = retrieve_template("sparql_table.html")
sparql_explain_template = retrieve_template("sparql_explain.html")
sparql_construct_template = retrieve_template("sparql_construct.html")
gremlin_table_template = retrieve_template("gremlin_table.html")
opencypher_table_template = retrieve_template("opencypher_table.html")
pre_container_template = retrieve_template("pre_container.html")
loading_wheel_template = retrieve_template("loading_wheel.html")
error_template = retrieve_template("error.html")
loading_wheel_html = loading_wheel_template.render()
DEFAULT_LAYOUT = widgets.Layout(max_height='600px', overflow='scroll', width='100%')
logging.basicConfig()
logger = logging.getLogger("graph_magic")
DEFAULT_MAX_RESULTS = 1000
GREMLIN_CANCEL_HINT_MSG = '''You must supply a string queryId when using --cancelQuery,
for example: %gremlin_status --cancelQuery --queryId my-query-id'''
SPARQL_CANCEL_HINT_MSG = '''You must supply a string queryId when using --cancelQuery,
for example: %sparql_status --cancelQuery --queryId my-query-id'''
OPENCYPHER_CANCEL_HINT_MSG = '''You must supply a string queryId when using --cancelQuery,
for example: %opencypher_status --cancelQuery --queryId my-query-id'''
SEED_LANGUAGE_OPTIONS = ['', 'Property_Graph', 'RDF']
LOADER_FORMAT_CHOICES = ['']
LOADER_FORMAT_CHOICES.extend(VALID_FORMATS)
serializers_map = {
"MIME_JSON": "application/json",
"GRAPHSON_V2D0": "application/vnd.gremlin-v2.0+json",
"GRAPHSON_V3D0": "application/vnd.gremlin-v3.0+json",
"GRYO_V3D0": "application/vnd.gremlin-v3.0+gryo",
"GRAPHBINARY_V1D0": "application/vnd.graphbinary-v1.0"
}
DEFAULT_NAMEDGRAPH_URI = "http://aws.amazon.com/neptune/vocab/v01/DefaultNamedGraph"
DEFAULT_BASE_URI = "http://aws.amazon.com/neptune/default"
RDF_LOAD_FORMATS = [FORMAT_NTRIPLE, FORMAT_NQUADS, FORMAT_RDFXML, FORMAT_TURTLE]
BASE_URI_FORMATS = [FORMAT_RDFXML, FORMAT_TURTLE]
class QueryMode(Enum):
DEFAULT = 'query'
EXPLAIN = 'explain'
PROFILE = 'profile'
EMPTY = ''
def store_to_ns(key: str, value, ns: dict = None):
if key == '' or ns is None:
return
ns[key] = value
def str_to_query_mode(s: str) -> QueryMode:
s = s.lower()
for mode in list(QueryMode):
if mode.value == s:
return QueryMode(s)
logger.debug(f'Invalid query mode {s} supplied, defaulting to query.')
return QueryMode.DEFAULT
ACTION_TO_QUERY_TYPE = {
'sparql': 'application/sparql-query',
'sparqlupdate': 'application/sparql-update'
}
def get_query_type(query):
s = SPARQLWrapper('')
s.setQuery(query)
return s.queryType
def query_type_to_action(query_type):
query_type = query_type.upper()
if query_type in ['SELECT', 'CONSTRUCT', 'ASK', 'DESCRIBE']:
return 'sparql'
else:
# TODO: check explicitly for all query types, raise exception for invalid query
return 'sparqlupdate'
# TODO: refactor large magic commands into their own modules like what we do with %neptune_ml
# noinspection PyTypeChecker
@magics_class
class Graph(Magics):
def __init__(self, shell):
# You must call the parent constructor
super(Graph, self).__init__(shell)
self.graph_notebook_config = generate_default_config()
try:
self.config_location = os.getenv('GRAPH_NOTEBOOK_CONFIG', DEFAULT_CONFIG_LOCATION)
self.client: Client = None
self.graph_notebook_config = get_config(self.config_location)
except FileNotFoundError:
print('Could not find a valid configuration. '
'Do not forget to validate your settings using %graph_notebook_config.')
self.max_results = DEFAULT_MAX_RESULTS
self.graph_notebook_vis_options = OPTIONS_DEFAULT_DIRECTED
self._generate_client_from_config(self.graph_notebook_config)
logger.setLevel(logging.ERROR)
def _generate_client_from_config(self, config: Configuration):
if self.client:
self.client.close()
if "amazonaws.com" in config.host:
builder = ClientBuilder() \
.with_host(config.host) \
.with_port(config.port) \
.with_region(config.aws_region) \
.with_tls(config.ssl) \
.with_sparql_path(config.sparql.path)
if config.auth_mode == AuthModeEnum.IAM:
builder = builder.with_iam(get_session())
else:
builder = ClientBuilder() \
.with_host(config.host) \
.with_port(config.port) \
.with_tls(config.ssl) \
.with_sparql_path(config.sparql.path) \
.with_gremlin_traversal_source(config.gremlin.traversal_source)
self.client = builder.build()
@line_cell_magic
@display_exceptions
def graph_notebook_config(self, line='', cell=''):
if cell != '':
data = json.loads(cell)
config = get_config_from_dict(data)
self.graph_notebook_config = config
self._generate_client_from_config(config)
print('set notebook config to:')
print(json.dumps(self.graph_notebook_config.to_dict(), indent=2))
elif line == 'reset':
self.graph_notebook_config = get_config(self.config_location)
print('reset notebook config to:')
print(json.dumps(self.graph_notebook_config.to_dict(), indent=2))
elif line == 'silent':
"""
silent option to that our neptune_menu extension can receive json instead
of python Configuration object
"""
config_dict = self.graph_notebook_config.to_dict()
return print(json.dumps(config_dict, indent=2))
else:
config_dict = self.graph_notebook_config.to_dict()
print(json.dumps(config_dict, indent=2))
return self.graph_notebook_config
@line_magic
def stream_viewer(self,line):
parser = argparse.ArgumentParser()
parser.add_argument('language', type=str.lower, nargs='?', default='gremlin',
help='language (default=gremlin) [gremlin|sparql]',
choices = ['gremlin','sparql'])
parser.add_argument('--limit', type=int, default=10, help='Maximum number of rows to display at a time')
args = parser.parse_args(line.split())
language = args.language
limit = args.limit
uri = self.client.get_uri_with_port()
viewer = StreamViewer(self.client,uri,language,limit=limit)
viewer.show()
@line_magic
def graph_notebook_host(self, line):
if line == '':
print('please specify a host.')
return
# TODO: we should attempt to make a status call to this host before we set the config to this value.
self.graph_notebook_config.host = line
self._generate_client_from_config(self.graph_notebook_config)
print(f'set host to {line}')
@magic_variables
@cell_magic
@needs_local_scope
@display_exceptions
def sparql(self, line='', cell='', local_ns: dict = None):
parser = argparse.ArgumentParser()
parser.add_argument('query_mode', nargs='?', default='query',
help='query mode (default=query) [query|explain]')
parser.add_argument('--path', '-p', default='',
help='prefix path to sparql endpoint. For example, if "foo/bar" were specified, '
'the endpoint called would be host:port/foo/bar')
parser.add_argument('--expand-all', action='store_true')
parser.add_argument('--explain-type', default='dynamic',
help='explain mode to use when using the explain query mode',
choices=['dynamic', 'static', 'details'])
parser.add_argument('--explain-format', default='text/html', help='response format for explain query mode',
choices=['text/csv', 'text/html'])
parser.add_argument('-l', '--label-max-length', type=int, default=10,
help='Specifies max length of vertex labels, in characters. Default is 10')
parser.add_argument('-le', '--edge-label-max-length', type=int, default=10,
help='Specifies max length of edge labels, in characters. Default is 10')
parser.add_argument('--store-to', type=str, default='', help='store query result to this variable')
parser.add_argument('-sp', '--stop-physics', action='store_true', default=False,
help="Disable visualization physics after the initial simulation stabilizes.")
parser.add_argument('-sd', '--simulation-duration', type=int, default=1500,
help='Specifies maximum duration of visualization physics simulation. Default is 1500ms')
parser.add_argument('--silent', action='store_true', default=False, help="Display no query output.")
args = parser.parse_args(line.split())
mode = str_to_query_mode(args.query_mode)
if not args.silent:
tab = widgets.Tab()
titles = []
children = []
first_tab_output = widgets.Output(layout=DEFAULT_LAYOUT)
children.append(first_tab_output)
path = args.path if args.path != '' else self.graph_notebook_config.sparql.path
logger.debug(f'using mode={mode}')
if mode == QueryMode.EXPLAIN:
res = self.client.sparql_explain(cell, args.explain_type, args.explain_format, path=path)
res.raise_for_status()
explain = res.content.decode('utf-8')
store_to_ns(args.store_to, explain, local_ns)
if not args.silent:
sparql_metadata = build_sparql_metadata_from_query(query_type='explain', res=res)
titles.append('Explain')
first_tab_html = sparql_explain_template.render(table=explain)
else:
query_type = get_query_type(cell)
headers = {} if query_type not in ['SELECT', 'CONSTRUCT', 'DESCRIBE'] else {
'Accept': 'application/sparql-results+json'}
query_res = self.client.sparql(cell, path=path, headers=headers)
query_res.raise_for_status()
results = query_res.json()
store_to_ns(args.store_to, results, local_ns)
try:
res = query_res.json()
except JSONDecodeError:
res = query_res.content.decode('utf-8')
store_to_ns(args.store_to, res, local_ns)
if not args.silent:
# Assign an empty value so we can always display to table output.
# We will only add it as a tab if the type of query allows it.
# Because of this, the table_output will only be displayed on the DOM if the query was of type SELECT.
first_tab_html = ""
query_type = get_query_type(cell)
if query_type in ['SELECT', 'CONSTRUCT', 'DESCRIBE']:
logger.debug('creating sparql network...')
titles.append('Table')
sparql_metadata = build_sparql_metadata_from_query(query_type='query', res=query_res,
results=results, scd_query=True)
sn = SPARQLNetwork(label_max_length=args.label_max_length,
edge_label_max_length=args.edge_label_max_length, expand_all=args.expand_all)
sn.extract_prefix_declarations_from_query(cell)
try:
sn.add_results(results)
except ValueError as value_error:
logger.debug(value_error)
logger.debug(f'number of nodes is {len(sn.graph.nodes)}')
if len(sn.graph.nodes) > 0:
self.graph_notebook_vis_options['physics']['disablePhysicsAfterInitialSimulation'] \
= args.stop_physics
self.graph_notebook_vis_options['physics']['simulationDuration'] = args.simulation_duration
f = Force(network=sn, options=self.graph_notebook_vis_options)
titles.append('Graph')
children.append(f)
logger.debug('added sparql network to tabs')
rows_and_columns = sparql_get_rows_and_columns(results)
if rows_and_columns is not None:
table_id = f"table-{str(uuid.uuid4())[:8]}"
first_tab_html = sparql_table_template.render(columns=rows_and_columns['columns'],
rows=rows_and_columns['rows'], guid=table_id)
# Handling CONSTRUCT and DESCRIBE on their own because we want to maintain the previous result
# pattern of showing a tsv with each line being a result binding in addition to new ones.
if query_type == 'CONSTRUCT' or query_type == 'DESCRIBE':
lines = []
for b in results['results']['bindings']:
lines.append(f'{b["subject"]["value"]}\t{b["predicate"]["value"]}\t{b["object"]["value"]}')
raw_output = widgets.Output(layout=DEFAULT_LAYOUT)
with raw_output:
html = sparql_construct_template.render(lines=lines)
display(HTML(html))
children.append(raw_output)
titles.append('Raw')
else:
sparql_metadata = build_sparql_metadata_from_query(query_type='query', res=query_res,
results=results)
json_output = widgets.Output(layout=DEFAULT_LAYOUT)
with json_output:
print(json.dumps(results, indent=2))
children.append(json_output)
titles.append('JSON')
if not args.silent:
metadata_output = widgets.Output(layout=DEFAULT_LAYOUT)
children.append(metadata_output)
titles.append('Query Metadata')
if first_tab_html == "":
tab.children = children[1:] # the first tab is empty, remove it and proceed
else:
tab.children = children
for i in range(len(titles)):
tab.set_title(i, titles[i])
display(tab)
with metadata_output:
display(HTML(sparql_metadata.to_html()))
if first_tab_html != "":
with first_tab_output:
display(HTML(first_tab_html))
@line_magic
@needs_local_scope
@display_exceptions
def sparql_status(self, line='', local_ns: dict = None):
parser = argparse.ArgumentParser()
parser.add_argument('-q', '--queryId', default='',
help='The ID of a running SPARQL query. Only displays the status of the specified query.')
parser.add_argument('-c', '--cancelQuery', action='store_true',
help='Tells the status command to cancel a query. This parameter does not take a value')
parser.add_argument('-s', '--silent', action='store_true',
help='If silent=true then the running query is cancelled and the HTTP response code is 200.'
'If silent is not present or silent=false, '
'the query is cancelled with an HTTP 500 status code.')
parser.add_argument('--store-to', type=str, default='', help='store query result to this variable')
args = parser.parse_args(line.split())
if not args.cancelQuery:
status_res = self.client.sparql_cancel(args.queryId)
status_res.raise_for_status()
res = status_res.json()
else:
if args.queryId == '':
print(SPARQL_CANCEL_HINT_MSG)
return
else:
cancel_res = self.client.sparql_cancel(args.queryId, args.silent)
cancel_res.raise_for_status()
res = cancel_res.json()
store_to_ns(args.store_to, res, local_ns)
print(json.dumps(res, indent=2))
@magic_variables
@cell_magic
@needs_local_scope
@display_exceptions
def gremlin(self, line, cell, local_ns: dict = None):
parser = argparse.ArgumentParser()
parser.add_argument('query_mode', nargs='?', default='query',
help='query mode (default=query) [query|explain|profile]')
parser.add_argument('-p', '--path-pattern', default='', help='path pattern')
parser.add_argument('-g', '--group-by', type=str, default='T.label',
help='Property used to group nodes (e.g. code, T.region) default is T.label')
parser.add_argument('-d', '--display-property', type=str, default='T.label',
help='Property to display the value of on each node, default is T.label')
parser.add_argument('-de', '--edge-display-property', type=str, default='T.label',
help='Property to display the value of on each edge, default is T.label')
parser.add_argument('-l', '--label-max-length', type=int, default=10,
help='Specifies max length of vertex label, in characters. Default is 10')
parser.add_argument('-le', '--edge-label-max-length', type=int, default=10,
help='Specifies max length of edge labels, in characters. Default is 10')
parser.add_argument('--store-to', type=str, default='', help='store query result to this variable')
parser.add_argument('--ignore-groups', action='store_true', default=False, help="Ignore all grouping options")
parser.add_argument('--no-results', action='store_false', default=True,
help='Display only the result count. If not used, all query results will be displayed in '
'the profile report by default.')
parser.add_argument('--chop', type=int, default=250,
help='Property to specify max length of profile results string. Default is 250')
parser.add_argument('--serializer', type=str, default='application/json',
help='Specify how to serialize results. Allowed values are any of the valid MIME type or '
'TinkerPop driver "Serializers" enum values. Default is application/json')
parser.add_argument('--indexOps', action='store_true', default=False,
help='Show a detailed report of all index operations.')
parser.add_argument('-sp', '--stop-physics', action='store_true', default=False,
help="Disable visualization physics after the initial simulation stabilizes.")
parser.add_argument('-sd', '--simulation-duration', type=int, default=1500,
help='Specifies maximum duration of visualization physics simulation. Default is 1500ms')
parser.add_argument('--silent', action='store_true', default=False, help="Display no query output.")
args = parser.parse_args(line.split())
mode = str_to_query_mode(args.query_mode)
logger.debug(f'Arguments {args}')
if not args.silent:
tab = widgets.Tab()
children = []
titles = []
first_tab_output = widgets.Output(layout=DEFAULT_LAYOUT)
children.append(first_tab_output)
if mode == QueryMode.EXPLAIN:
res = self.client.gremlin_explain(cell)
res.raise_for_status()
query_res = res.content.decode('utf-8')
if not args.silent:
gremlin_metadata = build_gremlin_metadata_from_query(query_type='explain', results=query_res, res=res)
titles.append('Explain')
if 'Neptune Gremlin Explain' in query_res:
first_tab_html = pre_container_template.render(content=query_res)
else:
first_tab_html = pre_container_template.render(content='No explain found')
elif mode == QueryMode.PROFILE:
logger.debug(f'results: {args.no_results}')
logger.debug(f'chop: {args.chop}')
logger.debug(f'serializer: {args.serializer}')
logger.debug(f'indexOps: {args.indexOps}')
if args.serializer in serializers_map:
serializer = serializers_map[args.serializer]
else:
serializer = args.serializer
profile_args = {"profile.results": args.no_results,
"profile.chop": args.chop,
"profile.serializer": serializer,
"profile.indexOps": args.indexOps}
res = self.client.gremlin_profile(query=cell, args=profile_args)
res.raise_for_status()
query_res = res.content.decode('utf-8')
if not args.silent:
gremlin_metadata = build_gremlin_metadata_from_query(query_type='profile', results=query_res, res=res)
titles.append('Profile')
if 'Neptune Gremlin Profile' in query_res:
first_tab_html = pre_container_template.render(content=query_res)
else:
first_tab_html = pre_container_template.render(content='No profile found')
else:
query_start = time.time() * 1000 # time.time() returns time in seconds w/high precision; x1000 to get in ms
query_res = self.client.gremlin_query(cell)
query_time = time.time() * 1000 - query_start
if not args.silent:
gremlin_metadata = build_gremlin_metadata_from_query(query_type='query', results=query_res,
query_time=query_time)
titles.append('Console')
try:
logger.debug(f'groupby: {args.group_by}')
logger.debug(f'display_property: {args.display_property}')
logger.debug(f'edge_display_property: {args.edge_display_property}')
logger.debug(f'label_max_length: {args.label_max_length}')
logger.debug(f'ignore_groups: {args.ignore_groups}')
gn = GremlinNetwork(group_by_property=args.group_by, display_property=args.display_property,
edge_display_property=args.edge_display_property,
label_max_length=args.label_max_length,
edge_label_max_length=args.edge_label_max_length,
ignore_groups=args.ignore_groups)
if args.path_pattern == '':
gn.add_results(query_res)
else:
pattern = parse_pattern_list_str(args.path_pattern)
gn.add_results_with_pattern(query_res, pattern)
logger.debug(f'number of nodes is {len(gn.graph.nodes)}')
if len(gn.graph.nodes) > 0:
self.graph_notebook_vis_options['physics']['disablePhysicsAfterInitialSimulation'] \
= args.stop_physics
self.graph_notebook_vis_options['physics']['simulationDuration'] = args.simulation_duration
f = Force(network=gn, options=self.graph_notebook_vis_options)
titles.append('Graph')
children.append(f)
logger.debug('added gremlin network to tabs')
except ValueError as value_error:
logger.debug(
f'unable to create gremlin network from result. Skipping from result set: {value_error}')
table_id = f"table-{str(uuid.uuid4()).replace('-', '')[:8]}"
first_tab_html = gremlin_table_template.render(guid=table_id, results=query_res)
if not args.silent:
metadata_output = widgets.Output(layout=DEFAULT_LAYOUT)
titles.append('Query Metadata')
children.append(metadata_output)
tab.children = children
for i in range(len(titles)):
tab.set_title(i, titles[i])
display(tab)
with metadata_output:
display(HTML(gremlin_metadata.to_html()))
with first_tab_output:
display(HTML(first_tab_html))
store_to_ns(args.store_to, query_res, local_ns)
@line_magic
@needs_local_scope
@display_exceptions
def gremlin_status(self, line='', local_ns: dict = None):
parser = argparse.ArgumentParser()
parser.add_argument('-q', '--queryId', default='',
help='The ID of a running Gremlin query. Only displays the status of the specified query.')
parser.add_argument('-c', '--cancelQuery', action='store_true',
help='Required for cancellation. Parameter has no corresponding value.')
parser.add_argument('-w', '--includeWaiting', action='store_true',
help='(Optional) Normally, only running queries are included in the response. '
'When the includeWaiting parameter is specified, '
'the status of all waiting queries is also returned.')
parser.add_argument('--store-to', type=str, default='', help='store query result to this variable')
args = parser.parse_args(line.split())
if not args.cancelQuery:
status_res = self.client.gremlin_status(args.queryId)
status_res.raise_for_status()
res = status_res.json()
else:
if args.queryId == '':
print(GREMLIN_CANCEL_HINT_MSG)
return
else:
cancel_res = self.client.gremlin_cancel(args.queryId)
cancel_res.raise_for_status()
res = cancel_res.json()
print(json.dumps(res, indent=2))
store_to_ns(args.store_to, res, local_ns)
@magic_variables
@cell_magic
@needs_local_scope
@display_exceptions
def oc(self, line='', cell='', local_ns: dict = None):
self.handle_opencypher_query(line, cell, local_ns)
@magic_variables
@cell_magic
@needs_local_scope
@display_exceptions
def opencypher(self, line='', cell='', local_ns: dict = None):
self.handle_opencypher_query(line, cell, local_ns)
@line_magic
@needs_local_scope
@display_exceptions
def oc_status(self, line='', local_ns: dict = None):
self.handle_opencypher_status(line, local_ns)
@line_magic
@needs_local_scope
@display_exceptions
def opencypher_status(self, line='', local_ns: dict = None):
self.handle_opencypher_status(line, local_ns)
@line_magic
@display_exceptions
def status(self, line):
logger.info(f'calling for status on endpoint {self.graph_notebook_config.host}')
status_res = self.client.status()
status_res.raise_for_status()
try:
res = status_res.json()
logger.info(f'got the json format response {res}')
return res
except ValueError:
logger.info(f'got the HTML format response {status_res.text}')
if "blazegraph™ by SYSTAP" in status_res.text:
print("For more information on the status of your Blazegraph cluster, please visit: ")
print()
print(f'http://{self.graph_notebook_config.host}:{self.graph_notebook_config.port}/blazegraph/#status')
print()
return status_res
@line_magic
@display_exceptions
def db_reset(self, line):
logger.info(f'calling system endpoint {self.client.host}')
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--generate-token', action='store_true', help='generate token for database reset')
parser.add_argument('-t', '--token', default='', help='perform database reset with given token')
parser.add_argument('-y', '--yes', action='store_true', help='skip the prompt and perform database reset')
args = parser.parse_args(line.split())
generate_token = args.generate_token
skip_prompt = args.yes
if generate_token is False and args.token == '':
if skip_prompt:
initiate_res = self.client.initiate_reset()
initiate_res.raise_for_status()
res = initiate_res.json()
token = res['payload']['token']
perform_reset_res = self.client.perform_reset(token)
perform_reset_res.raise_for_status()
logger.info(f'got the response {res}')
res = perform_reset_res.json()
return res
output = widgets.Output()
source = 'Are you sure you want to delete all the data in your cluster?'
label = widgets.Label(source)
text_hbox = widgets.HBox([label])
check_box = widgets.Checkbox(
value=False,
disabled=False,
indent=False,
description='I acknowledge that upon deletion the cluster data will no longer be available.',
layout=widgets.Layout(width='600px', margin='5px 5px 5px 5px')
)
button_delete = widgets.Button(description="Delete")
button_cancel = widgets.Button(description="Cancel")
button_hbox = widgets.HBox([button_delete, button_cancel])
display(text_hbox, check_box, button_hbox, output)
def on_button_delete_clicked(b):
initiate_res = self.client.initiate_reset()
initiate_res.raise_for_status()
result = initiate_res.json()
text_hbox.close()
check_box.close()
button_delete.close()
button_cancel.close()
button_hbox.close()
if not check_box.value:
with output:
print('Checkbox is not checked.')
return
token = result['payload']['token']
if token == "":
with output:
print('Failed to get token.')
print(result)
return
perform_reset_res = self.client.perform_reset(token)
perform_reset_res.raise_for_status()
result = perform_reset_res.json()
if 'status' not in result or result['status'] != '200 OK':
with output:
print('Database reset failed, please try the operation again or reboot the cluster.')
print(result)
logger.error(result)
return
retry = 10
poll_interval = 5
interval_output = widgets.Output()
job_status_output = widgets.Output()
status_hbox = widgets.HBox([interval_output])
vbox = widgets.VBox([status_hbox, job_status_output])
display(vbox)
last_poll_time = time.time()
while retry > 0:
time_elapsed = int(time.time() - last_poll_time)
time_remaining = poll_interval - time_elapsed
interval_output.clear_output()
if time_elapsed > poll_interval:
with interval_output:
print('checking status...')
job_status_output.clear_output()
with job_status_output:
display_html(HTML(loading_wheel_html))
try:
retry -= 1
status_res = self.client.status()
status_res.raise_for_status()
interval_check_response = status_res.json()
except Exception as e:
# Exception is expected when database is resetting, continue waiting
with job_status_output:
last_poll_time = time.time()
time.sleep(1)
continue
job_status_output.clear_output()
with job_status_output:
if interval_check_response["status"] == 'healthy':
interval_output.close()
print('Database has been reset.')
return
last_poll_time = time.time()
else:
with interval_output:
print(f'checking status in {time_remaining} seconds')
time.sleep(1)
with output:
print(result)
if interval_check_response["status"] != 'healthy':
print("Could not retrieve the status of the reset operation within the allotted time. "
"If the database is not healthy after 1 min, please try the operation again or "
"reboot the cluster.")
def on_button_cancel_clicked(b):
text_hbox.close()
check_box.close()
button_delete.close()
button_cancel.close()
button_hbox.close()
with output:
print('Database reset operation has been canceled.')
button_delete.on_click(on_button_delete_clicked)
button_cancel.on_click(on_button_cancel_clicked)
return
elif generate_token:
initiate_res = self.client.initiate_reset()
initiate_res.raise_for_status()
res = initiate_res.json()
else:
# args.token is an array of a single string, e.g., args.token=['ade-23-c23'], use index 0 to take the string
perform_res = self.client.perform_reset(args.token)
perform_res.raise_for_status()
res = perform_res.json()
logger.info(f'got the response {res}')
return res
@line_magic
@needs_local_scope
@display_exceptions
def load(self, line='', local_ns: dict = None):
# TODO: change widgets to let any arbitrary inputs be added by users
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', default='s3://')
parser.add_argument('-l', '--loader-arn', default=self.graph_notebook_config.load_from_s3_arn)
parser.add_argument('-f', '--format', choices=LOADER_FORMAT_CHOICES, default=FORMAT_CSV)
parser.add_argument('-p', '--parallelism', choices=PARALLELISM_OPTIONS, default=PARALLELISM_HIGH)
parser.add_argument('-r', '--region', default=self.graph_notebook_config.aws_region)
parser.add_argument('--fail-on-failure', action='store_true', default=False)
parser.add_argument('--update-single-cardinality', action='store_true', default=True)
parser.add_argument('--store-to', type=str, default='', help='store query result to this variable')
parser.add_argument('--run', action='store_true', default=False)
parser.add_argument('-m', '--mode', choices=LOAD_JOB_MODES, default=MODE_AUTO)
parser.add_argument('-q', '--queue-request', action='store_true', default=False)
parser.add_argument('-d', '--dependencies', action='append', default=[])
parser.add_argument('-e', '--no-edge-ids', action='store_true', default=False)
parser.add_argument('--named-graph-uri', type=str, default=DEFAULT_NAMEDGRAPH_URI,
help='The default graph for all RDF formats when no graph is specified. '
'Default is http://aws.amazon.com/neptune/vocab/v01/DefaultNamedGraph.')
parser.add_argument('--base-uri', type=str, default=DEFAULT_BASE_URI,
help='The base URI for RDF/XML and Turtle formats. '
'Default is http://aws.amazon.com/neptune/default')
parser.add_argument('--allow-empty-strings', action='store_true', default=False,
help='Load empty strings found in node and edge property values.')
parser.add_argument('-n', '--nopoll', action='store_true', default=False)
args = parser.parse_args(line.split())
region = self.graph_notebook_config.aws_region
button = widgets.Button(description="Submit")
output = widgets.Output()
widget_width = '25%'
label_width = '16%'
source = widgets.Text(
value=args.source,
placeholder='Type something',
disabled=False,
layout=widgets.Layout(width=widget_width)
)
arn = widgets.Text(
value=args.loader_arn,
placeholder='Type something',
disabled=False,
layout=widgets.Layout(width=widget_width)
)
source_format = widgets.Dropdown(
options=LOADER_FORMAT_CHOICES,
value=args.format,
disabled=False,
layout=widgets.Layout(width=widget_width)
)
ids_hbox_visibility = 'none'
gremlin_parser_options_hbox_visibility = 'none'
named_graph_hbox_visibility = 'none'
base_uri_hbox_visibility = 'none'
if source_format.value.lower() == FORMAT_CSV:
gremlin_parser_options_hbox_visibility = 'flex'
elif source_format.value.lower() == FORMAT_OPENCYPHER:
ids_hbox_visibility = 'flex'
elif source_format.value.lower() in RDF_LOAD_FORMATS:
named_graph_hbox_visibility = 'flex'
if source_format.value.lower() in BASE_URI_FORMATS:
base_uri_hbox_visibility = 'flex'
region_box = widgets.Text(
value=region,
placeholder=args.region,
disabled=False,
layout=widgets.Layout(width=widget_width)
)
fail_on_error = widgets.Dropdown(
options=['TRUE', 'FALSE'],
value=str(args.fail_on_failure).upper(),
disabled=False,
layout=widgets.Layout(width=widget_width)
)
parallelism = widgets.Dropdown(
options=PARALLELISM_OPTIONS,
value=args.parallelism,
disabled=False,
layout=widgets.Layout(width=widget_width)
)
allow_empty_strings = widgets.Dropdown(
options=['TRUE', 'FALSE'],
value=str(args.allow_empty_strings).upper(),
disabled=False,
layout=widgets.Layout(display=gremlin_parser_options_hbox_visibility,
width=widget_width)
)
named_graph_uri = widgets.Text(
value=args.named_graph_uri,
placeholder='http://named-graph-string',
disabled=False,
layout=widgets.Layout(display=named_graph_hbox_visibility,
width=widget_width)
)
base_uri = widgets.Text(
value=args.base_uri,
placeholder='http://base-uri-string',
disabled=False,
layout=widgets.Layout(display=base_uri_hbox_visibility,
width=widget_width)
)
update_single_cardinality = widgets.Dropdown(
options=['TRUE', 'FALSE'],
value=str(args.update_single_cardinality).upper(),
disabled=False,
layout=widgets.Layout(width=widget_width)
)
mode = widgets.Dropdown(
options=LOAD_JOB_MODES,
value=args.mode,
disabled=False,
layout=widgets.Layout(width=widget_width)
)
user_provided_edge_ids = widgets.Dropdown(
options=['TRUE', 'FALSE'],
value=str(not args.no_edge_ids).upper(),
disabled=False,
layout=widgets.Layout(display=ids_hbox_visibility,
width=widget_width)
)
queue_request = widgets.Dropdown(
options=['TRUE', 'FALSE'],
value=str(args.queue_request).upper(),
disabled=False,
layout=widgets.Layout(width=widget_width)
)
dependencies = widgets.Textarea(
value="\n".join(args.dependencies),
placeholder='load_A_id\nload_B_id',
disabled=False,
layout=widgets.Layout(width=widget_width)
)
poll_status = widgets.Dropdown(
options=['TRUE', 'FALSE'],
value=str(not args.nopoll).upper(),
disabled=False,
layout=widgets.Layout(width=widget_width)
)
# Create a series of HBox containers that will hold the widgets and labels
# that make up the %load form. Some of the labels and widgets are created
# in two parts to support the validation steps that come later. In the case
# of validation errors this allows additional text to easily be added to an
# HBox describing the issue.
source_hbox_label = widgets.Label('Source:',
layout=widgets.Layout(width=label_width,
display="flex",
justify_content="flex-end"))
source_hbox = widgets.HBox([source_hbox_label, source])
format_hbox_label = widgets.Label('Format:',
layout=widgets.Layout(width=label_width,
display="flex",
justify_content="flex-end"))
source_format_hbox = widgets.HBox([format_hbox_label, source_format])
region_hbox = widgets.HBox([widgets.Label('Region:',
layout=widgets.Layout(width=label_width,
display="flex",
justify_content="flex-end")),
region_box])
arn_hbox_label = widgets.Label('Load ARN:',
layout=widgets.Layout(width=label_width,
display="flex",
justify_content="flex-end"))
arn_hbox = widgets.HBox([arn_hbox_label, arn])
mode_hbox = widgets.HBox([widgets.Label('Mode:',
layout=widgets.Layout(width=label_width,
display="flex",
justify_content="flex-end")),
mode])
fail_hbox = widgets.HBox([widgets.Label('Fail on Error:',
layout=widgets.Layout(width=label_width,
display="flex",
justify_content="flex-end")),
fail_on_error])
parallelism_hbox = widgets.HBox([widgets.Label('Parallelism:',
layout=widgets.Layout(width=label_width,
display="flex",
justify_content="flex-end")),
parallelism])
allow_empty_strings_hbox_label = widgets.Label('Allow Empty Strings:',
layout=widgets.Layout(width=label_width,
display=gremlin_parser_options_hbox_visibility,
justify_content="flex-end"))
allow_empty_strings_hbox = widgets.HBox([allow_empty_strings_hbox_label, allow_empty_strings])
named_graph_uri_hbox_label = widgets.Label('Named Graph URI:',
layout=widgets.Layout(width=label_width,
display=named_graph_hbox_visibility,
justify_content="flex-end"))
named_graph_uri_hbox = widgets.HBox([named_graph_uri_hbox_label, named_graph_uri])
base_uri_hbox_label = widgets.Label('Base URI:',