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
| public final class TinkerGraphComputer implements GraphComputer { static { TraversalStrategies.GlobalCache.registerStrategies(TinkerGraphComputer.class, TraversalStrategies.GlobalCache.getStrategies(GraphComputer.class).clone().removeSt rategies(GraphFilterStrategy.class)); }
private ResultGraph resultGraph = null; private Persist persist = null; private VertexProgram<?> vertexProgram; private final TinkerGraph graph; private TinkerMemory memory; private final TinkerMessageBoard messageBoard = new TinkerMessageBoard(); private boolean executed = false; private final Set<MapReduce> mapReducers = new HashSet<>(); private int workers = Runtime.getRuntime().availableProcessors(); private final GraphFilter graphFilter = new GraphFilter();
private final ThreadFactory threadFactoryBoss = new BasicThreadFactory.Builder().namingPattern(TinkerGraphComputer.class.getSimpleName() + "-boss").build();
private final ExecutorService computerService = Executors.newSingleThreadExecutor(threadFactoryBoss);
public TinkerGraphComputer(final TinkerGraph graph) { this.graph = graph; }
@Override public GraphComputer result(final ResultGraph resultGraph) { this.resultGraph = resultGraph; return this; }
@Override public GraphComputer persist(final Persist persist) { this.persist = persist; return this; }
@Override public GraphComputer program(final VertexProgram vertexProgram) { this.vertexProgram = vertexProgram; return this; }
@Override public GraphComputer mapReduce(final MapReduce mapReduce) { this.mapReducers.add(mapReduce); return this; }
@Override public GraphComputer workers(final int workers) { this.workers = workers; return this; }
@Override public GraphComputer vertices(final Traversal<Vertex, Vertex> vertexFilter) { this.graphFilter.setVertexFilter(vertexFilter); return this; }
@Override public GraphComputer edges(final Traversal<Vertex, Edge> edgeFilter) { this.graphFilter.setEdgeFilter(edgeFilter); return this; }
@Override public Future<ComputerResult> submit() { if (this.executed) throw Exceptions.computerHasAlreadyBeenSubmittedAVertexProgram(); else this.executed = true; if (null == this.vertexProgram && this.mapReducers.isEmpty()) throw GraphComputer.Exceptions.computerHasNoVertexProgramNorMapReducers(); if (null != this.vertexProgram) { GraphComputerHelper.validateProgramOnComputer(this, this.vertexProgram); this.mapReducers.addAll(this.vertexProgram.getMapReducers()); } this.resultGraph = GraphComputerHelper.getResultGraphState(Optional.ofNullable(this.vertexProgram), Optional.ofNullable(this.resultGraph)); this.persist = GraphComputerHelper.getPersistState(Optional.ofNullable(this.vertexProgram), Optional.ofNullable(this.persist));
if (!this.features().supportsResultGraphPersistCombination(this.resultGraph, this.persist))throw GraphComputer.Exceptions.resultGraphPersistCombinationNotSupported(this.resultGraph , this.persist); if (this.workers > this.features().getMaxWorkers()) throw GraphComputer.Exceptions.computerRequiresMoreWorkersThanSupported(this.workers, this.features().getMaxWorkers());
this.memory = new TinkerMemory(this.vertexProgram, this.mapReducers); return computerService.submit(() -> { final long time = System.currentTimeMillis(); final TinkerGraphComputerView view; final TinkerWorkerPool workers = new TinkerWorkerPool(this.workers); try { if (null != this.vertexProgram) { view = TinkerHelper.createGraphComputerView(this.graph, this.graphFilter, this.vertexProgram.getVertexComputeKeys()); this.vertexProgram.setup(this.memory); while (true) { if (Thread.interrupted()) throw new TraversalInterruptedException(); this.memory.completeSubRound(); workers.setVertexProgram(this.vertexProgram); final SynchronizedIterator<Vertex> vertices = new SynchronizedIterator<>(this.graph.vertices()); workers.executeVertexProgram(vertexProgram -> { vertexProgram.workerIterationStart(this.memory.asImmutable()); while (true) { final Vertex vertex = vertices.next(); if (Thread.interrupted()) throw new TraversalInterruptedException(); if (null == vertex) break; vertexProgram.execute( ComputerGraph.vertexProgram(vertex, vertexProgram), new TinkerMessenger<>(vertex, this.messageBoard, vertexProgram.getMessageCombiner()), this.memory ); } vertexProgram.workerIterationEnd(this.memory.asImmutable()); }); this.messageBoard.completeIteration(); this.memory.completeSubRound(); if (this.vertexProgram.terminate(this.memory)) { this.memory.incrIteration(); break; } else { this.memory.incrIteration(); } } view.complete(); } else { view = TinkerHelper.createGraphComputerView(this.graph, this.graphFilter, Collections.emptySet()); }
for (final MapReduce mapReduce : mapReducers) { final TinkerMapEmitter<?, ?> mapEmitter = new TinkerMapEmitter<>(mapReduce.doStage(MapReduce.Stage.REDUCE)); final SynchronizedIterator<Vertex> vertices = new SynchronizedIterator<>(this.graph.vertices()); workers.setMapReduce(mapReduce); workers.executeMapReduce(workerMapReduce -> { workerMapReduce.workerStart(MapReduce.Stage.MAP); while (true) { if (Thread.interrupted()) throw new TraversalInterruptedException(); final Vertex vertex = vertices.next(); if (null == vertex) break; workerMapReduce.map(ComputerGraph.mapReduce(vertex), mapEmitter); } workerMapReduce.workerEnd(MapReduce.Stage.MAP); }); mapEmitter.complete(mapReduce); if (mapReduce.doStage(MapReduce.Stage.REDUCE)) { final TinkerReduceEmitter<?, ?> reduceEmitter = new TinkerReduceEmitter<>(); final SynchronizedIterator<Map.Entry<?, Queue<?>>> keyValues = new SynchronizedIterator((Iterator) mapEmitter.reduceMap.entrySet().iterator()); workers.executeMapReduce(workerMapReduce -> { workerMapReduce.workerStart(MapReduce.Stage.REDUCE); while (true) { if (Thread.interrupted()) throw new TraversalInterruptedException(); final Map.Entry<?, Queue<?>> entry = keyValues.next(); if (null == entry) break; workerMapReduce.reduce(entry.getKey(), entry.getValue().iterator(), reduceEmitter); } workerMapReduce.workerEnd(MapReduce.Stage.REDUCE); }); reduceEmitter.complete(mapReduce); mapReduce.addResultToMemory(this.memory, reduceEmitter.reduceQueue.iterator()); } else { mapReduce.addResultToMemory(this.memory, mapEmitter.mapQueue.iterator()); } } this.memory.setRuntime(System.currentTimeMillis() - time); this.memory.complete(); final Graph resultGraph = view.processResultGraphPersist(this.resultGraph, this.persist); TinkerHelper.dropGraphComputerView(this.graph); return new DefaultComputerResult(resultGraph, this.memory.asImmutable()); } catch (InterruptedException ie) { workers.closeNow(); throw new TraversalInterruptedException(); } catch (Exception ex) { workers.closeNow(); throw new RuntimeException(ex); } finally { workers.close(); } }); }
@Override public String toString() { return StringFactory.graphComputerString(this); }
private static class SynchronizedIterator<V> {
private final Iterator<V> iterator;
public SynchronizedIterator(final Iterator<V> iterator) { this.iterator = iterator; }
public synchronized V next() { return this.iterator.hasNext() ? this.iterator.next() : null; } }
@Override public Features features() { return new Features() {
@Override public int getMaxWorkers() { return Runtime.getRuntime().availableProcessors(); }
@Override public boolean supportsVertexAddition() { return false; }
@Override public boolean supportsVertexRemoval() { return false; }
@Override public boolean supportsVertexPropertyRemoval() { return false; }
@Override public boolean supportsEdgeAddition() { return false; }
@Override public boolean supportsEdgeRemoval() { return false; }
@Override public boolean supportsEdgePropertyAddition() { return false; }
@Override public boolean supportsEdgePropertyRemoval() { return false; } }; } }
public final class TinkerGraphComputerView {
private final TinkerGraph graph; protected final Map<String, VertexComputeKey> computeKeys; private Map<Element, Map<String, List<VertexProperty<?>>>> computeProperties; private final Set<Object> legalVertices = new HashSet<>(); private final Map<Object, Set<Object>> legalEdges = new HashMap<>(); private final GraphFilter graphFilter;
public TinkerGraphComputerView(final TinkerGraph graph, final GraphFilter graphFilter, final Set<VertexComputeKey> computeKeys) { this.graph = graph; this.computeKeys = new HashMap<>(); computeKeys.forEach(key -> this.computeKeys.put(key.getKey(), key)); this.computeProperties = new ConcurrentHashMap<>(); this.graphFilter = graphFilter; if (this.graphFilter.hasFilter()) { graph.vertices().forEachRemaining(vertex -> { boolean legalVertex = false; if (this.graphFilter.hasVertexFilter() && this.graphFilter.legalVertex(vertex)) { this.legalVertices.add(vertex.id()); legalVertex = true; } if ((legalVertex || !this.graphFilter.hasVertexFilter()) && this.graphFilter.hasEdgeFilter()) { final Set<Object> edges = new HashSet<>(); this.legalEdges.put(vertex.id(), edges); this.graphFilter.legalEdges(vertex).forEachRemaining(edge -> edges.add(edge.id())); } }); } }
public <V> Property<V> addProperty(final TinkerVertex vertex, final String key, final V value) { ElementHelper.validateProperty(key, value); if (isComputeKey(key)) { final TinkerVertexProperty<V> property = new TinkerVertexProperty<V>((TinkerVertex) vertex, key, value) { @Override public void remove() { removeProperty(vertex, key, this); } }; this.addValue(vertex, key, property); return property; } else { throw GraphComputer.Exceptions.providedKeyIsNotAnElementComputeKey(key); } }
public List<VertexProperty<?>> getProperty(final TinkerVertex vertex, final String key) { final List<VertexProperty<?>> vertexProperty = this.getValue(vertex, key); return vertexProperty.isEmpty() ? (List) TinkerHelper.getProperties(vertex).getOrDefault(key, Collections.emptyList()) : vertexProperty; }
public List<Property> getProperties(final TinkerVertex vertex) { final Stream<Property> a = TinkerHelper.getProperties(vertex).values().stream().flatMap(list -> list.stream()); final Stream<Property> b = this.computeProperties.containsKey(vertex) ? this.computeProperties.get(vertex).values().stream().flatMap(list -> list.stream()) : Stream.empty(); return Stream.concat(a, b).collect(Collectors.toList()); }
public void removeProperty(final TinkerVertex vertex, final String key, final VertexProperty property) { if (isComputeKey(key)) { this.removeValue(vertex, key, property); } else { throw GraphComputer.Exceptions.providedKeyIsNotAnElementComputeKey(key); } }
public boolean legalVertex(final Vertex vertex) { return !this.graphFilter.hasVertexFilter() || this.legalVertices.contains(vertex.id()); }
public boolean legalEdge(final Vertex vertex, final Edge edge) { return !this.graphFilter.hasEdgeFilter() || this.legalEdges.get(vertex.id()).contains(edge.id()); }
protected void complete() { for (final VertexComputeKey computeKey : this.computeKeys.values()) { if (computeKey.isTransient()) { final List<VertexProperty<?>> toRemove = this.computeProperties.values().stream().flatMap(map -> map.getOrDefault(computeKey.getKey(), Collections.emptyList()).stream()).collect(Collectors.toList()); toRemove.forEach(VertexProperty::remove); } } }
public Graph processResultGraphPersist(final GraphComputer.ResultGraph resultGraph, final GraphComputer.Persist persist) { if (GraphComputer.Persist.NOTHING == persist) { if (GraphComputer.ResultGraph.ORIGINAL == resultGraph) return this.graph; else return EmptyGraph.instance(); } else if (GraphComputer.Persist.VERTEX_PROPERTIES == persist) { if (GraphComputer.ResultGraph.ORIGINAL == resultGraph) { this.addPropertiesToOriginalGraph(); return this.graph; } else { final TinkerGraph newGraph = TinkerGraph.open(); this.graph.vertices().forEachRemaining(vertex -> { final Vertex newVertex = newGraph.addVertex(T.id, vertex.id(), T.label, vertex.label()); vertex.properties().forEachRemaining(vertexProperty -> { final VertexProperty<?> newVertexProperty = newVertex.property(VertexProperty.Cardinality.list, vertexProperty.key(), vertexProperty.value(), T.id, vertexProperty.id()); vertexProperty.properties().forEachRemaining(property -> { newVertexProperty.property(property.key(), property.value()); }); }); }); return newGraph; } } else { if (GraphComputer.ResultGraph.ORIGINAL == resultGraph) { this.addPropertiesToOriginalGraph(); return this.graph; } else { final TinkerGraph newGraph = TinkerGraph.open(); this.graph.vertices().forEachRemaining(vertex -> { final Vertex newVertex = newGraph.addVertex(T.id, vertex.id(), T.label, vertex.label()); vertex.properties().forEachRemaining(vertexProperty -> { final VertexProperty<?> newVertexProperty = newVertex.property(VertexProperty.Cardinality.list, vertexProperty.key(), vertexProperty.value(), T.id, vertexProperty.id()); vertexProperty.properties().forEachRemaining(property -> { newVertexProperty.property(property.key(), property.value()); }); }); }); this.graph.edges().forEachRemaining(edge -> { final Vertex outVertex = newGraph.vertices(edge.outVertex().id()).next(); final Vertex inVertex = newGraph.vertices(edge.inVertex().id()).next(); final Edge newEdge = outVertex.addEdge(edge.label(), inVertex, T.id, edge.id()); edge.properties().forEachRemaining(property -> newEdge.property(property.key(), property.value())); }); return newGraph; } } }
private void addPropertiesToOriginalGraph() { TinkerHelper.dropGraphComputerView(this.graph); this.computeProperties.forEach((element, properties) -> { properties.forEach((key, vertexProperties) -> { vertexProperties.forEach(vertexProperty -> { final VertexProperty<?> newVertexProperty = ((Vertex) element).property(VertexProperty.Cardinality.list, vertexProperty.key(), vertexProperty.value(), T.id, vertexProperty.id()); vertexProperty.properties().forEachRemaining(property -> { newVertexProperty.property(property.key(), property.value()); }); }); }); }); this.computeProperties.clear(); }
private boolean isComputeKey(final String key) { return this.computeKeys.containsKey(key); }
private void addValue(final Vertex vertex, final String key, final VertexProperty property) { final Map<String, List<VertexProperty<?>>> elementProperties = this.computeProperties.computeIfAbsent(vertex, k -> new ConcurrentHashMap<>()); elementProperties.compute(key, (k, v) -> { if (null == v) v = Collections.synchronizedList(new ArrayList<>()); v.add(property); return v; }); }
private void removeValue(final Vertex vertex, final String key, final VertexProperty property) { this.computeProperties.computeIfPresent(vertex, (k, v) -> { v.computeIfPresent(key, (k1, v1) -> { v1.remove(property); return v1; }); return v; }); }
private List<VertexProperty<?>> getValue(final Vertex vertex, final String key) { return this.computeProperties.getOrDefault(vertex, Collections.emptyMap()).getOrDefault(key, Collections.emptyList()); } }
|