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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
|
/*-
* ============LICENSE_START=======================================================
* org.openecomp.aai
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.openecomp.aai.dbgen;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.openecomp.aai.db.props.AAIProperties;
import org.openecomp.aai.dbmap.AAIGraph;
import org.openecomp.aai.exceptions.AAIException;
import org.openecomp.aai.introspection.Introspector;
import org.openecomp.aai.introspection.Loader;
import org.openecomp.aai.introspection.LoaderFactory;
import org.openecomp.aai.introspection.ModelType;
import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException;
import org.openecomp.aai.logging.ErrorLogHelper;
import org.openecomp.aai.serialization.db.AAIDirection;
import org.openecomp.aai.serialization.db.EdgeProperty;
import org.openecomp.aai.util.AAIConfig;
import org.openecomp.aai.util.AAIConstants;
import org.openecomp.aai.util.FormatDate;
import com.att.eelf.configuration.Configuration;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.thinkaurelius.titan.core.TitanFactory;
import com.thinkaurelius.titan.core.TitanGraph;
public class DataGrooming {
private static EELFLogger LOGGER;
private static final String FROMAPPID = "AAI-DB";
private static final String TRANSID = UUID.randomUUID().toString();
private static int dupeGrpsDeleted = 0;
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
// Set the logging file properties to be used by EELFManager
Properties props = System.getProperties();
props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_DATA_GROOMING_LOGBACK_PROPS);
props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES);
LOGGER = EELFManager.getInstance().getLogger(DataGrooming.class);
String ver = "version"; // Placeholder
Boolean doAutoFix = false;
Boolean edgesOnlyFlag = false;
Boolean dontFixOrphansFlag = false;
Boolean skipHostCheck = false;
Boolean singleCommits = false;
Boolean dupeCheckOff = false;
Boolean dupeFixOn = false;
Boolean ghost2CheckOff = false;
Boolean ghost2FixOn = false;
Boolean neverUseCache = false;
Boolean skipEdgeCheckFlag = false;
int timeWindowMinutes = 0; // A value of 0 means that we will not have a time-window -- we will look
// at all nodes of the passed-in nodeType.
long windowStartTime = 0; // Translation of the window into a starting timestamp
int maxRecordsToFix = AAIConstants.AAI_GROOMING_DEFAULT_MAX_FIX;
int sleepMinutes = AAIConstants.AAI_GROOMING_DEFAULT_SLEEP_MINUTES;
try {
String maxFixStr = AAIConfig.get("aai.grooming.default.max.fix");
if( maxFixStr != null && !maxFixStr.equals("") ){
maxRecordsToFix = Integer.parseInt(maxFixStr);
}
String sleepStr = AAIConfig.get("aai.grooming.default.sleep.minutes");
if( sleepStr != null && !sleepStr.equals("") ){
sleepMinutes = Integer.parseInt(sleepStr);
}
}
catch ( Exception e ){
// Don't worry, we'll just use the defaults that we got from AAIConstants
LOGGER.warn("WARNING - could not pick up aai.grooming values from aaiconfig.properties file. ");
}
String prevFileName = "";
dupeGrpsDeleted = 0;
FormatDate fd = new FormatDate("yyyyMMddHHmm", "GMT");
String dteStr = fd.getDateTime();
String groomOutFileName = "dataGrooming." + dteStr + ".out";
String argString = "";
for( int x = 0; x < args.length; x++ ) {
argString = argString + " " + args[x];
}
LOGGER.info(" DataGrooming called with these options: [" + argString + "]");
if (args.length > 0) {
// They passed some arguments in that will affect processing
for (int i = 0; i < args.length; i++) {
String thisArg = args[i];
if (thisArg.equals("-edgesOnly")) {
edgesOnlyFlag = true;
} else if (thisArg.equals("-autoFix")) {
doAutoFix = true;
} else if (thisArg.equals("-skipHostCheck")) {
skipHostCheck = true;
} else if (thisArg.equals("-dontFixOrphans")) {
dontFixOrphansFlag = true;
} else if (thisArg.equals("-singleCommits")) {
singleCommits = true;
} else if (thisArg.equals("-dupeCheckOff")) {
dupeCheckOff = true;
} else if (thisArg.equals("-dupeFixOn")) {
dupeFixOn = true;
} else if (thisArg.equals("-ghost2CheckOff")) {
ghost2CheckOff = true;
} else if (thisArg.equals("-neverUseCache")) {
neverUseCache = true;
} else if (thisArg.equals("-ghost2FixOn")) {
ghost2FixOn = true;
} else if (thisArg.equals("-skipEdgeChecks")) {
skipEdgeCheckFlag = true;
} else if (thisArg.equals("-maxFix")) {
i++;
if (i >= args.length) {
LOGGER.error(" No value passed with -maxFix option. ");
System.exit(0);
}
String nextArg = args[i];
try {
maxRecordsToFix = Integer.parseInt(nextArg);
} catch (Exception e) {
LOGGER.error("Bad value passed with -maxFix option: ["
+ nextArg + "]");
System.exit(0);
}
} else if (thisArg.equals("-sleepMinutes")) {
i++;
if (i >= args.length) {
LOGGER.error("No value passed with -sleepMinutes option.");
System.exit(0);
}
String nextArg = args[i];
try {
sleepMinutes = Integer.parseInt(nextArg);
} catch (Exception e) {
LOGGER.error("Bad value passed with -sleepMinutes option: ["
+ nextArg + "]");
System.exit(0);
}
} else if (thisArg.equals("-timeWindowMinutes")) {
i++;
if (i >= args.length) {
LOGGER.error("No value passed with -timeWindowMinutes option.");
System.exit(0);
}
String nextArg = args[i];
try {
timeWindowMinutes = Integer.parseInt(nextArg);
} catch (Exception e) {
LOGGER.error("Bad value passed with -timeWindowMinutes option: ["
+ nextArg + "]");
System.exit(0);
}
if( timeWindowMinutes > 0 ){
// Translate the window value (ie. 30 minutes) into a unix timestamp like
// we use in the db - so we can select data created after that time.
windowStartTime = figureWindowStartTime( timeWindowMinutes );
}
} else if (thisArg.equals("-f")) {
i++;
if (i >= args.length) {
LOGGER.error(" No value passed with -f option. ");
System.exit(0);
}
prevFileName = args[i];
} else {
LOGGER.error(" Unrecognized argument passed to DataGrooming: ["
+ thisArg + "]. ");
LOGGER.error(" Valid values are: -f -autoFix -maxFix -edgesOnly -dupeFixOn -donFixOrphans -sleepMinutes -neverUseCache");
System.exit(0);
}
}
}
try {
LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST);
}
catch (Exception ex){
LOGGER.error("ERROR - Could not create loader", ex);
System.exit(1);
}
try {
if (!prevFileName.equals("")) {
// They are trying to fix some data based on a data in a
// previous file.
LOGGER.info(" Call doTheGrooming() with a previous fileName ["
+ prevFileName + "] for cleanup. ");
Boolean finalShutdownFlag = true;
Boolean cacheDbOkFlag = false;
doTheGrooming(prevFileName, edgesOnlyFlag, dontFixOrphansFlag,
maxRecordsToFix, groomOutFileName, ver, singleCommits,
dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn,
finalShutdownFlag, cacheDbOkFlag,
skipEdgeCheckFlag, windowStartTime);
} else if (doAutoFix) {
// They want us to run the processing twice -- first to look for
// delete candidates, then after
// napping for a while, run it again and delete any candidates
// that were found by the first run.
// Note: we will produce a separate output file for each of the
// two runs.
LOGGER.info(" Doing an auto-fix call to Grooming. ");
LOGGER.info(" First, Call doTheGrooming() to look at what's out there. ");
Boolean finalShutdownFlag = false;
Boolean cacheDbOkFlag = true;
int fixCandCount = doTheGrooming("", edgesOnlyFlag,
dontFixOrphansFlag, maxRecordsToFix, groomOutFileName,
ver, singleCommits, dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn,
finalShutdownFlag, cacheDbOkFlag,
skipEdgeCheckFlag, windowStartTime);
if (fixCandCount == 0) {
LOGGER.info(" No fix-Candidates were found by the first pass, so no second/fix-pass is needed. ");
} else {
// We'll sleep a little and then run a fix-pass based on the
// first-run's output file.
try {
LOGGER.info("About to sleep for " + sleepMinutes
+ " minutes.");
int sleepMsec = sleepMinutes * 60 * 1000;
Thread.sleep(sleepMsec);
} catch (InterruptedException ie) {
LOGGER.info("\n >>> Sleep Thread has been Interrupted <<< ");
System.exit(0);
}
dteStr = fd.getDateTime();
String secondGroomOutFileName = "dataGrooming." + dteStr
+ ".out";
LOGGER.info(" Now, call doTheGrooming() a second time and pass in the name of the file "
+ "generated by the first pass for fixing: ["
+ groomOutFileName + "]");
finalShutdownFlag = true;
cacheDbOkFlag = false;
doTheGrooming(groomOutFileName, edgesOnlyFlag,
dontFixOrphansFlag, maxRecordsToFix,
secondGroomOutFileName, ver, singleCommits,
dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn,
finalShutdownFlag, cacheDbOkFlag,
skipEdgeCheckFlag, windowStartTime);
}
} else {
// Do the grooming - plain vanilla (no fix-it-file, no
// auto-fixing)
Boolean finalShutdownFlag = true;
LOGGER.info(" Call doTheGrooming() ");
Boolean cacheDbOkFlag = true;
if( neverUseCache ){
// They have forbidden us from using a cached db connection.
cacheDbOkFlag = false;
}
doTheGrooming("", edgesOnlyFlag, dontFixOrphansFlag,
maxRecordsToFix, groomOutFileName, ver, singleCommits,
dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn,
finalShutdownFlag, cacheDbOkFlag,
skipEdgeCheckFlag, windowStartTime);
}
} catch (Exception ex) {
LOGGER.error("Exception while grooming data", ex);
}
LOGGER.info(" Done! ");
System.exit(0);
}// End of main()
/**
* Do the grooming.
*
* @param fileNameForFixing the file name for fixing
* @param edgesOnlyFlag the edges only flag
* @param dontFixOrphansFlag the dont fix orphans flag
* @param maxRecordsToFix the max records to fix
* @param groomOutFileName the groom out file name
* @param version the version
* @param singleCommits the single commits
* @param dupeCheckOff the dupe check off
* @param dupeFixOn the dupe fix on
* @param ghost2CheckOff the ghost 2 check off
* @param ghost2FixOn the ghost 2 fix on
* @param finalShutdownFlag the final shutdown flag
* @param cacheDbOkFlag the cacheDbOk flag
* @return the int
*/
private static int doTheGrooming(String fileNameForFixing,
Boolean edgesOnlyFlag, Boolean dontFixOrphansFlag,
int maxRecordsToFix, String groomOutFileName, String version,
Boolean singleCommits,
Boolean dupeCheckOff, Boolean dupeFixOn,
Boolean ghost2CheckOff, Boolean ghost2FixOn,
Boolean finalShutdownFlag, Boolean cacheDbOkFlag,
Boolean skipEdgeCheckFlag, long windowStartTime) {
LOGGER.debug(" Entering doTheGrooming \n");
int cleanupCandidateCount = 0;
BufferedWriter bw = null;
TitanGraph graph = null;
TitanGraph graph2 = null;
int deleteCount = 0;
boolean executeFinalCommit = false;
Set<String> deleteCandidateList = new LinkedHashSet<>();
Set<String> processedVertices = new LinkedHashSet<>();
Graph g = null;
Graph g2 = null;
try {
AAIConfig.init();
String targetDir = AAIConstants.AAI_HOME + AAIConstants.AAI_FILESEP
+ "logs" + AAIConstants.AAI_FILESEP + "data"
+ AAIConstants.AAI_FILESEP + "dataGrooming";
// Make sure the target directory exists
new File(targetDir).mkdirs();
if (!fileNameForFixing.equals("")) {
deleteCandidateList = getDeleteList(targetDir,
fileNameForFixing, edgesOnlyFlag, dontFixOrphansFlag,
dupeFixOn);
}
if (deleteCandidateList.size() > maxRecordsToFix) {
LOGGER.warn(" >> WARNING >> Delete candidate list size ("
+ deleteCandidateList.size()
+ ") is too big. The maxFix we are using is: "
+ maxRecordsToFix
+ ". No candidates will be deleted. ");
// Clear out the list so it won't be processed below.
deleteCandidateList = new LinkedHashSet<>();
}
String fullOutputFileName = targetDir + AAIConstants.AAI_FILESEP
+ groomOutFileName;
File groomOutFile = new File(fullOutputFileName);
try {
groomOutFile.createNewFile();
} catch (IOException e) {
String emsg = " Problem creating output file ["
+ fullOutputFileName + "], exception=" + e.getMessage();
throw new AAIException("AAI_6124", emsg);
}
LOGGER.info(" Will write to " + fullOutputFileName );
bw = new BufferedWriter(new FileWriter(groomOutFile.getAbsoluteFile()));
ErrorLogHelper.loadProperties();
LOGGER.info(" ---- NOTE --- about to open graph (takes a little while)--------\n");
if( cacheDbOkFlag ){
// Since we're just reading (not deleting/fixing anything), we can use
// a cached connection to the DB
graph = TitanFactory.open(AAIConstants.CACHED_DB_CONFIG);
}
else {
graph = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG);
}
if (graph == null) {
String emsg = "null graph object in DataGrooming\n";
throw new AAIException("AAI_6101", emsg);
}
LOGGER.debug(" Got the graph object. ");
g = graph.newTransaction();
if (g == null) {
String emsg = "null graphTransaction object in DataGrooming\n";
throw new AAIException("AAI_6101", emsg);
}
GraphTraversalSource source1 = g.traversal();
ArrayList<String> errArr = new ArrayList<>();
int totalNodeCount = 0;
HashMap<String, String> misMatchedHash = new HashMap<String, String>();
HashMap<String, Vertex> orphanNodeHash = new HashMap<String, Vertex>();
HashMap<String, Vertex> missingDepNodeHash = new HashMap<String, Vertex>();
HashMap<String, Edge> oneArmedEdgeHash = new HashMap<String, Edge>();
HashMap<String, String> emptyVertexHash = new HashMap<String, String>();
HashMap<String, Vertex> ghostNodeHash = new HashMap<String, Vertex>();
ArrayList<String> dupeGroups = new ArrayList<>();
Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST);
Set<Entry<String, Introspector>> entrySet = loader.getAllObjects().entrySet();
String ntList = "";
LOGGER.info(" Starting DataGrooming Processing ");
if (edgesOnlyFlag) {
LOGGER.info(" NOTE >> Skipping Node processing as requested. Will only process Edges. << ");
}
else {
for (Entry<String, Introspector> entry : entrySet) {
String nType = entry.getKey();
int thisNtCount = 0;
int thisNtDeleteCount = 0;
LOGGER.debug(" > Look at : [" + nType + "] ...");
ntList = ntList + "," + nType;
// Get a collection of the names of the key properties for this nodeType to use later
// Determine what the key fields are for this nodeType
Collection <String> keyProps = entry.getValue().getKeys();
// Get the types of nodes that this nodetype depends on for uniqueness (if any)
Collection <String> depNodeTypes = loader.introspectorFromName(nType).getDependentOn();
// Loop through all the nodes of this Node type
int lastShownForNt = 0;
ArrayList <Vertex> tmpList = new ArrayList <> ();
Iterator <Vertex> iterv = source1.V().has("aai-node-type",nType);
while (iterv.hasNext()) {
// We put the nodes into an ArrayList because the graph.query iterator can time out
tmpList.add(iterv.next());
}
Iterator <Vertex> iter = tmpList.iterator();
while (iter.hasNext()) {
try {
thisNtCount++;
if( thisNtCount == lastShownForNt + 250 ){
lastShownForNt = thisNtCount;
LOGGER.debug("count for " + nType + " so far = " + thisNtCount );
}
Vertex thisVtx = iter.next();
if( windowStartTime > 0 ){
// We only want nodes that are created after a passed-in timestamp
Object objTimeStamp = thisVtx.property("aai-created-ts").orElse(null);
if( objTimeStamp != null ){
long thisNodeCreateTime = (long)objTimeStamp;
if( thisNodeCreateTime < windowStartTime ){
// It is NOT in our window, so we can pass over it
continue;
}
}
}
String thisVid = thisVtx.id().toString();
if (processedVertices.contains(thisVid)) {
LOGGER.debug("skipping already processed vertex: " + thisVid);
continue;
}
totalNodeCount++;
List <Vertex> secondGetList = new ArrayList <> ();
// -----------------------------------------------------------------------
// For each vertex of this nodeType, we want to:
// a) make sure that it can be retrieved using it's AAI defined key
// b) make sure that it is not a duplicate
// -----------------------------------------------------------------------
// For this instance of this nodeType, get the key properties
HashMap<String, Object> propHashWithKeys = new HashMap<>();
Iterator<String> keyPropI = keyProps.iterator();
while (keyPropI.hasNext()) {
String propName = keyPropI.next();
String propVal = "";
//delete an already deleted vertex
Object obj = thisVtx.<Object>property(propName).orElse(null);
if (obj != null) {
propVal = obj.toString();
}
propHashWithKeys.put(propName, propVal);
}
try {
// If this node is dependent on another for uniqueness, then do the query from that parent node
// Note - all of our nodes that are dependent on others for uniqueness are
// "children" of that node.
boolean depNodeOk = true;
if( depNodeTypes.isEmpty() ){
// This kind of node is not dependent on any other.
// Make sure we can get it back using it's key properties and that we only get one.
secondGetList = getNodeJustUsingKeyParams( TRANSID, FROMAPPID, source1, nType,
propHashWithKeys, version );
}
else {
// This kind of node is dependent on another for uniqueness.
// Start at it's parent (the dependent vertex) and make sure we can get it
// back using it's key properties and that we only get one.
Iterator <Vertex> vertI2 = source1.V(thisVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV());
Vertex parentVtx = null;
int pCount = 0;
while( vertI2 != null && vertI2.hasNext() ){
parentVtx = vertI2.next();
pCount++;
}
if( pCount <= 0 ){
//List<Vertex> vertI2 = g.traversal().V(thisVtx).union(__.outE().has("isParent-REV",true).outV(),__.inE().has("isParent",true).inV()).toList();
//if( vertI2.isEmpty()){
// It's Missing it's dependent/parent node
depNodeOk = false;
boolean zeroEdges = false;
try {
Iterator<Edge> tmpEdgeIter = thisVtx.edges(Direction.BOTH);
int edgeCount = 0;
while( tmpEdgeIter.hasNext() ){
edgeCount++;
tmpEdgeIter.next();
}
if( edgeCount == 0 ){
zeroEdges = true;
}
} catch (Exception ex) {
LOGGER.warn("WARNING from inside the for-each-vid-loop orphan-edges-check ", ex);
}
if (deleteCandidateList.contains(thisVid)) {
boolean okFlag = true;
try {
processedVertices.add(thisVtx.id().toString());
thisVtx.remove();
deleteCount++;
thisNtDeleteCount++;
} catch (Exception e) {
okFlag = false;
LOGGER.error("ERROR trying to delete missing-dep-node VID = " + thisVid, e);
}
if (okFlag) {
LOGGER.info(" DELETED missing-dep-node VID = " + thisVid);
}
} else {
// We count nodes missing their depNodes two ways - the first if it has
// at least some edges, and the second if it has zero edges. Either
// way, they are effectively orphaned.
// NOTE - Only nodes that have dependent nodes are ever considered "orphaned".
if( zeroEdges ){
missingDepNodeHash.put(thisVid, thisVtx);
}
else {
orphanNodeHash.put(thisVid, thisVtx);
}
}
}
else if ( pCount > 1 ){
// Not sure how this could happen? Should we do something here?
depNodeOk = false;
}
else {
// We found the parent - so use it to do the second-look.
// NOTE --- We're just going to do the same check from the other direction - because
// there could be duplicates or the pointer going the other way could be broken
ArrayList <Vertex> tmpListSec = new ArrayList <> ();
tmpListSec = getConnectedChildrenOfOneType( source1, parentVtx, nType ) ;
Iterator<Vertex> vIter = tmpListSec.iterator();
while (vIter.hasNext()) {
Vertex tmpV = vIter.next();
if( vertexHasTheseKeys(tmpV, propHashWithKeys) ){
secondGetList.add(tmpV);
}
}
}
}
if( depNodeOk && (secondGetList == null || secondGetList.size() == 0) ){
// We could not get the node back using it's own key info.
// So, it's a PHANTOM
if (deleteCandidateList.contains(thisVid)) {
boolean okFlag = true;
try {
thisVtx.remove();
deleteCount++;
thisNtDeleteCount++;
} catch (Exception e) {
okFlag = false;
LOGGER.error("ERROR trying to delete phantom VID = " + thisVid, e);
}
if (okFlag) {
LOGGER.info(" DELETED VID = " + thisVid);
}
} else {
ghostNodeHash.put(thisVid, thisVtx);
}
}
else if( (secondGetList.size() > 1) && depNodeOk && !dupeCheckOff ){
// Found some DUPLICATES - need to process them
LOGGER.info(" - now check Dupes for this guy - ");
List<String> tmpDupeGroups = checkAndProcessDupes(
TRANSID, FROMAPPID, g, source1, version,
nType, secondGetList, dupeFixOn,
deleteCandidateList, singleCommits, dupeGroups, loader);
Iterator<String> dIter = tmpDupeGroups.iterator();
while (dIter.hasNext()) {
// Add in any newly found dupes to our running list
String tmpGrp = dIter.next();
LOGGER.info("Found set of dupes: [" + tmpGrp + "]");
dupeGroups.add(tmpGrp);
}
}
}
catch (AAIException e1) {
LOGGER.warn(" For nodeType = " + nType + " Caught exception", e1);
errArr.add(e1.getErrorObject().toString());
}
catch (Exception e2) {
LOGGER.warn(" For nodeType = " + nType
+ " Caught exception", e2);
errArr.add(e2.getMessage());
}
}// try block to enclose looping of a single vertex
catch (Exception exx) {
LOGGER.warn("WARNING from inside the while-verts-loop ", exx);
}
} // while loop for each record of a nodeType
if ( (thisNtDeleteCount > 0) && singleCommits ) {
// NOTE - the singleCommits option is not used in normal processing
g.tx().commit();
g = AAIGraph.getInstance().getGraph().newTransaction();
}
thisNtDeleteCount = 0;
LOGGER.info( " Processed " + thisNtCount + " records for [" + nType + "], " + totalNodeCount + " total overall. " );
}// While-loop for each node type
}// end of check to make sure we weren't only supposed to do edges
if( !skipEdgeCheckFlag ){
// --------------------------------------------------------------------------------------
// Now, we're going to look for one-armed-edges. Ie. an edge that
// should have
// been deleted (because a vertex on one side was deleted) but
// somehow was not deleted.
// So the one end of it points to a vertexId -- but that vertex is
// empty.
// --------------------------------------------------------------------------------------
// To do some strange checking - we need a second graph object
LOGGER.debug(" ---- DEBUG --- about to open a SECOND graph (takes a little while)--------\n");
// Note - graph2 just reads - but we want it to use a fresh connection to
// the database, so we are NOT using the CACHED DB CONFIG here.
graph2 = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG);
if (graph2 == null) {
String emsg = "null graph2 object in DataGrooming\n";
throw new AAIException("AAI_6101", emsg);
} else {
LOGGER.debug("Got the graph2 object... \n");
}
g2 = graph2.newTransaction();
if (g2 == null) {
String emsg = "null graphTransaction2 object in DataGrooming\n";
throw new AAIException("AAI_6101", emsg);
}
ArrayList<Vertex> vertList = new ArrayList<>();
Iterator<Vertex> vItor3 = g.traversal().V();
// Gotta hold these in a List - or else HBase times out as you cycle
// through these
while (vItor3.hasNext()) {
Vertex v = vItor3.next();
vertList.add(v);
}
int counter = 0;
int lastShown = 0;
Iterator<Vertex> vItor2 = vertList.iterator();
LOGGER.info(" Checking for bad edges --- ");
while (vItor2.hasNext()) {
Vertex v = null;
try {
try {
v = vItor2.next();
} catch (Exception vex) {
LOGGER.warn(">>> WARNING trying to get next vertex on the vItor2 ");
continue;
}
counter++;
String thisVertId = "";
try {
thisVertId = v.id().toString();
} catch (Exception ev) {
LOGGER.warn("WARNING when doing getId() on a vertex from our vertex list. ");
continue;
}
if (ghostNodeHash.containsKey(thisVertId)) {
// This is a phantom node, so don't try to use it
LOGGER.info(" >> Skipping edge check for edges from vertexId = "
+ thisVertId
+ ", since that guy is a Phantom Node");
continue;
}
if( windowStartTime > 0 ){
// We only want to look at nodes that are created after a passed-in timestamp
Object objTimeStamp = v.property("aai-created-ts").orElse(null);
if( objTimeStamp != null ){
long thisNodeCreateTime = (long)objTimeStamp;
if( thisNodeCreateTime < windowStartTime ){
// It is NOT in our window, so we can pass over it
continue;
}
}
}
if (counter == lastShown + 250) {
lastShown = counter;
LOGGER.info("... Checking edges for vertex # "
+ counter);
}
Iterator<Edge> eItor = v.edges(Direction.BOTH);
while (eItor.hasNext()) {
Edge e = null;
Vertex vIn = null;
Vertex vOut = null;
try {
e = eItor.next();
} catch (Exception iex) {
LOGGER.warn(">>> WARNING trying to get next edge on the eItor ", iex);
continue;
}
try {
vIn = e.inVertex();
} catch (Exception err) {
LOGGER.warn(">>> WARNING trying to get edge's In-vertex ", err);
}
String vNtI = "";
String vIdI = "";
Vertex ghost2 = null;
Boolean keysMissing = true;
Boolean cantGetUsingVid = false;
if (vIn != null) {
try {
Object ob = vIn.<Object>property("aai-node-type").orElse(null);
if (ob != null) {
vNtI = ob.toString();
keysMissing = anyKeyFieldsMissing(vNtI, vIn, loader);
}
ob = vIn.id();
long vIdLong = 0L;
if (ob != null) {
vIdI = ob.toString();
vIdLong = Long.parseLong(vIdI);
}
if( ! ghost2CheckOff ){
Vertex connectedVert = g2.traversal().V(vIdLong).next();
if( connectedVert == null ) {
LOGGER.warn( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong);
cantGetUsingVid = true;
// If we can NOT get this ghost with the SECOND graph-object,
// it is still a ghost since even though we can get data about it using the FIRST graph
// object.
try {
ghost2 = g.traversal().V(vIdLong).next();
}
catch( Exception ex){
LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex);
}
if( ghost2 != null ){
ghostNodeHash.put(vIdI, ghost2);
}
}
}// end of the ghost2 checking
}
catch (Exception err) {
LOGGER.warn(">>> WARNING trying to get edge's In-vertex props ", err);
}
}
if (keysMissing || vIn == null || vNtI.equals("")
|| cantGetUsingVid) {
// this is a bad edge because it points to a vertex
// that isn't there anymore or is corrupted
String thisEid = e.id().toString();
if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdI)) {
boolean okFlag = true;
if (!vIdI.equals("")) {
// try to get rid of the corrupted vertex
try {
if( (ghost2 != null) && ghost2FixOn ){
ghost2.remove();
}
else {
vIn.remove();
}
if (singleCommits) {
// NOTE - the singleCommits option is not used in normal processing
g.tx().commit();
g = AAIGraph.getInstance().getGraph().newTransaction();
}
deleteCount++;
} catch (Exception e1) {
okFlag = false;
LOGGER.warn("WARNING when trying to delete bad-edge-connected VERTEX VID = "
+ vIdI, e1);
}
if (okFlag) {
LOGGER.info(" DELETED vertex from bad edge = "
+ vIdI);
}
} else {
// remove the edge if we couldn't get the
// vertex
try {
e.remove();
if (singleCommits) {
// NOTE - the singleCommits option is not used in normal processing
g.tx().commit();
g = AAIGraph.getInstance().getGraph().newTransaction();
}
deleteCount++;
} catch (Exception ex) {
// NOTE - often, the exception is just
// that this edge has already been
// removed
okFlag = false;
LOGGER.warn("WARNING when trying to delete edge = "
+ thisEid);
}
if (okFlag) {
LOGGER.info(" DELETED edge = " + thisEid);
}
}
} else {
oneArmedEdgeHash.put(thisEid, e);
if ((vIn != null) && (vIn.id() != null)) {
emptyVertexHash.put(thisEid, vIn.id()
.toString());
}
}
}
try {
vOut = e.outVertex();
} catch (Exception err) {
LOGGER.warn(">>> WARNING trying to get edge's Out-vertex ");
}
String vNtO = "";
String vIdO = "";
ghost2 = null;
keysMissing = true;
cantGetUsingVid = false;
if (vOut != null) {
try {
Object ob = vOut.<Object>property("aai-node-type").orElse(null);
if (ob != null) {
vNtO = ob.toString();
keysMissing = anyKeyFieldsMissing(vNtO,
vOut, loader);
}
ob = vOut.id();
long vIdLong = 0L;
if (ob != null) {
vIdO = ob.toString();
vIdLong = Long.parseLong(vIdO);
}
if( ! ghost2CheckOff ){
Vertex connectedVert = g2.traversal().V(vIdLong).next();
if( connectedVert == null ) {
cantGetUsingVid = true;
LOGGER.info( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong);
// If we can get this ghost with the other graph-object, then get it -- it's still a ghost
try {
ghost2 = g.traversal().V(vIdLong).next();
}
catch( Exception ex){
LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex);
}
if( ghost2 != null ){
ghostNodeHash.put(vIdO, ghost2);
}
}
}
} catch (Exception err) {
LOGGER.warn(">>> WARNING trying to get edge's Out-vertex props ", err);
}
}
if (keysMissing || vOut == null || vNtO.equals("")
|| cantGetUsingVid) {
// this is a bad edge because it points to a vertex
// that isn't there anymore
String thisEid = e.id().toString();
if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdO)) {
boolean okFlag = true;
if (!vIdO.equals("")) {
// try to get rid of the corrupted vertex
try {
if( (ghost2 != null) && ghost2FixOn ){
ghost2.remove();
}
else {
vOut.remove();
}
if (singleCommits) {
// NOTE - the singleCommits option is not used in normal processing
g.tx().commit();
g = AAIGraph.getInstance().getGraph().newTransaction();
}
deleteCount++;
} catch (Exception e1) {
okFlag = false;
LOGGER.warn("WARNING when trying to delete bad-edge-connected VID = "
+ vIdO, e1);
}
if (okFlag) {
LOGGER.info(" DELETED vertex from bad edge = "
+ vIdO);
}
} else {
// remove the edge if we couldn't get the
// vertex
try {
e.remove();
if (singleCommits) {
// NOTE - the singleCommits option is not used in normal processing
g.tx().commit();
g = AAIGraph.getInstance().getGraph().newTransaction();
}
deleteCount++;
} catch (Exception ex) {
// NOTE - often, the exception is just
// that this edge has already been
// removed
okFlag = false;
LOGGER.warn("WARNING when trying to delete edge = "
+ thisEid, ex);
}
if (okFlag) {
LOGGER.info(" DELETED edge = " + thisEid);
}
}
} else {
oneArmedEdgeHash.put(thisEid, e);
if ((vOut != null) && (vOut.id() != null)) {
emptyVertexHash.put(thisEid, vOut.id()
.toString());
}
}
}
}// End of while-edges-loop
} catch (Exception exx) {
LOGGER.warn("WARNING from in the while-verts-loop ", exx);
}
}// End of while-vertices-loop (the edge-checking)
} // end of -- if we're not skipping the edge-checking
deleteCount = deleteCount + dupeGrpsDeleted;
if (!singleCommits && deleteCount > 0) {
try {
LOGGER.info("About to do the commit for "
+ deleteCount + " removes. ");
executeFinalCommit = true;
LOGGER.info("Commit was successful ");
} catch (Exception excom) {
LOGGER.error(" >>>> ERROR <<<< Could not commit changes. ", excom);
deleteCount = 0;
}
}
int ghostNodeCount = ghostNodeHash.size();
int orphanNodeCount = orphanNodeHash.size();
int missingDepNodeCount = missingDepNodeHash.size();
int oneArmedEdgeCount = oneArmedEdgeHash.size();
int dupeCount = dupeGroups.size();
deleteCount = deleteCount + dupeGrpsDeleted;
bw.write("\n\n ============ Summary ==============\n");
bw.write("Ran these nodeTypes: " + ntList + "\n\n");
bw.write("There were this many delete candidates from previous run = "
+ deleteCandidateList.size() + "\n");
if (dontFixOrphansFlag) {
bw.write(" Note - we are not counting orphan nodes since the -dontFixOrphans parameter was used. \n");
}
bw.write("Deleted this many delete candidates = " + deleteCount
+ "\n");
bw.write("Total number of nodes looked at = " + totalNodeCount
+ "\n");
bw.write("Ghost Nodes identified = " + ghostNodeCount + "\n");
bw.write("Orphan Nodes identified = " + orphanNodeCount + "\n");
bw.write("Bad Edges identified = " + oneArmedEdgeCount + "\n");
bw.write("Missing Dependent Edge (but not orphaned) node count = "
+ missingDepNodeCount + "\n");
bw.write("Duplicate Groups count = " + dupeCount + "\n");
bw.write("MisMatching Label/aai-node-type count = "
+ misMatchedHash.size() + "\n");
bw.write("\n ------------- Delete Candidates ---------\n");
for (Map.Entry<String, Vertex> entry : ghostNodeHash
.entrySet()) {
String vid = entry.getKey();
bw.write("DeleteCandidate: Phantom Vid = [" + vid + "]\n");
cleanupCandidateCount++;
}
for (Map.Entry<String, Vertex> entry : orphanNodeHash
.entrySet()) {
String vid = entry.getKey();
bw.write("DeleteCandidate: OrphanDepNode Vid = [" + vid + "]\n");
if (!dontFixOrphansFlag) {
cleanupCandidateCount++;
}
}
for (Map.Entry<String, Edge> entry : oneArmedEdgeHash.entrySet()) {
String eid = entry.getKey();
bw.write("DeleteCandidate: Bad EDGE Edge-id = [" + eid + "]\n");
cleanupCandidateCount++;
}
for (Map.Entry<String, Vertex> entry : missingDepNodeHash
.entrySet()) {
String vid = entry.getKey();
bw.write("DeleteCandidate: (maybe) missingDepNode Vid = ["
+ vid + "]\n");
cleanupCandidateCount++;
}
bw.write("\n-- NOTE - To see DeleteCandidates for Duplicates, you need to look in the Duplicates Detail section below.\n");
bw.write("\n ------------- GHOST NODES - detail ");
for (Map.Entry<String, Vertex> entry : ghostNodeHash
.entrySet()) {
try {
String vid = entry.getKey();
bw.write("\n ==> Phantom Vid = " + vid + "\n");
ArrayList<String> retArr = showPropertiesForNode(
TRANSID, FROMAPPID, entry.getValue());
for (String info : retArr) {
bw.write(info + "\n");
}
retArr = showAllEdgesForNode(TRANSID, FROMAPPID,
entry.getValue());
for (String info : retArr) {
bw.write(info + "\n");
}
} catch (Exception dex) {
LOGGER.error("error trying to print detail info for a ghost-node: ", dex);
}
}
bw.write("\n ------------- Missing Dependent Edge ORPHAN NODES - detail: ");
for (Map.Entry<String, Vertex> entry : orphanNodeHash
.entrySet()) {
try {
String vid = entry.getKey();
bw.write("\n> Orphan Node Vid = " + vid + "\n");
ArrayList<String> retArr = showPropertiesForNode(
TRANSID, FROMAPPID, entry.getValue());
for (String info : retArr) {
bw.write(info + "\n");
}
retArr = showAllEdgesForNode(TRANSID, FROMAPPID,
entry.getValue());
for (String info : retArr) {
bw.write(info + "\n");
}
} catch (Exception dex) {
LOGGER.error("error trying to print detail info for a Orphan Node /missing dependent edge", dex);
}
}
bw.write("\n ------------- Missing Dependent Edge (but not orphan) NODES: ");
for (Map.Entry<String, Vertex> entry : missingDepNodeHash
.entrySet()) {
try {
String vid = entry.getKey();
bw.write("\n> Missing edge to Dependent Node (but has edges) Vid = "
+ vid + "\n");
ArrayList<String> retArr = showPropertiesForNode(
TRANSID, FROMAPPID, entry.getValue());
for (String info : retArr) {
bw.write(info + "\n");
}
retArr = showAllEdgesForNode(TRANSID, FROMAPPID,
entry.getValue());
for (String info : retArr) {
bw.write(info + "\n");
}
} catch (Exception dex) {
LOGGER.error("error trying to print detail info for a node missing its dependent edge but not an orphan", dex);
}
}
bw.write("\n ------------- EDGES pointing to empty/bad vertices: ");
for (Map.Entry<String, Edge> entry : oneArmedEdgeHash.entrySet()) {
try {
String eid = entry.getKey();
Edge thisE = entry.getValue();
String badVid = emptyVertexHash.get(eid);
bw.write("\n> Edge pointing to bad vertex (Vid = "
+ badVid + ") EdgeId = " + eid + "\n");
bw.write("Label: [" + thisE.label() + "]\n");
Iterator<Property<Object>> pI = thisE.properties();
while (pI.hasNext()) {
Property<Object> propKey = pI.next();
bw.write("Prop: [" + propKey + "], val = ["
+ propKey.value() + "]\n");
}
} catch (Exception pex) {
LOGGER.error("error trying to print empty/bad vertex data: ", pex);
}
}
bw.write("\n ------------- Duplicates: ");
Iterator<String> dupeIter = dupeGroups.iterator();
int dupeSetCounter = 0;
while (dupeIter.hasNext()) {
dupeSetCounter++;
String dset = (String) dupeIter.next();
bw.write("\n --- Duplicate Group # " + dupeSetCounter
+ " Detail -----------\n");
try {
// We expect each line to have at least two vid's, followed
// by the preferred one to KEEP
String[] dupeArr = dset.split("\\|");
ArrayList<String> idArr = new ArrayList<>();
int lastIndex = dupeArr.length - 1;
for (int i = 0; i <= lastIndex; i++) {
if (i < lastIndex) {
// This is not the last entry, it is one of the
// dupes, so we want to show all its info
bw.write(" >> Duplicate Group # "
+ dupeSetCounter + " Node # " + i
+ " ----\n");
String vidString = dupeArr[i];
idArr.add(vidString);
long longVertId = Long.parseLong(vidString);
Iterator<Vertex> vtxIterator = g.vertices(longVertId);
Vertex vtx = null;
if (vtxIterator.hasNext()) {
vtx = vtxIterator.next();
}
ArrayList<String> retArr = showPropertiesForNode(TRANSID, FROMAPPID, vtx);
for (String info : retArr) {
bw.write(info + "\n");
}
retArr = showAllEdgesForNode(TRANSID,
FROMAPPID, vtx);
for (String info : retArr) {
bw.write(info + "\n");
}
} else {
// This is the last entry which should tell us if we
// have a preferred keeper
String prefString = dupeArr[i];
if (prefString.equals("KeepVid=UNDETERMINED")) {
bw.write("\n For this group of duplicates, could not tell which one to keep.\n");
bw.write(" >>> This group needs to be taken care of with a manual/forced-delete.\n");
} else {
// If we know which to keep, then the prefString
// should look like, "KeepVid=12345"
String[] prefArr = prefString.split("=");
if (prefArr.length != 2
|| (!prefArr[0].equals("KeepVid"))) {
throw new Exception("Bad format. Expecting KeepVid=999999");
} else {
String keepVidStr = prefArr[1];
if (idArr.contains(keepVidStr)) {
bw.write("\n The vertex we want to KEEP has vertexId = "
+ keepVidStr);
bw.write("\n The others become delete candidates: \n");
idArr.remove(keepVidStr);
for (int x = 0; x < idArr.size(); x++) {
cleanupCandidateCount++;
bw.write("DeleteCandidate: Duplicate Vid = ["
+ idArr.get(x) + "]\n");
}
} else {
throw new Exception("ERROR - Vertex Id to keep not found in list of dupes. dset = ["
+ dset + "]");
}
}
}// else we know which one to keep
}// else last entry
}// for each vertex in a group
} catch (Exception dex) {
LOGGER.error("error trying to print duplicate vertex data", dex);
}
}// while - work on each group of dupes
bw.write("\n ------------- Mis-matched Label/aai-node-type Nodes: \n ");
for (Map.Entry<String, String> entry : misMatchedHash.entrySet()) {
String msg = entry.getValue();
bw.write("MixedMsg = " + msg + "\n");
}
bw.write("\n ------------- Got these errors while processing: \n");
Iterator<String> errIter = errArr.iterator();
while (errIter.hasNext()) {
String line = (String) errIter.next();
bw.write(line + "\n");
}
bw.close();
LOGGER.info("\n ------------- Done doing all the checks ------------ ");
LOGGER.info("Output will be written to " + fullOutputFileName);
if (cleanupCandidateCount > 0) {
// Technically, this is not an error -- but we're throwing this
// error so that hopefully a
// monitoring system will pick it up and do something with it.
throw new AAIException("AAI_6123", "See file: [" + fullOutputFileName
+ "] and investigate delete candidates. ");
}
} catch (AAIException e) {
LOGGER.error("Caught AAIException while grooming data", e);
ErrorLogHelper.logException(e);
} catch (Exception ex) {
LOGGER.error("Caught exception while grooming data", ex);
ErrorLogHelper.logError("AAI_6128", ex.getMessage() + ", resolve and rerun dataGrooming");
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException iox) {
LOGGER.warn("Got an IOException trying to close bufferedWriter() \n", iox);
}
}
if (g != null && g.tx().isOpen()) {
// Any changes that worked correctly should have already done
// their commits.
try {
if (executeFinalCommit) {
g.tx().commit();
}
g.tx().rollback();
} catch (Exception ex) {
// Don't throw anything because Titan sometimes is just saying that the graph is already closed
LOGGER.warn("WARNING from final graphTransaction.rollback()", ex);
}
}
if (g2 != null && g2.tx().isOpen()) {
// Any changes that worked correctly should have already done
// their commits.
try {
g2.tx().rollback();
} catch (Exception ex) {
// Don't throw anything because Titan sometimes is just saying that the graph is already closed
LOGGER.warn("WARNING from final graphTransaction2.rollback()", ex);
}
}
if( finalShutdownFlag ){
try {
if( graph != null && graph.isOpen() ){
graph.tx().close();
graph.close();
}
} catch (Exception ex) {
// Don't throw anything because Titan sometimes is just saying that the graph is already closed{
LOGGER.warn("WARNING from final graph.shutdown()", ex);
}
try {
if( graph2 != null && graph2.isOpen() ){
graph2.tx().close();
graph2.close();
}
} catch (Exception ex) {
// Don't throw anything because Titan sometimes is just saying that the graph is already closed{
LOGGER.warn("WARNING from final graph2.shutdown()", ex);
}
}
}
return cleanupCandidateCount;
}// end of doTheGrooming()
/**
* Vertex has these keys.
*
* @param tmpV the tmp V
* @param propHashWithKeys the prop hash with keys
* @return the boolean
*/
private static Boolean vertexHasTheseKeys( Vertex tmpV, HashMap <String, Object> propHashWithKeys) {
Iterator <?> it = propHashWithKeys.entrySet().iterator();
while( it.hasNext() ){
String propName = "";
String propVal = "";
Map.Entry <?,?>propEntry = (Map.Entry<?,?>)it.next();
Object propNameObj = propEntry.getKey();
if( propNameObj != null ){
propName = propNameObj.toString();
}
Object propValObj = propEntry.getValue();
if( propValObj != null ){
propVal = propValObj.toString();
}
Object checkValObj = tmpV.<Object>property(propName).orElse(null);
if( checkValObj == null ) {
return false;
}
else if( !propVal.equals(checkValObj.toString()) ){
return false;
}
}
return true;
}
/**
* Any key fields missing.
*
* @param nType the n type
* @param v the v
* @return the boolean
*/
private static Boolean anyKeyFieldsMissing(String nType, Vertex v, Loader loader) {
try {
Introspector obj = null;
try {
obj = loader.introspectorFromName(nType);
} catch (AAIUnknownObjectException e) {
// They gave us a non-empty nodeType but our NodeKeyProps does
// not have data for it. Since we do not know what the
// key params are for this type of node, we will just
// return "false".
String emsg = " -- WARNING -- Unrecognized nodeType: [" + nType
+ "]. We cannot determine required keys for this nType. ";
// NOTE - this will be caught below and a "false" returned
throw new AAIException("AAI_6121", emsg);
}
// Determine what the key fields are for this nodeType
Collection <String> keyPropNamesColl = obj.getKeys();
Iterator<String> keyPropI = keyPropNamesColl.iterator();
while (keyPropI.hasNext()) {
String propName = keyPropI.next();
Object ob = v.<Object>property(propName).orElse(null);
if (ob == null || ob.toString().equals("")) {
// It is missing a key property
return true;
}
}
} catch (AAIException e) {
// Something was wrong -- but since we weren't able to check
// the keys, we will not declare that it is missing keys.
return false;
}
return false;
}
/**
* Gets the delete list.
*
* @param targetDir the target dir
* @param fileName the file name
* @param edgesOnlyFlag the edges only flag
* @param dontFixOrphans the dont fix orphans
* @param dupeFixOn the dupe fix on
* @return the delete list
* @throws AAIException the AAI exception
*/
private static Set<String> getDeleteList(String targetDir,
String fileName, Boolean edgesOnlyFlag, Boolean dontFixOrphans,
Boolean dupeFixOn) throws AAIException {
// Look in the file for lines formated like we expect - pull out any
// Vertex Id's to delete on this run
Set<String> delList = new LinkedHashSet<>();
String fullFileName = targetDir + AAIConstants.AAI_FILESEP + fileName;
try(BufferedReader br = new BufferedReader(new FileReader(fullFileName))) {
String line = br.readLine();
while (line != null) {
if (!"".equals(line) && line.startsWith("DeleteCandidate")) {
if (edgesOnlyFlag && (!line.contains("Bad Edge"))) {
// We're not going to process edge guys
} else if (dontFixOrphans && line.contains("Orphan")) {
// We're not going to process orphans
} else if (!dupeFixOn && line.contains("Duplicate")) {
// We're not going to process Duplicates
} else {
int begIndex = line.indexOf("id = ");
int endIndex = line.indexOf("]");
String vidVal = line.substring(begIndex + 6, endIndex);
delList.add(vidVal);
}
}
line = br.readLine();
}
br.close();
} catch (IOException e) {
throw new AAIException("AAI_6124", e, "Could not open input-file [" + fullFileName
+ "], exception= " + e.getMessage());
}
return delList;
}// end of getDeleteList
/**
* Gets the preferred dupe.
*
* @param transId the trans id
* @param fromAppId the from app id
* @param g the g
* @param dupeVertexList the dupe vertex list
* @param ver the ver
* @return Vertex
* @throws AAIException the AAI exception
*/
public static Vertex getPreferredDupe(String transId,
String fromAppId, GraphTraversalSource g,
ArrayList<Vertex> dupeVertexList, String ver, Loader loader)
throws AAIException {
// This method assumes that it is being passed a List of vertex objects
// which
// violate our uniqueness constraints.
Vertex nullVtx = null;
if (dupeVertexList == null) {
return nullVtx;
}
int listSize = dupeVertexList.size();
if (listSize == 0) {
return nullVtx;
}
if (listSize == 1) {
return (dupeVertexList.get(0));
}
Vertex vtxPreferred = null;
Vertex currentFaveVtx = dupeVertexList.get(0);
for (int i = 1; i < listSize; i++) {
Vertex vtxB = dupeVertexList.get(i);
vtxPreferred = pickOneOfTwoDupes(transId, fromAppId, g,
currentFaveVtx, vtxB, ver, loader);
if (vtxPreferred == null) {
// We couldn't choose one
return nullVtx;
} else {
currentFaveVtx = vtxPreferred;
}
}
return (currentFaveVtx);
} // end of getPreferredDupe()
/**
* Pick one of two dupes.
*
* @param transId the trans id
* @param fromAppId the from app id
* @param g the g
* @param vtxA the vtx A
* @param vtxB the vtx B
* @param ver the ver
* @return Vertex
* @throws AAIException the AAI exception
*/
public static Vertex pickOneOfTwoDupes(String transId,
String fromAppId, GraphTraversalSource g, Vertex vtxA,
Vertex vtxB, String ver, Loader loader) throws AAIException {
Vertex nullVtx = null;
Vertex preferredVtx = null;
Long vidA = new Long(vtxA.id().toString());
Long vidB = new Long(vtxB.id().toString());
String vtxANodeType = "";
String vtxBNodeType = "";
Object objType = vtxA.<Object>property("aai-node-type").orElse(null);
if (objType != null) {
vtxANodeType = objType.toString();
}
objType = vtxB.<Object>property("aai-node-type").orElse(null);
if (objType != null) {
vtxBNodeType = objType.toString();
}
if (vtxANodeType.equals("") || (!vtxANodeType.equals(vtxBNodeType))) {
// Either they're not really dupes or there's some bad data - so
// don't pick one
return nullVtx;
}
// Check that node A and B both have the same key values (or else they
// are not dupes)
// (We'll check dep-node later)
// Determine what the key fields are for this nodeType
Collection <String> keyProps = new ArrayList <>();
try {
keyProps = loader.introspectorFromName(vtxANodeType).getKeys();
} catch (AAIUnknownObjectException e) {
LOGGER.warn("Required property not found", e);
throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + vtxANodeType + ")");
}
Iterator<String> keyPropI = keyProps.iterator();
while (keyPropI.hasNext()) {
String propName = keyPropI.next();
String vtxAKeyPropVal = "";
objType = vtxA.<Object>property(propName).orElse(null);
if (objType != null) {
vtxAKeyPropVal = objType.toString();
}
String vtxBKeyPropVal = "";
objType = vtxB.<Object>property(propName).orElse(null);
if (objType != null) {
vtxBKeyPropVal = objType.toString();
}
if (vtxAKeyPropVal.equals("")
|| (!vtxAKeyPropVal.equals(vtxBKeyPropVal))) {
// Either they're not really dupes or they are missing some key
// data - so don't pick one
return nullVtx;
}
}
// Collect the vid's and aai-node-types of the vertices that each vertex
// (A and B) is connected to.
ArrayList<String> vtxIdsConn2A = new ArrayList<>();
ArrayList<String> vtxIdsConn2B = new ArrayList<>();
HashMap<String, String> nodeTypesConn2A = new HashMap<>();
HashMap<String, String> nodeTypesConn2B = new HashMap<>();
ArrayList<Vertex> vertListA = getConnectedNodes( g, vtxA );
if (vertListA != null) {
Iterator<Vertex> iter = vertListA.iterator();
while (iter.hasNext()) {
Vertex tvCon = iter.next();
String conVid = tvCon.id().toString();
String nt = "";
objType = tvCon.<Object>property("aai-node-type").orElse(null);
if (objType != null) {
nt = objType.toString();
}
nodeTypesConn2A.put(nt, conVid);
vtxIdsConn2A.add(conVid);
}
}
ArrayList<Vertex> vertListB = getConnectedNodes( g, vtxB );
if (vertListB != null) {
Iterator<Vertex> iter = vertListB.iterator();
while (iter.hasNext()) {
Vertex tvCon = iter.next();
String conVid = tvCon.id().toString();
String nt = "";
objType = tvCon.<Object>property("aai-node-type").orElse(null);
if (objType != null) {
nt = objType.toString();
}
nodeTypesConn2B.put(nt, conVid);
vtxIdsConn2B.add(conVid);
}
}
// 1 - If this kind of node needs a dependent node for uniqueness, then
// verify that they both nodes
// point to the same dependent node (otherwise they're not really
// duplicates)
// Note - there are sometimes more than one dependent node type since
// one nodeType can be used in
// different ways. But for a particular node, it will only have one
// dependent node that it's
// connected to.
Collection <String> depNodeTypes = loader.introspectorFromName(vtxANodeType).getDependentOn();
if (depNodeTypes.isEmpty()) {
// This kind of node is not dependent on any other. That is ok.
} else {
String depNodeVtxId4A = "";
String depNodeVtxId4B = "";
Iterator<String> iter = depNodeTypes.iterator();
while (iter.hasNext()) {
String depNodeType = iter.next();
if (nodeTypesConn2A.containsKey(depNodeType)) {
// This is the dependent node type that vertex A is using
depNodeVtxId4A = nodeTypesConn2A.get(depNodeType);
}
if (nodeTypesConn2B.containsKey(depNodeType)) {
// This is the dependent node type that vertex B is using
depNodeVtxId4B = nodeTypesConn2B.get(depNodeType);
}
}
if (depNodeVtxId4A.equals("")
|| (!depNodeVtxId4A.equals(depNodeVtxId4B))) {
// Either they're not really dupes or there's some bad data - so
// don't pick either one
return nullVtx;
}
}
if (vtxIdsConn2A.size() == vtxIdsConn2B.size()) {
// 2 - If they both have edges to all the same vertices, then return
// the one with the lower vertexId.
boolean allTheSame = true;
Iterator<String> iter = vtxIdsConn2A.iterator();
while (iter.hasNext()) {
String vtxIdConn2A = iter.next();
if (!vtxIdsConn2B.contains(vtxIdConn2A)) {
allTheSame = false;
break;
}
}
if (allTheSame) {
if (vidA < vidB) {
preferredVtx = vtxA;
} else {
preferredVtx = vtxB;
}
}
} else if (vtxIdsConn2A.size() > vtxIdsConn2B.size()) {
// 3 - VertexA is connected to more things than vtxB.
// We'll pick VtxA if its edges are a superset of vtxB's edges.
boolean missingOne = false;
Iterator<String> iter = vtxIdsConn2B.iterator();
while (iter.hasNext()) {
String vtxIdConn2B = iter.next();
if (!vtxIdsConn2A.contains(vtxIdConn2B)) {
missingOne = true;
break;
}
}
if (!missingOne) {
preferredVtx = vtxA;
}
} else if (vtxIdsConn2B.size() > vtxIdsConn2A.size()) {
// 4 - VertexB is connected to more things than vtxA.
// We'll pick VtxB if its edges are a superset of vtxA's edges.
boolean missingOne = false;
Iterator<String> iter = vtxIdsConn2A.iterator();
while (iter.hasNext()) {
String vtxIdConn2A = iter.next();
if (!vtxIdsConn2B.contains(vtxIdConn2A)) {
missingOne = true;
break;
}
}
if (!missingOne) {
preferredVtx = vtxB;
}
} else {
preferredVtx = nullVtx;
}
return (preferredVtx);
} // end of pickOneOfTwoDupes()
/**
* Check and process dupes.
*
* @param transId the trans id
* @param fromAppId the from app id
* @param g the g
* @param version the version
* @param nType the n type
* @param passedVertList the passed vert list
* @param dupeFixOn the dupe fix on
* @param deleteCandidateList the delete candidate list
* @param singleCommits the single commits
* @param alreadyFoundDupeGroups the already found dupe groups
* @param dbMaps the db maps
* @return the array list
*/
private static List<String> checkAndProcessDupes(String transId,
String fromAppId, Graph g, GraphTraversalSource source, String version, String nType,
List<Vertex> passedVertList, Boolean dupeFixOn,
Set<String> deleteCandidateList, Boolean singleCommits,
ArrayList<String> alreadyFoundDupeGroups, Loader loader ) {
ArrayList<String> returnList = new ArrayList<>();
ArrayList<Vertex> checkVertList = new ArrayList<>();
ArrayList<String> alreadyFoundDupeVidArr = new ArrayList<>();
Boolean noFilterList = true;
Iterator<String> afItr = alreadyFoundDupeGroups.iterator();
while (afItr.hasNext()) {
String dupeGrpStr = afItr.next();
String[] dupeArr = dupeGrpStr.split("\\|");
int lastIndex = dupeArr.length - 1;
for (int i = 0; i < lastIndex; i++) {
// Note: we don't want the last one...
String vidString = dupeArr[i];
alreadyFoundDupeVidArr.add(vidString);
noFilterList = false;
}
}
// For a given set of Nodes that were found with a set of KEY
// Parameters, (nodeType + key data) we will
// see if we find any duplicate nodes that need to be cleaned up. Note -
// it's legit to have more than one
// node with the same key data if the nodes depend on a parent for
// uniqueness -- as long as the two nodes
// don't hang off the same Parent.
// If we find duplicates, and we can figure out which of each set of
// duplicates is the one that we
// think should be preserved, we will record that. Whether we can tell
// which one should be
// preserved or not, we will return info about any sets of duplicates
// found.
//
// Each element in the returned arrayList might look like this:
// "1234|5678|keepVid=UNDETERMINED" (if there were 2 dupes, and we
// couldn't figure out which one to keep)
// or, "100017|200027|30037|keepVid=30037" (if there were 3 dupes and we
// thought the third one was the one that should survive)
// Because of the way the calling code loops over stuff, we can get the
// same data multiple times - so we should
// not process any vertices that we've already seen.
try {
Iterator<Vertex> pItr = passedVertList.iterator();
while (pItr.hasNext()) {
Vertex tvx = pItr.next();
String passedId = tvx.id().toString();
if (noFilterList || !alreadyFoundDupeVidArr.contains(passedId)) {
// We haven't seen this one before - so we should check it.
checkVertList.add(tvx);
}
}
if (checkVertList.size() < 2) {
// Nothing new to check.
return returnList;
}
if (loader.introspectorFromName(nType).isTopLevel()) {
// If this was a node that does NOT depend on other nodes for
// uniqueness, and we
// found more than one node using its key -- record the found
// vertices as duplicates.
String dupesStr = "";
for (int i = 0; i < checkVertList.size(); i++) {
dupesStr = dupesStr
+ ((checkVertList.get(i))).id()
.toString() + "|";
}
if (dupesStr != "") {
Vertex prefV = getPreferredDupe(transId, fromAppId,
source, checkVertList, version, loader);
if (prefV == null) {
// We could not determine which duplicate to keep
dupesStr = dupesStr + "KeepVid=UNDETERMINED";
returnList.add(dupesStr);
} else {
dupesStr = dupesStr + "KeepVid=" + prefV.id();
Boolean didRemove = false;
if (dupeFixOn) {
didRemove = deleteNonKeepersIfAppropriate(g,
dupesStr, prefV.id().toString(),
deleteCandidateList, singleCommits);
}
if (didRemove) {
dupeGrpsDeleted++;
} else {
// keep them on our list
returnList.add(dupesStr);
}
}
}
} else {
// More than one node have the same key fields since they may
// depend on a parent node for uniqueness. Since we're finding
// more than one, we want to check to see if any of the
// vertices that have this set of keys (and are the same nodeType)
// are also pointing at the same 'parent' node.
// Note: for a given set of key data, it is possible that there
// could be more than one set of duplicates.
HashMap<String, ArrayList<Vertex>> vertsGroupedByParentHash = groupVertsByDepNodes(
transId, fromAppId, source, version, nType,
checkVertList, loader);
for (Map.Entry<String, ArrayList<Vertex>> entry : vertsGroupedByParentHash
.entrySet()) {
ArrayList<Vertex> thisParentsVertList = entry
.getValue();
if (thisParentsVertList.size() > 1) {
// More than one vertex found with the same key info
// hanging off the same parent/dependent node
String dupesStr = "";
for (int i = 0; i < thisParentsVertList.size(); i++) {
dupesStr = dupesStr
+ ((thisParentsVertList
.get(i))).id() + "|";
}
if (dupesStr != "") {
Vertex prefV = getPreferredDupe(transId,
fromAppId, source, thisParentsVertList,
version, loader);
if (prefV == null) {
// We could not determine which duplicate to
// keep
dupesStr = dupesStr + "KeepVid=UNDETERMINED";
returnList.add(dupesStr);
} else {
Boolean didRemove = false;
dupesStr = dupesStr + "KeepVid="
+ prefV.id().toString();
if (dupeFixOn) {
didRemove = deleteNonKeepersIfAppropriate(
g, dupesStr, prefV.id()
.toString(),
deleteCandidateList, singleCommits);
}
if (didRemove) {
dupeGrpsDeleted++;
} else {
// keep them on our list
returnList.add(dupesStr);
}
}
}
}
}
}
} catch (Exception e) {
LOGGER.warn(" >>> Threw an error in checkAndProcessDupes - just absorb this error and move on. ", e);
}
return returnList;
}// End of checkAndProcessDupes()
/**
* Group verts by dep nodes.
*
* @param transId the trans id
* @param fromAppId the from app id
* @param g the g
* @param version the version
* @param nType the n type
* @param passedVertList the passed vert list
* @param dbMaps the db maps
* @return the hash map
* @throws AAIException the AAI exception
*/
private static HashMap<String, ArrayList<Vertex>> groupVertsByDepNodes(
String transId, String fromAppId, GraphTraversalSource g, String version,
String nType, ArrayList<Vertex> passedVertList, Loader loader)
throws AAIException {
// Given a list of Titan Vertices of one nodeType (see AAI-8956), group
// them together by the parent node they depend on.
// Ie. if given a list of ip address nodes (assumed to all have the
// same key info) they might sit under several different parent vertices.
// Under Normal conditions, there would only be one per parent -- but
// we're trying to find duplicates - so we
// allow for the case where more than one is under the same parent node.
HashMap<String, ArrayList<Vertex>> retHash = new HashMap<String, ArrayList<Vertex>>();
if (loader.introspectorFromName(nType).isTopLevel()) {
// This method really should not have been called if this is not the
// kind of node
// that depends on a parent for uniqueness, so just return the empty
// hash.
return retHash;
}
// Find out what types of nodes the passed in nodes can depend on
ArrayList<String> depNodeTypeL = new ArrayList<>();
Collection<String> depNTColl = loader.introspectorFromName(nType).getDependentOn();
Iterator<String> ntItr = depNTColl.iterator();
while (ntItr.hasNext()) {
depNodeTypeL.add(ntItr.next());
}
// For each vertex, we want find its depended-on/parent vertex so we
// can track what other vertexes that are dependent on that same guy.
if (passedVertList != null) {
Iterator<Vertex> iter = passedVertList.iterator();
while (iter.hasNext()) {
Vertex thisVert = iter.next();
Vertex tmpParentVtx = getConnectedParent( g, thisVert );
if( tmpParentVtx != null ) {
String parentNt = null;
Object obj = tmpParentVtx.<Object>property("aai-node-type").orElse(null);
if (obj != null) {
parentNt = obj.toString();
}
if (depNTColl.contains(parentNt)) {
// This must be the parent/dependent node
String parentVid = tmpParentVtx.id().toString();
if (retHash.containsKey(parentVid)) {
// add this vert to the list for this parent key
retHash.get(parentVid).add(thisVert);
} else {
// This is the first one we found on this parent
ArrayList<Vertex> vList = new ArrayList<>();
vList.add(thisVert);
retHash.put(parentVid, vList);
}
}
}
}
}
return retHash;
}// end of groupVertsByDepNodes()
/**
* Delete non keepers if appropriate.
*
* @param g the g
* @param dupeInfoString the dupe info string
* @param vidToKeep the vid to keep
* @param deleteCandidateList the delete candidate list
* @param singleCommits the single commits
* @return the boolean
*/
private static Boolean deleteNonKeepersIfAppropriate(Graph g,
String dupeInfoString, String vidToKeep,
Set<String> deleteCandidateList, Boolean singleCommits) {
Boolean deletedSomething = false;
// This assumes that the dupeInfoString is in the format of
// pipe-delimited vid's followed by
// ie. "3456|9880|keepVid=3456"
if (deleteCandidateList == null || deleteCandidateList.size() == 0) {
// No vid's on the candidate list -- so no deleting will happen on
// this run
return false;
}
String[] dupeArr = dupeInfoString.split("\\|");
ArrayList<String> idArr = new ArrayList<>();
int lastIndex = dupeArr.length - 1;
for (int i = 0; i <= lastIndex; i++) {
if (i < lastIndex) {
// This is not the last entry, it is one of the dupes,
String vidString = dupeArr[i];
idArr.add(vidString);
} else {
// This is the last entry which should tell us if we have a
// preferred keeper
String prefString = dupeArr[i];
if (prefString.equals("KeepVid=UNDETERMINED")) {
// They sent us a bad string -- nothing should be deleted if
// no dupe could be tagged as preferred
return false;
} else {
// If we know which to keep, then the prefString should look
// like, "KeepVid=12345"
String[] prefArr = prefString.split("=");
if (prefArr.length != 2 || (!prefArr[0].equals("KeepVid"))) {
LOGGER.error("Bad format. Expecting KeepVid=999999");
return false;
} else {
String keepVidStr = prefArr[1];
if (idArr.contains(keepVidStr)) {
idArr.remove(keepVidStr);
// So now, the idArr should just contain the vid's
// that we want to remove.
for (int x = 0; x < idArr.size(); x++) {
boolean okFlag = true;
String thisVid = idArr.get(x);
if (deleteCandidateList.contains(thisVid)) {
// This vid is a valid delete candidate from
// a prev. run, so we can remove it.
try {
long longVertId = Long
.parseLong(thisVid);
Vertex vtx = g
.traversal().V(longVertId).next();
vtx.remove();
if (singleCommits) {
// NOTE - the singleCommits option is not used in normal processing
g.tx().commit();
g = AAIGraph.getInstance().getGraph().newTransaction();
}
} catch (Exception e) {
okFlag = false;
LOGGER.error("ERROR trying to delete VID = " + thisVid, e);
}
if (okFlag) {
LOGGER.info(" DELETED VID = " + thisVid);
deletedSomething = true;
}
}
}
} else {
LOGGER.error("ERROR - Vertex Id to keep not found in list of dupes. dupeInfoString = ["
+ dupeInfoString + "]");
return false;
}
}
}// else we know which one to keep
}// else last entry
}// for each vertex in a group
return deletedSomething;
}// end of deleteNonKeepersIfAppropriate()
/**
* Gets the node just using key params.
*
* @param transId the trans id
* @param fromAppId the from app id
* @param graph the graph
* @param nodeType the node type
* @param keyPropsHash the key props hash
* @param apiVersion the api version
* @return the node just using key params
* @throws AAIException the AAI exception
*/
public static List <Vertex> getNodeJustUsingKeyParams( String transId, String fromAppId, GraphTraversalSource graph, String nodeType,
HashMap<String,Object> keyPropsHash, String apiVersion ) throws AAIException{
List <Vertex> retVertList = new ArrayList <> ();
// We assume that all NodeTypes have at least one key-property defined.
// Note - instead of key-properties (the primary key properties), a user could pass
// alternate-key values if they are defined for the nodeType.
List<String> kName = new ArrayList<>();
List<Object> kVal = new ArrayList<>();
if( keyPropsHash == null || keyPropsHash.isEmpty() ) {
throw new AAIException("AAI_6120", " NO key properties passed for this getNodeJustUsingKeyParams() request. NodeType = [" + nodeType + "]. ");
}
int i = -1;
for( Map.Entry<String, Object> entry : keyPropsHash.entrySet() ){
i++;
kName.add(i, entry.getKey());
kVal.add(i, entry.getValue());
}
int topPropIndex = i;
Vertex tiV = null;
String propsAndValuesForMsg = "";
Iterator <Vertex> verts = null;
try {
if( topPropIndex == 0 ){
propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ") ";
verts= graph.V().has(kName.get(0),kVal.get(0)).has("aai-node-type",nodeType);
}
else if( topPropIndex == 1 ){
propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
+ kName.get(1) + " = " + kVal.get(1) + ") ";
verts = graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has("aai-node-type",nodeType);
}
else if( topPropIndex == 2 ){
propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
+ kName.get(1) + " = " + kVal.get(1) + ", "
+ kName.get(2) + " = " + kVal.get(2) + ") ";
verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has("aai-node-type",nodeType);
}
else if( topPropIndex == 3 ){
propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
+ kName.get(1) + " = " + kVal.get(1) + ", "
+ kName.get(2) + " = " + kVal.get(2) + ", "
+ kName.get(3) + " = " + kVal.get(3) + ") ";
verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has(kName.get(3),kVal.get(3)).has("aai-node-type",nodeType);
}
else {
throw new AAIException("AAI_6114", " We only support 4 keys per nodeType for now \n");
}
}
catch( Exception ex ){
LOGGER.error( " ERROR trying to get node for: [" + propsAndValuesForMsg + "]", ex);
}
if( verts != null ){
while( verts.hasNext() ){
tiV = verts.next();
retVertList.add(tiV);
}
}
if( retVertList.size() == 0 ){
LOGGER.debug("DEBUG No node found for nodeType = [" + nodeType +
"], propsAndVal = " + propsAndValuesForMsg );
}
return retVertList;
}// End of getNodeJustUsingKeyParams()
/**
* Show all edges for node.
*
* @param transId the trans id
* @param fromAppId the from app id
* @param tVert the t vert
* @return the array list
*/
private static ArrayList <String> showAllEdgesForNode( String transId, String fromAppId, Vertex tVert ){
ArrayList <String> retArr = new ArrayList <> ();
Iterator <Edge> eI = tVert.edges(Direction.IN);
if( ! eI.hasNext() ){
retArr.add("No IN edges were found for this vertex. ");
}
while( eI.hasNext() ){
Edge ed = eI.next();
String lab = ed.label();
Vertex vtx;
if (tVert.equals(ed.inVertex())) {
vtx = ed.outVertex();
} else {
vtx = ed.inVertex();
}
if( vtx == null ){
retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< ");
}
else {
String nType = vtx.<String>property("aai-node-type").orElse(null);
String vid = vtx.id().toString();
retArr.add("Found an IN edge (" + lab + ") to this vertex from a [" + nType + "] node with VtxId = " + vid );
}
}
eI = tVert.edges(Direction.OUT);
if( ! eI.hasNext() ){
retArr.add("No OUT edges were found for this vertex. ");
}
while( eI.hasNext() ){
Edge ed = eI.next();
String lab = ed.label();
Vertex vtx;
if (tVert.equals(ed.inVertex())) {
vtx = ed.outVertex();
} else {
vtx = ed.inVertex();
}
if( vtx == null ){
retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< ");
}
else {
String nType = vtx.<String>property("aai-node-type").orElse(null);
String vid = vtx.id().toString();
retArr.add("Found an OUT edge (" + lab + ") from this vertex to a [" + nType + "] node with VtxId = " + vid );
}
}
return retArr;
}
/**
* Show properties for node.
*
* @param transId the trans id
* @param fromAppId the from app id
* @param tVert the t vert
* @return the array list
*/
private static ArrayList <String> showPropertiesForNode( String transId, String fromAppId, Vertex tVert ){
ArrayList <String> retArr = new ArrayList <> ();
if( tVert == null ){
retArr.add("null Node object passed to showPropertiesForNode()\n");
}
else {
String nodeType = "";
Object ob = tVert.<Object>property("aai-node-type").orElse(null);
if( ob == null ){
nodeType = "null";
}
else{
nodeType = ob.toString();
}
retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]");
retArr.add(" Property Detail: ");
Iterator<VertexProperty<Object>> pI = tVert.properties();
while( pI.hasNext() ){
VertexProperty<Object> tp = pI.next();
Object val = tp.value();
retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] ");
}
}
return retArr;
}
private static ArrayList <Vertex> getConnectedNodes(GraphTraversalSource g, Vertex startVtx )
throws AAIException {
ArrayList <Vertex> retArr = new ArrayList <> ();
if( startVtx == null ){
return retArr;
}
else {
GraphTraversal<Vertex, Vertex> modPipe = null;
modPipe = g.V(startVtx).both();
if( modPipe != null && modPipe.hasNext() ){
while( modPipe.hasNext() ){
Vertex conVert = modPipe.next();
retArr.add(conVert);
}
}
}
return retArr;
}// End of getConnectedNodes()
private static ArrayList <Vertex> getConnectedChildrenOfOneType( GraphTraversalSource g,
Vertex startVtx, String childNType ) throws AAIException{
ArrayList <Vertex> childList = new ArrayList <> ();
Iterator <Vertex> vertI = g.V(startVtx).union(__.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).inV(), __.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).outV());
Vertex tmpVtx = null;
while( vertI != null && vertI.hasNext() ){
tmpVtx = vertI.next();
Object ob = tmpVtx.<Object>property("aai-node-type").orElse(null);
if (ob != null) {
String tmpNt = ob.toString();
if( tmpNt.equals(childNType)){
childList.add(tmpVtx);
}
}
}
return childList;
}// End of getConnectedChildrenOfOneType()
private static Vertex getConnectedParent( GraphTraversalSource g,
Vertex startVtx ) throws AAIException{
Vertex parentVtx = null;
Iterator <Vertex> vertI = g.V(startVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV());
while( vertI != null && vertI.hasNext() ){
// Note - there better only be one!
parentVtx = vertI.next();
}
return parentVtx;
}// End of getConnectedParent()
private static long figureWindowStartTime( int timeWindowMinutes ){
// Given a window size, calculate what the start-timestamp would be.
if( timeWindowMinutes <= 0 ){
// This just means that there is no window...
return 0;
}
long unixTimeNow = System.currentTimeMillis();
long windowInMillis = timeWindowMinutes * 60L * 1000;
long startTimeStamp = unixTimeNow - windowInMillis;
return startTimeStamp;
} // End of figureWindowStartTime()
}
|