-
Notifications
You must be signed in to change notification settings - Fork 328
/
NeoExecutionInfoLocation.java
1652 lines (1511 loc) · 57.4 KB
/
NeoExecutionInfoLocation.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.apache.hop.neo4j.execution;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.hop.core.Const;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.gui.plugin.GuiElementType;
import org.apache.hop.core.gui.plugin.GuiPlugin;
import org.apache.hop.core.gui.plugin.GuiWidgetElement;
import org.apache.hop.core.json.HopJson;
import org.apache.hop.core.logging.ILogChannel;
import org.apache.hop.core.logging.LogChannel;
import org.apache.hop.core.logging.LogLevel;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.row.JsonRowMeta;
import org.apache.hop.core.row.RowBuffer;
import org.apache.hop.core.row.RowMeta;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.execution.Execution;
import org.apache.hop.execution.ExecutionBuilder;
import org.apache.hop.execution.ExecutionData;
import org.apache.hop.execution.ExecutionDataBuilder;
import org.apache.hop.execution.ExecutionDataSetMeta;
import org.apache.hop.execution.ExecutionInfoLocation;
import org.apache.hop.execution.ExecutionState;
import org.apache.hop.execution.ExecutionStateBuilder;
import org.apache.hop.execution.ExecutionStateComponentMetrics;
import org.apache.hop.execution.ExecutionType;
import org.apache.hop.execution.IExecutionInfoLocation;
import org.apache.hop.execution.IExecutionMatcher;
import org.apache.hop.execution.plugin.ExecutionInfoLocationPlugin;
import org.apache.hop.metadata.api.HopMetadataProperty;
import org.apache.hop.metadata.api.IHopMetadataProvider;
import org.apache.hop.neo4j.actions.index.IndexUpdate;
import org.apache.hop.neo4j.actions.index.Neo4jIndex;
import org.apache.hop.neo4j.actions.index.ObjectType;
import org.apache.hop.neo4j.actions.index.UpdateType;
import org.apache.hop.neo4j.execution.builder.CypherCreateBuilder;
import org.apache.hop.neo4j.execution.builder.CypherDeleteBuilder;
import org.apache.hop.neo4j.execution.builder.CypherMergeBuilder;
import org.apache.hop.neo4j.execution.builder.CypherQueryBuilder;
import org.apache.hop.neo4j.execution.builder.CypherRelationshipBuilder;
import org.apache.hop.neo4j.execution.builder.ICypherBuilder;
import org.apache.hop.neo4j.shared.NeoConnection;
import org.apache.hop.neo4j.shared.NeoConnectionTypeMetadata;
import org.apache.hop.ui.core.dialog.EnterTextDialog;
import org.apache.hop.ui.core.dialog.ErrorDialog;
import org.apache.hop.ui.core.dialog.MessageBox;
import org.apache.hop.ui.hopgui.HopGui;
import org.apache.hop.ui.hopgui.file.workflow.delegates.HopGuiWorkflowClipboardDelegate;
import org.apache.hop.workflow.action.ActionMeta;
import org.eclipse.swt.SWT;
import org.neo4j.driver.Driver;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.neo4j.driver.Transaction;
import org.neo4j.driver.Value;
@GuiPlugin(description = "Neo4j execution information location GUI elements")
@ExecutionInfoLocationPlugin(
id = "neo4j-location",
name = "Neo4j location",
description = "Stores execution information in a Neo4j graph database")
public class NeoExecutionInfoLocation implements IExecutionInfoLocation {
public static final String EL_EXECUTION = "Execution";
public static final String EP_ID = "id";
public static final String EP_NAME = "name";
public static final String EP_COPY_NR = "copyNr";
public static final String EP_FILENAME = "filename";
public static final String EP_PARENT_ID = "parentId";
public static final String EP_EXECUTION_TYPE = "executionType";
public static final String EP_EXECUTOR_XML = "executorXml";
public static final String EP_METADATA_JSON = "metadataJson";
public static final String EP_RUN_CONFIG_NAME = "runConfigName";
public static final String EP_LOG_LEVEL = "logLevel";
public static final String EP_REGISTRATION_DATE = "registrationDate";
public static final String EP_EXECUTION_START_DATE = "executionStartDate";
// The status fields
public static final String EP_LOGGING_TEXT = "loggingText";
public static final String EP_STATUS_DESCRIPTION = "statusDescription";
public static final String EP_UPDATE_TIME = "updateTime";
public static final String EP_CHILD_IDS = "childIds";
public static final String EP_FAILED = "failed";
public static final String EP_DETAILS = "details";
public static final String EP_CONTAINER_ID = "containerId";
public static final String EP_EXECUTION_END_DATE = "executionEndDate";
public static final String CL_EXECUTION_METRIC = "ExecutionMetric";
public static final String CP_ID = "id";
public static final String CP_NAME = "name";
public static final String CP_COPY_NR = "copyNr";
public static final String CP_METRIC_KEY = "metricKey";
public static final String CP_METRIC_VALUE = "metricValue";
public static final String DL_EXECUTION_DATA = "ExecutionData";
public static final String DP_PARENT_ID = "parentId";
public static final String DP_OWNER_ID = "ownerId";
public static final String DP_FINISHED = "finished";
public static final String DP_EXECUTION_TYPE = "executionType";
public static final String DP_COLLECTION_DATE = "collectionDate";
public static final String ML_EXECUTION_DATA_SET_META = "ExecutionDataSetMeta";
public static final String MP_PARENT_ID = "parentId";
public static final String MP_OWNER_ID = "ownerId";
public static final String MP_SET_KEY = "setKey";
public static final String MP_NAME = "name";
public static final String MP_COPY_NR = "copyNr";
public static final String MP_DESCRIPTION = "description";
public static final String MP_FIELD_NAME = "fieldName";
public static final String MP_LOG_CHANNEL_ID = "logChannelId";
public static final String MP_SAMPLE_DESCRIPTION = "sampleDescription";
public static final String TL_EXECUTION_DATA_SET = "ExecutionDataSet";
public static final String TP_PARENT_ID = "parentId";
public static final String TP_OWNER_ID = "ownerId";
public static final String TP_SET_KEY = "setKey";
public static final String TP_ROW_META_JSON = "rowMetaJson";
public static final String OL_EXECUTION_DATA_SET_ROW = "ExecutionDataSetRow";
public static final String OP_PARENT_ID = "parentId";
public static final String OP_OWNER_ID = "ownerId";
public static final String OP_SET_KEY = "setKey";
public static final String OP_ROW_NR = "rowNr";
public static final String R_EXECUTES = "EXECUTES";
public static final String R_HAS_DATA = "HAS_DATA";
public static final String R_HAS_METADATA = "HAS_METADATA";
public static final String R_HAS_DATASET = "HAS_DATASET";
public static final String R_HAS_ROW = "HAS_ROW";
@HopMetadataProperty protected String pluginId;
@HopMetadataProperty protected String pluginName;
@GuiWidgetElement(
id = "connectionName",
order = "010",
parentId = ExecutionInfoLocation.GUI_PLUGIN_ELEMENT_PARENT_ID,
type = GuiElementType.METADATA,
typeMetadata = NeoConnectionTypeMetadata.class,
toolTip = "i18n::NeoExecutionInfoLocation.Connection.Tooltip",
label = "i18n::NeoExecutionInfoLocation.Connection.Label")
@HopMetadataProperty(key = "connection")
protected String connectionName;
private ILogChannel log;
private Driver driver;
private Session session;
public NeoExecutionInfoLocation() {}
public NeoExecutionInfoLocation(NeoExecutionInfoLocation location) {
this.pluginId = location.pluginId;
this.pluginName = location.pluginName;
this.connectionName = location.connectionName;
}
@Override
public NeoExecutionInfoLocation clone() {
return new NeoExecutionInfoLocation(this);
}
@Override
public void initialize(IVariables variables, IHopMetadataProvider metadataProvider)
throws HopException {
this.log = LogChannel.GENERAL;
validateSettings();
try {
NeoConnection connection =
metadataProvider
.getSerializer(NeoConnection.class)
.load(variables.resolve(connectionName));
if (connection == null) {
throw new HopException("Unable to find Neo4j connection " + connectionName);
}
// Connect to the database
//
this.driver = connection.getDriver(log, variables);
this.session = connection.getSession(log, driver, variables);
} catch (Exception e) {
throw new HopException(
"Error initializing Neo4j Execution Information location for connection "
+ connectionName,
e);
}
}
@Override
public void close() throws HopException {
try {
session.close();
driver.close();
} catch (Exception e) {
throw new HopException("Error closing Neo4j execution information location", e);
}
}
/** Simply show the DDL to create the indexes */
@GuiWidgetElement(
id = "createIndexesButton",
order = "020",
parentId = ExecutionInfoLocation.GUI_PLUGIN_ELEMENT_PARENT_ID,
type = GuiElementType.BUTTON,
label = "i18n::NeoExecutionInfoLocation.CreateIndexes.Label",
toolTip = "i18n::NeoExecutionInfoLocation.CreateIndexes.Tooltip")
public void createIndexesButton(Object object) {
StringBuilder cypher = new StringBuilder();
addIndex(cypher, "idx_execution_id", EL_EXECUTION, EP_ID);
addIndex(cypher, "idx_execution_failed", EL_EXECUTION, EP_FAILED);
addIndex(cypher, "idx_execution_parent_id", EL_EXECUTION, EP_PARENT_ID);
addIndex(cypher, "idx_execution_metric_id", EL_EXECUTION, EP_ID, EP_NAME, EP_COPY_NR);
addIndex(cypher, "idx_execution_data_id", DL_EXECUTION_DATA, DP_PARENT_ID, DP_OWNER_ID);
addIndex(
cypher,
"idx_execution_data_set_meta_id",
ML_EXECUTION_DATA_SET_META,
MP_PARENT_ID,
MP_OWNER_ID,
MP_SET_KEY);
addIndex(
cypher,
"idx_execution_data_set_id",
TL_EXECUTION_DATA_SET,
TP_PARENT_ID,
TP_OWNER_ID,
TP_SET_KEY);
addIndex(
cypher,
"idx_execution_data_set_row_id",
OL_EXECUTION_DATA_SET_ROW,
OP_PARENT_ID,
OP_OWNER_ID,
OP_SET_KEY);
EnterTextDialog textDialog =
new EnterTextDialog(
HopGui.getInstance().getShell(),
"Indexes DDL",
"Here is the list of Cypher statements to execute for the Neo4j location",
cypher.toString());
textDialog.open();
}
private void addIndex(StringBuilder cypher, String indexName, String label, String... keys) {
assert keys != null && keys.length > 0 : "specify one or more keys";
String keysClause = "ON ";
boolean firstKey = true;
for (String key : keys) {
if (firstKey) {
firstKey = false;
keysClause += "( ";
} else {
keysClause += ", ";
}
keysClause += "n." + key;
}
keysClause += ") ";
cypher
.append("CREATE INDEX ")
.append(indexName)
.append(" IF NOT EXISTS FOR (n:")
.append(label)
.append(") ")
.append(keysClause);
cypher.append(Const.CR).append(";").append(Const.CR);
}
/** Copy a Neo4j Indexes action to the clipboard */
@GuiWidgetElement(
id = "createIndexesAction",
order = "030",
parentId = ExecutionInfoLocation.GUI_PLUGIN_ELEMENT_PARENT_ID,
type = GuiElementType.BUTTON,
label = "i18n::NeoExecutionInfoLocation.CreateIndexAction.Label",
toolTip = "i18n::NeoExecutionInfoLocation.CreateIndexAction.Tooltip")
public void copyIndexActionToClipboardButton(Object object) {
try {
Neo4jIndex neo4jIndex = new Neo4jIndex("Neo4j Index", null);
String connectionName = ((NeoExecutionInfoLocation) object).getConnectionName();
if (StringUtils.isNotEmpty(connectionName)) {
// Load the connection
//
NeoConnection neoConnection =
HopGui.getInstance()
.getMetadataProvider()
.getSerializer(NeoConnection.class)
.load(connectionName);
neo4jIndex.setConnection(neoConnection);
}
addIndex(neo4jIndex, "idx_execution_id", EL_EXECUTION, EP_ID);
addIndex(neo4jIndex, "idx_execution_failed", EL_EXECUTION, EP_FAILED);
addIndex(neo4jIndex, "idx_execution_parent_id", EL_EXECUTION, EP_PARENT_ID);
addIndex(neo4jIndex, "idx_execution_metric_id", EL_EXECUTION, EP_ID, EP_NAME, EP_COPY_NR);
addIndex(neo4jIndex, "idx_execution_data_id", DL_EXECUTION_DATA, DP_PARENT_ID, DP_OWNER_ID);
addIndex(
neo4jIndex,
"idx_execution_data_set_meta_id",
ML_EXECUTION_DATA_SET_META,
MP_PARENT_ID,
MP_OWNER_ID,
MP_SET_KEY);
addIndex(
neo4jIndex,
"idx_execution_data_set_id",
TL_EXECUTION_DATA_SET,
TP_PARENT_ID,
TP_OWNER_ID,
TP_SET_KEY);
addIndex(
neo4jIndex,
"idx_execution_data_set_row_id",
OL_EXECUTION_DATA_SET_ROW,
OP_PARENT_ID,
OP_OWNER_ID,
OP_SET_KEY);
// Wrap it in an ActionMeta object
//
ActionMeta actionMeta = new ActionMeta(neo4jIndex);
actionMeta.setLocation(50, 50);
// Copy to clipboard
HopGuiWorkflowClipboardDelegate.copyActionsToClipboard(List.of(actionMeta));
// Show the message box
//
MessageBox box =
new MessageBox(HopGui.getInstance().getShell(), SWT.OK | SWT.ICON_INFORMATION);
box.setText("Copied to clipboard");
box.setMessage(
"A Neo4j Index action was copied to the clipboard. You can paste this in a workflow to make sure you have great performance when updating execution information in this Neo4j location.");
box.open();
} catch (Exception e) {
new ErrorDialog(
HopGui.getInstance().getShell(),
"Error",
"Error copying Neo4j Index action to the clipboard",
e);
}
}
private void addIndex(Neo4jIndex neo4jIndex, String indexName, String label, String... keys) {
StringBuilder properties = new StringBuilder();
for (String key : keys) {
if (properties.length() > 0) {
properties.append(",");
}
properties.append(key);
}
IndexUpdate indexUpdate =
new IndexUpdate(
UpdateType.CREATE, ObjectType.NODE, indexName, label, properties.toString());
neo4jIndex.getIndexUpdates().add(indexUpdate);
}
private void validateSettings() throws HopException {
if (StringUtils.isEmpty(connectionName)) {
throw new HopException("Please specify a Neo4j connection to send execution information to.");
}
}
@Override
public void registerExecution(Execution execution) throws HopException {
synchronized (this) {
try {
assert execution.getName() != null : "Please register executions with a name";
assert execution.getExecutionType() != null
: "Please register executions with an execution type";
session.writeTransaction(transaction -> registerNeo4jExecution(transaction, execution));
} catch (Exception e) {
throw new HopException("Error registering execution in Neo4j", e);
}
}
}
private boolean registerNeo4jExecution(Transaction transaction, Execution execution) {
try {
CypherMergeBuilder builder =
CypherMergeBuilder.of()
.withLabelAndKey(EL_EXECUTION, EP_ID, execution.getId())
.withValue(EP_NAME, execution.getName())
.withValue(EP_COPY_NR, execution.getCopyNr())
.withValue(EP_FILENAME, execution.getFilename())
.withValue(EP_PARENT_ID, execution.getParentId())
.withValue(EP_EXECUTION_TYPE, execution.getExecutionType().name())
.withValue(EP_EXECUTOR_XML, execution.getExecutorXml())
.withValue(EP_METADATA_JSON, execution.getMetadataJson())
.withValue(EP_RUN_CONFIG_NAME, execution.getRunConfigurationName())
.withValue(
EP_LOG_LEVEL,
execution.getLogLevel() == null ? null : execution.getLogLevel().getCode())
.withValue(EP_REGISTRATION_DATE, execution.getRegistrationDate())
.withValue(EP_EXECUTION_START_DATE, execution.getExecutionStartDate());
execute(transaction, builder);
if (StringUtils.isNotEmpty(execution.getParentId())) {
CypherRelationshipBuilder selfRelationshipBuilder =
CypherRelationshipBuilder.of()
.withMatch(EL_EXECUTION, "e1", EP_ID, execution.getId())
.withMatch(EL_EXECUTION, "e2", EP_ID, execution.getParentId())
.withMerge("e2", "e1", R_EXECUTES);
execute(transaction, selfRelationshipBuilder);
}
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
throw e;
}
}
@Override
public boolean deleteExecution(String executionId) throws HopException {
synchronized (this) {
try {
return session.writeTransaction(
transaction -> deleteNeo4jExecution(transaction, executionId));
} catch (Exception e) {
throw new HopException("Error deleting execution with id " + executionId + " in Neo4j", e);
}
}
}
private boolean deleteNeo4jExecution(Transaction transaction, String executionId) {
// Get the children of this execution. Delete those first
//
List<Execution> childExecutions = findNeo4jExecutions(transaction, executionId);
for (Execution childExecution : childExecutions) {
deleteNeo4jExecution(transaction, childExecution.getId());
}
// Now delete any data, data sets, rows and metadata with the given execution ID as a parent
//
// Rows
//
execute(
transaction,
CypherDeleteBuilder.of()
.withMatch(OL_EXECUTION_DATA_SET_ROW, "n", Map.of(OP_PARENT_ID, executionId))
.withDetachDelete("n"));
// SetMeta
//
execute(
transaction,
CypherDeleteBuilder.of()
.withMatch(ML_EXECUTION_DATA_SET_META, "n", Map.of(MP_PARENT_ID, executionId))
.withDetachDelete("n"));
// DataSet
//
execute(
transaction,
CypherDeleteBuilder.of()
.withMatch(TL_EXECUTION_DATA_SET, "n", Map.of(TP_PARENT_ID, executionId))
.withDetachDelete("n"));
// Data
//
execute(
transaction,
CypherDeleteBuilder.of()
.withMatch(DL_EXECUTION_DATA, "n", Map.of(DP_PARENT_ID, executionId))
.withDetachDelete("n"));
// The execution metrics
//
execute(
transaction,
CypherDeleteBuilder.of()
.withMatch(CL_EXECUTION_METRIC, "n", Map.of(CP_ID, executionId))
.withDetachDelete("n"));
// The execution itself
//
execute(
transaction,
CypherDeleteBuilder.of()
.withMatch(EL_EXECUTION, "n", Map.of(EP_ID, executionId))
.withDetachDelete("n"));
return true;
}
@Override
public Execution getExecution(String executionId) throws HopException {
synchronized (this) {
try {
return session.readTransaction(transaction -> getNeo4jExecution(transaction, executionId));
} catch (Exception e) {
throw new HopException("Error getting execution from Neo4j", e);
}
}
}
private Execution getNeo4jExecution(Transaction transaction, String executionId) {
CypherQueryBuilder builder =
CypherQueryBuilder.of()
.withLabelAndKey("n", EL_EXECUTION, EP_ID, executionId)
.withReturnValues(
"n",
EP_NAME,
EP_COPY_NR,
EP_FILENAME,
EP_PARENT_ID,
EP_EXECUTION_TYPE,
EP_EXECUTOR_XML,
EP_METADATA_JSON,
EP_RUN_CONFIG_NAME,
EP_LOG_LEVEL,
EP_REGISTRATION_DATE,
EP_EXECUTION_START_DATE);
Result result = transaction.run(builder.cypher(), builder.parameters());
// We expect exactly one result
//
if (!result.hasNext()) {
return null;
}
org.neo4j.driver.Record record = result.next();
return ExecutionBuilder.of()
.withId(executionId)
.withParentId(getString(record, EP_PARENT_ID))
.withName(getString(record, EP_NAME))
.withCopyNr(getString(record, EP_COPY_NR))
.withFilename(getString(record, EP_FILENAME))
.withExecutorType(ExecutionType.valueOf(getString(record, EP_EXECUTION_TYPE)))
.withExecutorXml(getString(record, EP_EXECUTOR_XML))
.withMetadataJson(getString(record, EP_METADATA_JSON))
.withRunConfigurationName(getString(record, EP_RUN_CONFIG_NAME))
.withLogLevel(LogLevel.getLogLevelForCode(getString(record, EP_LOG_LEVEL)))
.withRegistrationDate(getDate(record, EP_REGISTRATION_DATE))
.withExecutionStartDate(getDate(record, EP_EXECUTION_START_DATE))
.build();
}
@Override
public List<String> getExecutionIds(boolean includeChildren, int limit) throws HopException {
synchronized (this) {
try {
return session.readTransaction(
transaction -> getNeo4jExecutionIds(transaction, includeChildren, limit));
} catch (Exception e) {
throw new HopException("Error getting execution from Neo4j", e);
}
}
}
private List<String> getNeo4jExecutionIds(
Transaction transaction, boolean includeChildren, int limit) {
List<String> ids = new ArrayList<>();
CypherQueryBuilder builder =
CypherQueryBuilder.of().withLabelWithoutKey("n", EL_EXECUTION) // Get all nodes
;
if (!includeChildren) {
builder.withWhereIsNull("n", EP_PARENT_ID);
}
builder
.withReturnValues("n", EP_ID) // Just return the execution ID
.withOrderBy("n", EP_REGISTRATION_DATE, false)
.withLimit(limit);
Result result = transaction.run(builder.cypher());
while (result.hasNext()) {
org.neo4j.driver.Record record = result.next();
ids.add(getString(record, EP_ID));
}
return ids;
}
@Override
public void updateExecutionState(ExecutionState executionState) throws HopException {
synchronized (this) {
try {
assert executionState.getName() != null : "Please update execution states with a name";
assert executionState.getExecutionType() != null
: "Please update execution states with an execution type";
session.writeTransaction(
transaction -> updateNeo4jExecutionState(transaction, executionState));
} catch (Exception e) {
throw new HopException("Error updating execution state in Neo4j", e);
}
}
}
private boolean updateNeo4jExecutionState(Transaction transaction, ExecutionState state) {
try {
// Update information in the Execution node
//
CypherMergeBuilder stateCypherBuilder =
CypherMergeBuilder.of()
.withLabelAndKey(EL_EXECUTION, EP_ID, state.getId())
.withValue(EP_STATUS_DESCRIPTION, state.getStatusDescription())
.withValue(EP_LOGGING_TEXT, state.getLoggingText())
.withValue(EP_UPDATE_TIME, state.getUpdateTime())
.withValue(EP_CHILD_IDS, state.getChildIds())
.withValue(EP_FAILED, state.isFailed())
.withValue(EP_DETAILS, state.getDetails())
.withValue(EP_CONTAINER_ID, state.getContainerId())
.withValue(EP_EXECUTION_END_DATE, state.getExecutionEndDate());
transaction.run(stateCypherBuilder.cypher(), stateCypherBuilder.parameters());
// Save the metrics as well...
//
if (state.getMetrics() != null) {
for (ExecutionStateComponentMetrics metric : state.getMetrics()) {
// Save all the metrics in this map in there...
//
for (String metricKey : metric.getMetrics().keySet()) {
CypherCreateBuilder metricBuilder =
CypherCreateBuilder.of()
.withLabelAndKeys(
CL_EXECUTION_METRIC,
Map.of(
CP_ID, state.getId(),
CP_NAME, metric.getComponentName(),
CP_COPY_NR, metric.getComponentCopy(),
CP_METRIC_KEY, metricKey))
.withValue(CP_METRIC_VALUE, metric.getMetrics().get(metricKey));
execute(transaction, metricBuilder);
}
}
}
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
throw e;
}
}
@Override
public ExecutionState getExecutionState(String executionId) throws HopException {
synchronized (this) {
try {
return session.readTransaction(
transaction -> getNeo4jExecutionState(transaction, executionId));
} catch (Exception e) {
throw new HopException("Error getting execution from Neo4j", e);
}
}
}
private ExecutionState getNeo4jExecutionState(Transaction transaction, String executionId) {
CypherQueryBuilder executionBuilder =
CypherQueryBuilder.of()
.withLabelAndKey("n", EL_EXECUTION, EP_ID, executionId)
.withReturnValues(
"n",
EP_NAME,
EP_EXECUTION_TYPE,
EP_COPY_NR,
EP_PARENT_ID,
EP_LOGGING_TEXT,
EP_STATUS_DESCRIPTION,
EP_UPDATE_TIME,
EP_CHILD_IDS,
EP_FAILED,
EP_DETAILS,
EP_CONTAINER_ID,
EP_EXECUTION_END_DATE);
Result result = transaction.run(executionBuilder.cypher(), executionBuilder.parameters());
// We expect exactly one result
//
if (!result.hasNext()) {
return null;
}
org.neo4j.driver.Record record = result.next();
ExecutionStateBuilder stateBuilder =
ExecutionStateBuilder.of()
.withId(executionId)
.withName(getString(record, EP_NAME))
.withCopyNr(getString(record, EP_COPY_NR))
.withParentId(getString(record, EP_PARENT_ID))
.withLoggingText(getString(record, EP_LOGGING_TEXT))
.withExecutionType(ExecutionType.valueOf(getString(record, EP_EXECUTION_TYPE)))
.withStatusDescription(getString(record, EP_STATUS_DESCRIPTION))
.withUpdateTime(getDate(record, EP_UPDATE_TIME))
.withChildIds(getList(record, EP_CHILD_IDS))
.withFailed(getBoolean(record, EP_FAILED))
.withDetails(getMap(record, EP_DETAILS))
.withContainerId(getString(record, EP_CONTAINER_ID))
.withExecutionEndDate(getDate(record, EP_EXECUTION_END_DATE));
// Add the metrics to the state...
//
Result metricsResult =
execute(
transaction,
CypherQueryBuilder.of()
.withLabelAndKeys("n", CL_EXECUTION_METRIC, Map.of(CP_ID, executionId))
.withReturnValues("n", CP_NAME, CP_COPY_NR, CP_METRIC_KEY, CP_METRIC_VALUE));
Map<String, ExecutionStateComponentMetrics> metricsMap = new HashMap<>();
while (metricsResult.hasNext()) {
org.neo4j.driver.Record metricsRecord = metricsResult.next();
String componentName = getString(metricsRecord, CP_NAME);
String componentCopy = getString(metricsRecord, CP_COPY_NR);
String componentKey = componentName + "." + componentCopy;
String metricKey = getString(metricsRecord, CP_METRIC_KEY);
Long metricValue = getLong(metricsRecord, CP_METRIC_VALUE);
if (metricValue != null) {
// Add it to the map...
//
ExecutionStateComponentMetrics metric =
metricsMap.computeIfAbsent(
componentKey,
f -> new ExecutionStateComponentMetrics(componentName, componentCopy));
// Add the value
metric.getMetrics().put(metricKey, metricValue);
}
}
stateBuilder.withMetrics(new ArrayList(metricsMap.values()));
return stateBuilder.build();
}
@Override
public List<Execution> findExecutions(String parentExecutionId) throws HopException {
synchronized (this) {
try {
return session.readTransaction(
transaction -> findNeo4jExecutions(transaction, parentExecutionId));
} catch (Exception e) {
throw new HopException("Error getting execution from Neo4j", e);
}
}
}
/**
* Go over the executions and match those with type and name. They are reverse ordered by date so
* we look for the first in the list that doesn't have a failed state.
*
* @param executionType The type of execution to look for
* @param name The name of the executor
* @return
* @throws HopException
*/
@Override
public Execution findPreviousSuccessfulExecution(ExecutionType executionType, String name)
throws HopException {
synchronized (this) {
try {
return session.readTransaction(
transaction -> findNeo4jPreviousSuccessfulExecution(transaction, executionType, name));
} catch (Exception e) {
throw new HopException("Error find previous successful execution in Neo4j", e);
}
}
}
private Execution findNeo4jPreviousSuccessfulExecution(
Transaction transaction, ExecutionType executionType, String name) {
List<Execution> executions =
findNeo4jExecutions(
transaction, e -> e.getExecutionType() == executionType && name.equals(e.getName()));
for (Execution execution : executions) {
ExecutionState executionState = getNeo4jExecutionState(transaction, execution.getId());
if (executionState != null && !executionState.isFailed()) {
return execution;
}
}
return null;
}
/**
* Find those Executions that have a matching parentId
*
* @param transaction
* @param parentExecutionId
* @return The list of executions or an empty list if nothing was found
*/
private List<Execution> findNeo4jExecutions(Transaction transaction, String parentExecutionId) {
List<Execution> executions = new ArrayList<>();
Result result =
execute(
transaction,
CypherQueryBuilder.of()
.withLabelAndKey("n", EL_EXECUTION, EP_PARENT_ID, parentExecutionId)
.withReturnValues("n", EP_ID));
while (result.hasNext()) {
org.neo4j.driver.Record record = result.next();
String executionId = getString(record, EP_ID);
try {
Execution execution = getNeo4jExecution(transaction, executionId);
if (execution != null) {
executions.add(execution);
}
} catch (Exception e) {
log.logError(
"Error loading execution with id : " + executionId + " from Neo4j (non-fatal)", e);
}
}
return executions;
}
@Override
public List<Execution> findExecutions(IExecutionMatcher matcher) throws HopException {
synchronized (this) {
try {
return session.readTransaction(transaction -> findNeo4jExecutions(transaction, matcher));
} catch (Exception e) {
throw new HopException("Error getting execution from Neo4j", e);
}
}
}
private List<Execution> findNeo4jExecutions(Transaction transaction, IExecutionMatcher matcher) {
List<Execution> executions = new ArrayList<>();
// Get all
List<String> ids = getNeo4jExecutionIds(transaction, true, 0);
for (String id : ids) {
Execution execution = getNeo4jExecution(transaction, id);
if (execution != null && matcher.matches(execution)) {
executions.add(execution);
}
}
return executions;
}
@Override
public void registerData(ExecutionData data) throws HopException {
synchronized (this) {
try {
session.writeTransaction(transaction -> registerNeo4jData(transaction, data));
} catch (Exception e) {
throw new HopException("Error getting execution from Neo4j", e);
}
}
}
private boolean registerNeo4jData(Transaction transaction, ExecutionData data) {
try {
assert data != null : "no execution data provided";
assert data.getExecutionType() != null : "execution data has no type";
// Merge the ExecutionData node
//
CypherMergeBuilder stateCypherBuilder =
CypherMergeBuilder.of()
.withLabelAndKeys(
DL_EXECUTION_DATA,
Map.of(DP_PARENT_ID, data.getParentId(), DP_OWNER_ID, data.getOwnerId()))
.withValue(DP_EXECUTION_TYPE, data.getExecutionType().name())
.withValue(DP_FINISHED, data.isFinished())
.withValue(DP_COLLECTION_DATE, data.getCollectionDate());
execute(transaction, stateCypherBuilder);
// Merge the relationship between Execution and ExecutionData and ExecutionState
//
CypherRelationshipBuilder executionDataRelCypherBuilder =
CypherRelationshipBuilder.of()
.withMatch(EL_EXECUTION, "n", EP_ID, data.getParentId())
.withMatch(
DL_EXECUTION_DATA,
"d",
Map.of(DP_PARENT_ID, data.getParentId(), DP_OWNER_ID, data.getOwnerId()))
.withMerge("n", "d", R_HAS_DATA);
execute(transaction, executionDataRelCypherBuilder);
// Do we have metadata directly at the top level of the execution data?
//
ExecutionDataSetMeta dataSetMeta = data.getDataSetMeta();
if (dataSetMeta != null) {
saveDataSetMeta(transaction, data.getParentId(), data.getOwnerId(), dataSetMeta);
// Also save the relationship between the execution data and the metadata
//
execute(
transaction,
CypherRelationshipBuilder.of()
.withMatch(
DL_EXECUTION_DATA,
"s",
Map.of(DP_PARENT_ID, data.getParentId(), DP_OWNER_ID, data.getOwnerId()))
.withMatch(
ML_EXECUTION_DATA_SET_META,
"m",
Map.of(
MP_PARENT_ID,
data.getParentId(),
MP_OWNER_ID,
data.getOwnerId(),
MP_SET_KEY,
dataSetMeta.getSetKey()))
.withMerge("s", "m", R_HAS_METADATA));
}
// Do we have any data sets?
//
for (String setKey : data.getDataSets().keySet()) {
RowBuffer rowBuffer = data.getDataSets().get(setKey);
ExecutionDataSetMeta setMeta = data.getSetMetaData().get(setKey);
saveNeo4jRowsAndMeta(
transaction, data.getParentId(), data.getOwnerId(), rowBuffer, setMeta);
}
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
throw e;
}
}
private void saveNeo4jRowsAndMeta(
Transaction transaction,
String parentId,
String ownerId,
RowBuffer rowBuffer,
ExecutionDataSetMeta setMeta) {
try {
IRowMeta rowMeta = rowBuffer.getRowMeta();
String rowMetaJson = rowMeta == null ? null : JsonRowMeta.toJson(rowMeta);
// Save the Execution Data Set node
//
execute(
transaction,
CypherMergeBuilder.of()
.withLabelAndKeys(
TL_EXECUTION_DATA_SET,
Map.of(
TP_PARENT_ID,
parentId,
TP_OWNER_ID,
ownerId,
TP_SET_KEY,
setMeta.getSetKey()))
.withValue(TP_ROW_META_JSON, rowMetaJson));
// Create a relationship between the execution data and the data set
//
execute(
transaction,
CypherRelationshipBuilder.of()
.withMatch(
DL_EXECUTION_DATA, "d", Map.of(DP_PARENT_ID, parentId, DP_OWNER_ID, ownerId))
.withMatch(
TL_EXECUTION_DATA_SET,
"s",
Map.of(
TP_PARENT_ID,
parentId,
TP_OWNER_ID,
ownerId,