/
utils.py
1780 lines (1560 loc) · 64.6 KB
/
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# 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.
#
import base64
import copy
import datetime
import glob
import hashlib
import inspect
import json
import logging
import numbers
import os
import pickle
import shutil
import socket
import subprocess
import sys
import threading
import time
import uuid
import zipfile
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path
from queue import Empty as EmptyQueue
from queue import Queue
from string import Template
import yaml
from google.protobuf.any_pb2 import Any
from graphscope.framework import utils
from graphscope.framework.errors import CompilationError
from graphscope.framework.graph_schema import GraphSchema
from graphscope.framework.utils import PipeWatcher
from graphscope.framework.utils import get_platform_info
from graphscope.framework.utils import get_tempdir
from graphscope.proto import attr_value_pb2
from graphscope.proto import data_types_pb2
from graphscope.proto import graph_def_pb2
from graphscope.proto import op_def_pb2
from graphscope.proto import types_pb2
logger = logging.getLogger("graphscope")
# runtime workspace
try:
WORKSPACE = os.environ["GRAPHSCOPE_RUNTIME"]
except KeyError:
WORKSPACE = os.path.join(get_tempdir(), "gs")
# COORDINATOR_HOME
# 1) get from gscoordinator python module, if failed,
# 2) infer from current directory
try:
import gscoordinator
COORDINATOR_HOME = os.path.abspath(os.path.join(gscoordinator.__file__, "..", ".."))
except ModuleNotFoundError:
COORDINATOR_HOME = os.path.abspath(os.path.join(__file__, "..", ".."))
# template directory for codegen
TEMPLATE_DIR = os.path.join(COORDINATOR_HOME, "gscoordinator", "template")
# builtin app resource
BUILTIN_APP_RESOURCE_PATH = os.path.join(
COORDINATOR_HOME, "gscoordinator", "builtin/app/builtin_app.gar"
)
# default config file in gar resource
DEFAULT_GS_CONFIG_FILE = ".gs_conf.yaml"
DEFAULT_GRAPHSCOPE_HOME = "/opt/graphscope"
# GRAPHSCOPE_HOME
# 1) get from environment variable `GRAPHSCOPE_HOME`, if not exist,
# 2) infer from COORDINATOR_HOME
GRAPHSCOPE_HOME = os.environ.get("GRAPHSCOPE_HOME", None)
# resolve from pip installed package
if GRAPHSCOPE_HOME is None:
if os.path.isdir(os.path.join(COORDINATOR_HOME, "graphscope.runtime")):
GRAPHSCOPE_HOME = os.path.join(COORDINATOR_HOME, "graphscope.runtime")
# find from DEFAULT_GRAPHSCOPE_HOME
if GRAPHSCOPE_HOME is None:
if os.path.isdir(DEFAULT_GRAPHSCOPE_HOME):
GRAPHSCOPE_HOME = DEFAULT_GRAPHSCOPE_HOME
# resolve from develop source tree
if GRAPHSCOPE_HOME is None:
GRAPHSCOPE_HOME = os.path.join(COORDINATOR_HOME, "..")
# ANALYTICAL_ENGINE_HOME
# 1) infer from GRAPHSCOPE_HOME
ANALYTICAL_ENGINE_HOME = os.path.join(GRAPHSCOPE_HOME)
ANALYTICAL_ENGINE_PATH = os.path.join(ANALYTICAL_ENGINE_HOME, "bin", "grape_engine")
if not os.path.isfile(ANALYTICAL_ENGINE_PATH):
# try get analytical engine from build dir
ANALYTICAL_ENGINE_HOME = os.path.join(GRAPHSCOPE_HOME, "analytical_engine")
ANALYTICAL_ENGINE_PATH = os.path.join(
ANALYTICAL_ENGINE_HOME, "build", "grape_engine"
)
# INTERACTIVE_ENGINE_SCRIPT
INTERAVTIVE_INSTANCE_TIMEOUT_SECONDS = 600 # 10 mins
INTERACTIVE_ENGINE_SCRIPT = os.path.join(GRAPHSCOPE_HOME, "bin", "giectl")
if not os.path.isfile(INTERACTIVE_ENGINE_SCRIPT):
INTERACTIVE_ENGINE_SCRIPT = os.path.join(
GRAPHSCOPE_HOME, "interactive_engine", "bin", "giectl"
)
# JAVA SDK related CONSTANTS
LLVM4JNI_HOME = os.environ.get("LLVM4JNI_HOME", None)
LLVM4JNI_USER_OUT_DIR_BASE = "user-llvm4jni-output"
PROCESSOR_MAIN_CLASS = "com.alibaba.graphscope.annotation.Main"
JAVA_CODEGNE_OUTPUT_PREFIX = "gs-ffi"
GRAPE_PROCESSOR_JAR = os.path.join(
GRAPHSCOPE_HOME, "lib", "grape-runtime-0.1-shaded.jar"
)
def get_timestamp():
now = datetime.datetime.now()
return datetime.datetime.timestamp(now)
def get_lib_path(app_dir, app_name):
lib_path = ""
if sys.platform == "linux" or sys.platform == "linux2":
lib_path = os.path.join(app_dir, "lib%s.so" % app_name)
elif sys.platform == "darwin":
lib_path = os.path.join(app_dir, "lib%s.dylib" % app_name)
else:
raise RuntimeError(f"Unsupported platform {sys.platform}")
return lib_path
def get_app_sha256(attr):
(
app_type,
app_header,
app_class,
vd_type,
md_type,
pregel_combine,
java_jar_path,
java_app_class,
) = _codegen_app_info(attr, DEFAULT_GS_CONFIG_FILE)
graph_header, graph_type, _ = _codegen_graph_info(attr)
logger.info("Codegened graph type: %s, Graph header: %s", graph_type, graph_header)
app_sha256 = ""
if app_type == "cpp_pie":
app_sha256 = hashlib.sha256(
f"{app_type}.{app_class}.{graph_type}".encode("utf-8")
).hexdigest()
elif app_type == "java_pie":
s = hashlib.sha256()
# CAUTION!!!!!
# We believe jar_path.java_app_class can uniquely define one java app
s.update(f"{app_type}.{java_jar_path}.{java_app_class}".encode("utf-8"))
if types_pb2.GAR in attr:
s.update(attr[types_pb2.GAR].s)
app_sha256 = s.hexdigest()
else:
s = hashlib.sha256()
s.update(f"{app_type}.{app_class}.{graph_type}".encode("utf-8"))
if types_pb2.GAR in attr:
s.update(attr[types_pb2.GAR].s)
app_sha256 = s.hexdigest()
return app_sha256
def get_graph_sha256(attr):
_, graph_class, _ = _codegen_graph_info(attr)
return hashlib.sha256(graph_class.encode("utf-8")).hexdigest()
def compile_app(workspace: str, library_name, attr, engine_config: dict):
"""Compile an application.
Args:
workspace (str): working dir.
library_name (str): name of library
attr (`AttrValue`): All information needed to compile an app.
engine_config (dict): for options of NETWORKX
Returns:
str: Path of the built library.
str: Java jar path. For c++/python app, return None.
str: Directory containing generated java and jni code. For c++/python app, return None.
str: App type.
"""
app_dir = os.path.join(workspace, library_name)
os.makedirs(app_dir, exist_ok=True)
_extract_gar(app_dir, attr)
# codegen app and graph info
# vd_type and md_type is None in cpp_pie
(
app_type,
app_header,
app_class,
vd_type,
md_type,
pregel_combine,
java_jar_path,
java_app_class,
) = _codegen_app_info(attr, DEFAULT_GS_CONFIG_FILE)
logger.info(
"Codegened application type: %s, app header: %s, app_class: %s, vd_type: %s, md_type: %s, pregel_combine: %s, \
java_jar_path: %s, java_app_class: %s",
app_type,
app_header,
app_class,
str(vd_type),
str(md_type),
str(pregel_combine),
str(java_jar_path),
str(java_app_class),
)
graph_header, graph_type, graph_oid_type = _codegen_graph_info(attr)
logger.info("Codegened graph type: %s, Graph header: %s", graph_type, graph_header)
os.chdir(app_dir)
module_name = ""
# Output directory for java codegen
java_codegen_out_dir = ""
# set OPAL_PREFIX in CMAKE_PREFIX_PATH
OPAL_PREFIX = os.environ.get("OPAL_PREFIX", "")
cmake_commands = [
shutil.which("cmake"),
".",
f"-DNETWORKX={engine_config['networkx']}",
f"-DCMAKE_PREFIX_PATH='{GRAPHSCOPE_HOME};{OPAL_PREFIX}'",
]
if app_type == "java_pie":
if not os.path.isfile(GRAPE_PROCESSOR_JAR):
raise RuntimeError("Grape runtime jar not found")
# for java need to run preprocess
java_codegen_out_dir = os.path.join(
workspace, "{}-{}".format(JAVA_CODEGNE_OUTPUT_PREFIX, library_name)
)
cmake_commands += [
"-DENABLE_JAVA_SDK=ON",
"-DJAVA_PIE_APP=ON",
"-DPRE_CP={}:{}".format(GRAPE_PROCESSOR_JAR, java_jar_path),
"-DPROCESSOR_MAIN_CLASS={}".format(PROCESSOR_MAIN_CLASS),
"-DJAR_PATH={}".format(java_jar_path),
"-DOUTPUT_DIR={}".format(java_codegen_out_dir),
]
# if run llvm4jni.sh not found, we just go ahead,since it is optional.
if LLVM4JNI_HOME and os.path.isfile(os.path.join(LLVM4JNI_HOME, "run.sh")):
llvm4jni_user_out_dir = os.path.join(
workspace, "{}-{}".format(LLVM4JNI_USER_OUT_DIR_BASE, library_name)
)
cmake_commands += [
"-DRUN_LLVM4JNI_SH={}".format(os.path.join(LLVM4JNI_HOME, "run.sh")),
"-DLLVM4JNI_OUTPUT={}".format(llvm4jni_user_out_dir),
"-DLIB_PATH={}".format(get_lib_path(app_dir, library_name)),
]
else:
logger.info(
"Skip running llvm4jni since env var LLVM4JNI_HOME not found or run.sh not found under LLVM4JNI_HOME"
)
logger.info(" ".join(cmake_commands))
elif app_type != "cpp_pie":
if app_type == "cython_pregel":
pxd_name = "pregel"
cmake_commands += ["-DCYTHON_PREGEL_APP=True"]
if pregel_combine:
cmake_commands += ["-DENABLE_PREGEL_COMBINE=True"]
else:
pxd_name = "pie"
cmake_commands += ["-DCYTHON_PIE_APP=True"]
# Copy pxd file and generate cc file from pyx
shutil.copyfile(
os.path.join(TEMPLATE_DIR, f"{pxd_name}.pxd.template"),
os.path.join(app_dir, f"{pxd_name}.pxd"),
)
# Assume the gar will have and only have one .pyx file
for pyx_file in glob.glob(app_dir + "/*.pyx"):
module_name = os.path.splitext(os.path.basename(pyx_file))[0]
cc_file = os.path.join(app_dir, module_name + ".cc")
subprocess.check_call(
[shutil.which("cython"), "-3", "--cplus", "-o", cc_file, pyx_file]
)
app_header = f"{module_name}.h"
# replace and generate cmakelist
cmakelists_file_tmp = os.path.join(TEMPLATE_DIR, "CMakeLists.template")
cmakelists_file = os.path.join(app_dir, "CMakeLists.txt")
with open(cmakelists_file_tmp, mode="r") as template:
content = template.read()
content = Template(content).safe_substitute(
_analytical_engine_home=ANALYTICAL_ENGINE_HOME,
_frame_name=library_name,
_oid_type=graph_oid_type,
_vd_type=vd_type,
_md_type=md_type,
_graph_type=graph_type,
_graph_header=graph_header,
_module_name=module_name,
_app_type=app_class,
_app_header=app_header,
)
with open(cmakelists_file, mode="w") as f:
f.write(content)
# compile
logger.info("Building app ...")
cmake_process = subprocess.Popen(
cmake_commands,
env=os.environ.copy(),
encoding="utf-8",
errors="replace",
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
)
cmake_stderr_watcher = PipeWatcher(cmake_process.stderr, sys.stderr)
setattr(cmake_process, "stderr_watcher", cmake_stderr_watcher)
cmake_process.wait()
make_process = subprocess.Popen(
[shutil.which("make"), "-j4"],
env=os.environ.copy(),
encoding="utf-8",
errors="replace",
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
)
make_stderr_watcher = PipeWatcher(make_process.stderr, sys.stderr)
setattr(make_process, "stderr_watcher", make_stderr_watcher)
make_process.wait()
lib_path = get_lib_path(app_dir, library_name)
if not os.path.isfile(lib_path):
raise CompilationError(
f"Failed to compile app {app_class} on platform {get_platform_info()}"
)
return lib_path, java_jar_path, java_codegen_out_dir, app_type
def compile_graph_frame(workspace: str, library_name, attr: dict, engine_config: dict):
"""Compile an application.
Args:
workspace (str): Working dir.
library_name (str): name of library
attr (`AttrValue`): All information needed to compile a graph library.
engine_config (dict): for options of NETWORKX
Raises:
ValueError: When graph_type is not supported.
Returns:
str: Path of the built graph library.
None: For consistency with compiler_app.
None: For consistency with compile_app.
None: for consistency with compile_app.
"""
_, graph_class, _ = _codegen_graph_info(attr)
logger.info("Codegened graph frame type: %s", graph_class)
library_dir = os.path.join(workspace, library_name)
os.makedirs(library_dir, exist_ok=True)
os.chdir(library_dir)
graph_type = attr[types_pb2.GRAPH_TYPE].graph_type
# set OPAL_PREFIX in CMAKE_PREFIX_PATH
OPAL_PREFIX = os.environ.get("OPAL_PREFIX", "")
cmake_commands = [
shutil.which("cmake"),
".",
f"-DNETWORKX={engine_config['networkx']}",
f"-DCMAKE_PREFIX_PATH='{GRAPHSCOPE_HOME};{OPAL_PREFIX}'",
]
if graph_type == graph_def_pb2.ARROW_PROPERTY:
cmake_commands += ["-DPROPERTY_GRAPH_FRAME=True"]
elif graph_type in (
graph_def_pb2.ARROW_PROJECTED,
graph_def_pb2.DYNAMIC_PROJECTED,
graph_def_pb2.ARROW_FLATTENED,
):
cmake_commands += ["-DPROJECT_FRAME=True"]
else:
raise ValueError(f"Illegal graph type: {graph_type}")
# replace and generate cmakelist
cmakelists_file_tmp = os.path.join(TEMPLATE_DIR, "CMakeLists.template")
cmakelists_file = os.path.join(library_dir, "CMakeLists.txt")
with open(cmakelists_file_tmp, mode="r") as template:
content = template.read()
content = Template(content).safe_substitute(
_analytical_engine_home=ANALYTICAL_ENGINE_HOME,
_frame_name=library_name,
_graph_type=graph_class,
)
with open(cmakelists_file, mode="w") as f:
f.write(content)
# compile
logger.info("Building graph library ...")
cmake_process = subprocess.Popen(
cmake_commands,
env=os.environ.copy(),
encoding="utf-8",
errors="replace",
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
)
cmake_stderr_watcher = PipeWatcher(cmake_process.stderr, sys.stderr)
setattr(cmake_process, "stderr_watcher", cmake_stderr_watcher)
cmake_process.wait()
make_process = subprocess.Popen(
[shutil.which("make"), "-j4"],
env=os.environ.copy(),
encoding="utf-8",
errors="replace",
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
universal_newlines=True,
bufsize=1,
)
make_stderr_watcher = PipeWatcher(make_process.stderr, sys.stderr)
setattr(make_process, "stderr_watcher", make_stderr_watcher)
make_process.wait()
lib_path = get_lib_path(library_dir, library_name)
if not os.path.isfile(lib_path):
raise CompilationError(
f"Failed to compile graph {graph_class} on platform {get_platform_info()}"
)
return lib_path, None, None, None
def op_pre_process(op, op_result_pool, key_to_op, **kwargs): # noqa: C901
if op.op == types_pb2.REPORT_GRAPH:
return
if op.op == types_pb2.CREATE_GRAPH:
_pre_process_for_create_graph_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.ADD_LABELS:
_pre_process_for_add_labels_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.RUN_APP:
_pre_process_for_run_app_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.BIND_APP:
_pre_process_for_bind_app_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.PROJECT_GRAPH:
_pre_process_for_project_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.PROJECT_TO_SIMPLE:
_pre_process_for_project_to_simple_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.ADD_COLUMN:
_pre_process_for_add_column_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.UNLOAD_GRAPH:
_pre_process_for_unload_graph_op(op, op_result_pool, key_to_op, **kwargs)
if op.op in (
types_pb2.CONTEXT_TO_NUMPY,
types_pb2.CONTEXT_TO_DATAFRAME,
types_pb2.TO_VINEYARD_TENSOR,
types_pb2.TO_VINEYARD_DATAFRAME,
):
_pre_process_for_context_op(op, op_result_pool, key_to_op, **kwargs)
if op.op in (types_pb2.GRAPH_TO_NUMPY, types_pb2.GRAPH_TO_DATAFRAME):
_pre_process_for_output_graph_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.UNLOAD_APP:
_pre_process_for_unload_app_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.UNLOAD_CONTEXT:
_pre_process_for_unload_context_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.CREATE_INTERACTIVE_QUERY:
_pre_process_for_create_interactive_query_op(
op, op_result_pool, key_to_op, **kwargs
)
if op.op == types_pb2.GREMLIN_QUERY:
_pre_process_for_gremlin_query_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.FETCH_GREMLIN_RESULT:
_pre_process_for_fetch_gremlin_result(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.CLOSE_INTERACTIVE_QUERY:
_pre_process_for_close_interactive_query_op(
op, op_result_pool, key_to_op, **kwargs
)
if op.op == types_pb2.SUBGRAPH:
_pre_process_for_gremlin_to_subgraph_op(op, op_result_pool, key_to_op, **kwargs)
if op.op == types_pb2.CREATE_LEARNING_INSTANCE:
_pre_process_for_create_learning_graph_op(
op, op_result_pool, key_to_op, **kwargs
)
if op.op == types_pb2.CLOSE_LEARNING_INSTANCE:
_pre_process_for_close_learning_instance_op(
op, op_result_pool, key_to_op, **kwargs
)
if op.op == types_pb2.OUTPUT:
_pre_process_for_output_op(op, op_result_pool, key_to_op, **kwargs)
if op.op in (types_pb2.TO_DIRECTED, types_pb2.TO_UNDIRECTED):
_pre_process_for_transform_op(op, op_result_pool, key_to_op, **kwargs)
def _pre_process_for_create_graph_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) <= 1
if len(op.parents) == 1:
key_of_parent_op = op.parents[0]
parent_op = key_to_op[key_of_parent_op]
if parent_op.op == types_pb2.DATA_SOURCE:
op.large_attr.CopyFrom(parent_op.large_attr)
def _pre_process_for_add_labels_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 2
for key_of_parent_op in op.parents:
parent_op = key_to_op[key_of_parent_op]
if parent_op.op == types_pb2.DATA_SOURCE:
op.large_attr.CopyFrom(parent_op.large_attr)
else:
result = op_result_pool[key_of_parent_op]
op.attr[types_pb2.GRAPH_NAME].CopyFrom(
utils.s_to_attr(result.graph_def.key)
)
def _pre_process_for_transform_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
result = op_result_pool[op.parents[0]]
# To compatible with eager evaluation cases where it will has the key.
if types_pb2.GRAPH_NAME not in op.attr:
op.attr[types_pb2.GRAPH_NAME].CopyFrom(utils.s_to_attr(result.graph_def.key))
def _pre_process_for_close_interactive_query_op(
op, op_result_pool, key_to_op, **kwargs
):
assert len(op.parents) == 1
assert op.parents[0] in op_result_pool
def _pre_process_for_gremlin_to_subgraph_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
assert op.parents[0] in op_result_pool
def _pre_process_for_gremlin_query_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
assert op.parents[0] in op_result_pool
def _pre_process_for_fetch_gremlin_result(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
assert op.parents[0] in op_result_pool
def _pre_process_for_create_interactive_query_op(
op, op_result_pool, key_to_op, **kwargs
):
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
result = op_result_pool[key_of_parent_op]
assert result.graph_def.extension.Is(graph_def_pb2.VineyardInfoPb.DESCRIPTOR)
vy_info = graph_def_pb2.VineyardInfoPb()
result.graph_def.extension.Unpack(vy_info)
op.attr[types_pb2.VINEYARD_ID].CopyFrom(utils.i_to_attr(vy_info.vineyard_id))
op.attr[types_pb2.SCHEMA_PATH].CopyFrom(utils.s_to_attr(vy_info.schema_path))
def _pre_process_for_close_learning_instance_op(
op, op_result_pool, key_to_op, **kwargs
):
assert len(op.parents) == 1
assert op.parents[0] in op_result_pool
def _pre_process_for_create_learning_graph_op(op, op_result_pool, key_to_op, **kwargs):
from graphscope.learning.graph import Graph as LearningGraph
nodes = pickle.loads(op.attr[types_pb2.NODES].s)
edges = pickle.loads(op.attr[types_pb2.EDGES].s)
gen_labels = pickle.loads(op.attr[types_pb2.GLE_GEN_LABELS].s)
# get graph schema
key_of_parent_op = op.parents[0]
result = op_result_pool[key_of_parent_op]
assert result.graph_def.extension.Is(graph_def_pb2.VineyardInfoPb.DESCRIPTOR)
schema = GraphSchema()
schema.from_graph_def(result.graph_def)
# get graph vineyard id
vy_info = graph_def_pb2.VineyardInfoPb()
result.graph_def.extension.Unpack(vy_info)
vineyard_id = vy_info.vineyard_id
# gle handle
engine_hosts = kwargs.pop("engine_hosts")
engine_config = kwargs.pop("engine_config")
handle = get_gl_handle(schema, vineyard_id, engine_hosts, engine_config)
config = LearningGraph.preprocess_args(handle, nodes, edges, gen_labels)
config = base64.b64encode(json.dumps(config).encode("utf-8")).decode("utf-8")
op.attr[types_pb2.VINEYARD_ID].CopyFrom(utils.i_to_attr(vineyard_id))
op.attr[types_pb2.GLE_HANDLE].CopyFrom(utils.s_to_attr(handle))
op.attr[types_pb2.GLE_CONFIG].CopyFrom(utils.s_to_attr(config))
# get `bind_app` runtime informarion in lazy mode
def _pre_process_for_bind_app_op(op, op_result_pool, key_to_op, **kwargs):
for key_of_parent_op in op.parents:
parent_op = key_to_op[key_of_parent_op]
if parent_op.op == types_pb2.CREATE_APP:
# app assets
op.attr[types_pb2.APP_ALGO].CopyFrom(parent_op.attr[types_pb2.APP_ALGO])
if types_pb2.GAR in parent_op.attr:
op.attr[types_pb2.GAR].CopyFrom(parent_op.attr[types_pb2.GAR])
else:
# get graph runtime information from results
result = op_result_pool[key_of_parent_op]
assert result.graph_def.extension.Is(
graph_def_pb2.VineyardInfoPb.DESCRIPTOR
)
vy_info = graph_def_pb2.VineyardInfoPb()
result.graph_def.extension.Unpack(vy_info)
op.attr[types_pb2.GRAPH_NAME].CopyFrom(
attr_value_pb2.AttrValue(s=result.graph_def.key.encode("utf-8"))
)
op.attr[types_pb2.GRAPH_TYPE].CopyFrom(
attr_value_pb2.AttrValue(graph_type=result.graph_def.graph_type)
)
op.attr[types_pb2.OID_TYPE].CopyFrom(
utils.s_to_attr(
utils.normalize_data_type_str(
utils.data_type_to_cpp(vy_info.oid_type)
)
)
)
op.attr[types_pb2.VID_TYPE].CopyFrom(
utils.s_to_attr(utils.data_type_to_cpp(vy_info.vid_type))
)
op.attr[types_pb2.V_DATA_TYPE].CopyFrom(
utils.s_to_attr(utils.data_type_to_cpp(vy_info.vdata_type))
)
op.attr[types_pb2.E_DATA_TYPE].CopyFrom(
utils.s_to_attr(utils.data_type_to_cpp(vy_info.edata_type))
)
# get `run_app` runtime informarion in lazy mode
def _pre_process_for_run_app_op(op, op_result_pool, key_to_op, **kwargs):
# run_app op has only one parent
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
parent_op = key_to_op[key_of_parent_op]
assert parent_op.op == types_pb2.BIND_APP
# set graph key
op.attr[types_pb2.GRAPH_NAME].CopyFrom(parent_op.attr[types_pb2.GRAPH_NAME])
result = op_result_pool[key_of_parent_op]
# set app key
op.attr[types_pb2.APP_NAME].CopyFrom(
attr_value_pb2.AttrValue(s=result.result.decode("utf-8").encode("utf-8"))
)
app_type = parent_op.attr[types_pb2.APP_ALGO].s.decode("utf-8")
if app_type == "java_app":
# For java app, we need lib path as an explicit arg.
param = Any()
lib_path = parent_op.attr[types_pb2.APP_LIBRARY_PATH].s.decode("utf-8")
param.Pack(data_types_pb2.StringValue(value=lib_path))
op.query_args.args.extend([param])
logger.info("Lib path {}".format(lib_path))
def _pre_process_for_unload_graph_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
result = op_result_pool[key_of_parent_op]
assert result.graph_def.extension.Is(graph_def_pb2.VineyardInfoPb.DESCRIPTOR)
vy_info = graph_def_pb2.VineyardInfoPb()
result.graph_def.extension.Unpack(vy_info)
op.attr[types_pb2.GRAPH_NAME].CopyFrom(utils.s_to_attr(result.graph_def.key))
op.attr[types_pb2.VINEYARD_ID].CopyFrom(utils.i_to_attr(vy_info.vineyard_id))
def _pre_process_for_unload_app_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
result = op_result_pool[key_of_parent_op]
op.attr[types_pb2.APP_NAME].CopyFrom(utils.s_to_attr(result.result.decode("utf-8")))
def _pre_process_for_unload_context_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
result = op_result_pool[key_of_parent_op]
parent_op_result = json.loads(result.result.decode("utf-8"))
context_key = parent_op_result["context_key"]
op.attr[types_pb2.CONTEXT_KEY].CopyFrom(
attr_value_pb2.AttrValue(s=context_key.encode("utf-8"))
)
def _pre_process_for_add_column_op(op, op_result_pool, key_to_op, **kwargs):
for key_of_parent_op in op.parents:
parent_op = key_to_op[key_of_parent_op]
if parent_op.op != types_pb2.RUN_APP:
# get graph information
r = op_result_pool[key_of_parent_op]
graph_name = r.graph_def.key
graph_type = r.graph_def.graph_type
schema = GraphSchema()
schema.from_graph_def(r.graph_def)
for key_of_parent_op in op.parents:
parent_op = key_to_op[key_of_parent_op]
if parent_op.op == types_pb2.RUN_APP:
selector = op.attr[types_pb2.SELECTOR].s.decode("utf-8")
r = op_result_pool[key_of_parent_op]
parent_op_result = json.loads(r.result.decode("utf-8"))
context_key = parent_op_result["context_key"]
context_type = parent_op_result["context_type"]
selector = _tranform_dataframe_selector(context_type, schema, selector)
op.attr[types_pb2.GRAPH_NAME].CopyFrom(utils.s_to_attr(graph_name))
op.attr[types_pb2.GRAPH_TYPE].CopyFrom(utils.graph_type_to_attr(graph_type))
op.attr[types_pb2.CONTEXT_KEY].CopyFrom(utils.s_to_attr(context_key))
op.attr[types_pb2.SELECTOR].CopyFrom(utils.s_to_attr(selector))
def _pre_process_for_context_op(op, op_result_pool, key_to_op, **kwargs):
def __backtrack_key_of_graph_op(key):
bfs_queue = Queue()
bfs_queue.put(key)
while not bfs_queue.empty():
next_op_key = bfs_queue.get()
if next_op_key in key_to_op:
next_op = key_to_op[next_op_key]
if next_op.op in (
types_pb2.CREATE_GRAPH,
types_pb2.ADD_COLUMN,
types_pb2.ADD_LABELS,
types_pb2.TRANSFORM_GRAPH,
types_pb2.PROJECT_GRAPH,
types_pb2.PROJECT_TO_SIMPLE,
types_pb2.TO_DIRECTED,
types_pb2.TO_UNDIRECTED,
):
return next_op
for parent_key in next_op.parents:
bfs_queue.put(parent_key)
return None
assert len(op.parents) == 1
schema = None
key_of_parent_op = op.parents[0]
graph_op = __backtrack_key_of_graph_op(key_of_parent_op)
r = op_result_pool[key_of_parent_op]
# set context key
parent_op_result = json.loads(r.result.decode("utf-8"))
context_key = parent_op_result["context_key"]
context_type = parent_op_result["context_type"]
op.attr[types_pb2.CONTEXT_KEY].CopyFrom(
attr_value_pb2.AttrValue(s=context_key.encode("utf-8"))
)
r = op_result_pool[graph_op.key]
# transform selector
schema = GraphSchema()
schema.from_graph_def(r.graph_def)
selector = op.attr[types_pb2.SELECTOR].s.decode("utf-8")
if op.op in (types_pb2.CONTEXT_TO_DATAFRAME, types_pb2.TO_VINEYARD_DATAFRAME):
selector = _tranform_dataframe_selector(context_type, schema, selector)
else:
# to numpy
selector = _tranform_numpy_selector(context_type, schema, selector)
if selector is not None:
op.attr[types_pb2.SELECTOR].CopyFrom(
attr_value_pb2.AttrValue(s=selector.encode("utf-8"))
)
def _pre_process_for_output_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
parent_op = key_to_op[key_of_parent_op]
result = op_result_pool[key_of_parent_op]
if parent_op.output_type in (
types_pb2.VINEYARD_TENSOR,
types_pb2.VINEYARD_DATAFRAME,
):
# dependent to to_vineyard_dataframe
r = json.loads(result.result.decode("utf-8"))["object_id"]
op.attr[types_pb2.VINEYARD_ID].CopyFrom(utils.s_to_attr(r))
def _pre_process_for_output_graph_op(op, op_result_pool, key_to_op, **kwargs):
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
r = op_result_pool[key_of_parent_op]
schema = GraphSchema()
schema.from_graph_def(r.graph_def)
graph_name = r.graph_def.key
selector = op.attr[types_pb2.SELECTOR].s.decode("utf-8")
if op.op == types_pb2.GRAPH_TO_DATAFRAME:
selector = _tranform_dataframe_selector(
"labeled_vertex_property", schema, selector
)
else:
# to numpy
selector = _tranform_numpy_selector("labeled_vertex_property", schema, selector)
if selector is not None:
op.attr[types_pb2.SELECTOR].CopyFrom(
attr_value_pb2.AttrValue(s=selector.encode("utf-8"))
)
op.attr[types_pb2.GRAPH_NAME].CopyFrom(
attr_value_pb2.AttrValue(s=graph_name.encode("utf-8"))
)
def _pre_process_for_project_to_simple_op( # noqa: C901
op, op_result_pool, key_to_op, **kwargs
):
# for nx graph
if op.attr[types_pb2.GRAPH_TYPE].graph_type in (
graph_def_pb2.DYNAMIC_PROJECTED,
graph_def_pb2.ARROW_FLATTENED,
):
return
def _check_v_prop_exists_in_all_v_labels(schema, prop):
exists = True
for v_label in schema.vertex_labels:
exists = exists and schema.vertex_property_exists(v_label, prop)
return exists
def _check_e_prop_exists_in_all_e_labels(schema, prop):
exists = True
for e_label in schema.edge_labels:
exists = exists and schema.edge_property_exists(e_label, prop)
return exists
# get parent graph schema
assert len(op.parents) == 1
key_of_parent_op = op.parents[0]
r = op_result_pool[key_of_parent_op]
schema = GraphSchema()
schema.from_graph_def(r.graph_def)
graph_name = r.graph_def.key
if schema.vertex_label_num == 0:
raise RuntimeError(
"Failed to project to simple graph as no vertex exists in this graph."
)
if schema.edge_label_num == 0:
raise RuntimeError(
"Failed to project to simple graph as no edge exists in this graph."
)
need_flatten_graph = False
if schema.vertex_label_num > 1 or schema.edge_label_num > 1:
need_flatten_graph = True
# check and get vertex property
v_prop = op.attr[types_pb2.V_PROP_KEY].s.decode("utf-8")
if v_prop == "None":
v_prop_id = -1
v_prop_type = graph_def_pb2.NULLVALUE
if not need_flatten_graph:
# for projected graph
# if there is only one property on the label, uses this property
v_label = schema.vertex_labels[0]
if schema.vertex_properties_num(v_label) == 1:
v_prop = schema.get_vertex_properties(v_label)[0]
v_prop_id = v_prop.id
v_prop_type = v_prop.type
else:
# v_prop should exists in all labels
if not _check_v_prop_exists_in_all_v_labels(schema, v_prop):
raise RuntimeError(
"Property {0} doesn't exists in all vertex labels".format(v_prop)
)
# get vertex property id
v_prop_id = schema.get_vertex_property_id(schema.vertex_labels[0], v_prop)
# get vertex property type
v_prop_type = graph_def_pb2.NULLVALUE
v_props = schema.get_vertex_properties(schema.vertex_labels[0])
for v_prop in v_props:
if v_prop.id == v_prop_id:
v_prop_type = v_prop.type
break
# check and get edge property
e_prop = op.attr[types_pb2.E_PROP_KEY].s.decode("utf-8")
if e_prop == "None":
e_prop_id = -1
e_prop_type = graph_def_pb2.NULLVALUE
if not need_flatten_graph:
# for projected graph
# if there is only one property on the label, uses this property
e_label = schema.edge_labels[0]
if schema.edge_properties_num(e_label) == 1:
e_prop = schema.get_edge_properties(e_label)[0]
e_prop_id = e_prop.id
e_prop_type = e_prop.type
else:
# e_prop should exists in all labels
if not _check_e_prop_exists_in_all_e_labels(schema, e_prop):
raise RuntimeError(
"Property {0} doesn't exists in all edge labels".format(e_prop)
)
# get edge property id
e_prop_id = schema.get_edge_property_id(schema.edge_labels[0], e_prop)
# get edge property type
e_props = schema.get_edge_properties(schema.edge_labels[0])
e_prop_type = graph_def_pb2.NULLVALUE
for e_prop in e_props:
if e_prop.id == e_prop_id:
e_prop_type = e_prop.type
break
op.attr[types_pb2.GRAPH_NAME].CopyFrom(
attr_value_pb2.AttrValue(s=graph_name.encode("utf-8"))
)
op.attr[types_pb2.OID_TYPE].CopyFrom(
utils.s_to_attr(utils.data_type_to_cpp(schema.oid_type))
)
op.attr[types_pb2.VID_TYPE].CopyFrom(
utils.s_to_attr(utils.data_type_to_cpp(schema.vid_type))
)
op.attr[types_pb2.V_DATA_TYPE].CopyFrom(
utils.s_to_attr(utils.data_type_to_cpp(v_prop_type))
)
op.attr[types_pb2.E_DATA_TYPE].CopyFrom(
utils.s_to_attr(utils.data_type_to_cpp(e_prop_type))
)
if need_flatten_graph:
op.attr[types_pb2.GRAPH_TYPE].CopyFrom(
utils.graph_type_to_attr(graph_def_pb2.ARROW_FLATTENED)
)
op.attr[types_pb2.V_PROP_KEY].CopyFrom(utils.s_to_attr(str(v_prop_id)))
op.attr[types_pb2.E_PROP_KEY].CopyFrom(utils.s_to_attr(str(e_prop_id)))
else:
v_label = schema.vertex_labels[0]
e_label = schema.edge_labels[0]
relation = (v_label, v_label)
check_argument(
relation in schema.get_relationships(e_label),
f"Cannot project to simple, Graph doesn't contain such relationship: {v_label} -> {e_label} <- {v_label}.",
)
v_label_id = schema.get_vertex_label_id(v_label)
e_label_id = schema.get_edge_label_id(e_label)
op.attr[types_pb2.GRAPH_TYPE].CopyFrom(
utils.graph_type_to_attr(graph_def_pb2.ARROW_PROJECTED)
)
op.attr[types_pb2.V_LABEL_ID].CopyFrom(utils.i_to_attr(v_label_id))
op.attr[types_pb2.V_PROP_ID].CopyFrom(utils.i_to_attr(v_prop_id))
op.attr[types_pb2.E_LABEL_ID].CopyFrom(utils.i_to_attr(e_label_id))
op.attr[types_pb2.E_PROP_ID].CopyFrom(utils.i_to_attr(e_prop_id))
def _pre_process_for_project_op(op, op_result_pool, key_to_op, **kwargs):
def _get_all_v_props_id(schema, label):
props = schema.get_vertex_properties(label)
return [schema.get_vertex_property_id(label, prop.name) for prop in props]
def _get_all_e_props_id(schema, label):
props = schema.get_edge_properties(label)
return [schema.get_edge_property_id(label, prop.name) for prop in props]
assert len(op.parents) == 1
# get parent graph schema
key_of_parent_op = op.parents[0]
r = op_result_pool[key_of_parent_op]
schema = GraphSchema()
schema.from_graph_def(r.graph_def)
graph_name = r.graph_def.key
vertices = json.loads(op.attr[types_pb2.VERTEX_COLLECTIONS].s.decode("utf-8"))
edges = json.loads(op.attr[types_pb2.EDGE_COLLECTIONS].s.decode("utf-8"))
vertex_collections = {}
edge_collections = {}
for label, props in vertices.items():
label_id = schema.get_vertex_label_id(label)
if props is None:
vertex_collections[label_id] = _get_all_v_props_id(schema, label)
else:
vertex_collections[label_id] = sorted(
[schema.get_vertex_property_id(label, prop) for prop in props]
)