org.apache.tinkerpop.gremlin.process.traversal.util.TraversalInterruptedException Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.util.TraversalInterruptedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Traverser.Admin<E> next() {
    if (EmptyTraverser.instance() != this.nextEnd) {
        try {
            return this.prepareTraversalForNextStep(this.nextEnd);
        } finally {
            this.nextEnd = EmptyTraverser.instance();
        }
    } else {
        while (true) {
            if (Thread.interrupted()) throw new TraversalInterruptedException();
            final Traverser.Admin<E> traverser = this.processNextStart();
            if (traverser.bulk() > 0)
                return this.prepareTraversalForNextStep(traverser);
        }
    }
}
 
Example #2
Source File: AbstractStep.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasNext() {
    if (EmptyTraverser.instance() != this.nextEnd)
        return true;
    else {
        try {
            while (true) {
                if (Thread.interrupted()) throw new TraversalInterruptedException();
                this.nextEnd = this.processNextStart();
                if (this.nextEnd.bulk() > 0)
                    return true;
                else
                    this.nextEnd = EmptyTraverser.instance();
            }
        } catch (final NoSuchElementException e) {
            return false;
        }
    }
}
 
Example #3
Source File: SqlgAbstractStep.java    From sqlg with MIT License 6 votes vote down vote up
@Override
public Traverser.Admin<E> next() {
    if (null != this.nextEnd) {
        try {
            return this.prepareTraversalForNextStep(this.nextEnd);
        } finally {
            this.nextEnd = null;
        }
    } else {
        while (true) {
            if (Thread.interrupted()) throw new TraversalInterruptedException();
            final Traverser.Admin<E> traverser = this.processNextStart();
            if (null != traverser.get() && 0 != traverser.bulk())
                return this.prepareTraversalForNextStep(traverser);
        }
    }
}
 
Example #4
Source File: SqlgAbstractStep.java    From sqlg with MIT License 6 votes vote down vote up
@Override
public boolean hasNext() {
    if (null != this.nextEnd)
        return true;
    else {
        try {
            while (true) {
                if (Thread.interrupted()) throw new TraversalInterruptedException();
                this.nextEnd = this.processNextStart();
                if (null != this.nextEnd.get() && 0 != this.nextEnd.bulk())
                    return true;
                else
                    this.nextEnd = null;
            }
        } catch (final NoSuchElementException e) {
            return false;
        }
    }
}
 
Example #5
Source File: BackendTransaction.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private <V> V executeRead(Callable<V> exe) throws JanusGraphException {
    try {
        return BackendOperation.execute(exe, maxReadTime);
    } catch (JanusGraphException e) {
        // support traversal interruption
        // TODO: Refactor to allow direct propagation of underlying interrupt exception
        if (Thread.interrupted()) throw new TraversalInterruptedException();
        throw e;
    }
}
 
Example #6
Source File: TraversalInterruptionComputerTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(GRATEFUL)
public void shouldRespectThreadInterruptionInVertexStep() throws Exception {
    final AtomicBoolean exceptionThrown = new AtomicBoolean(false);
    final CountDownLatch startedIterating = new CountDownLatch(1);
    final Thread t = new Thread(() -> {
        try {
            final Traversal traversal = traversalMaker.apply(g).sideEffect(traverser -> {
                startedIterating.countDown();
                try {
                    // artificially slow down the traversal execution so that
                    // this test has a chance to interrupt it before it finishes
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // if the traversal is interrupted while in this
                    // sleep, reassert the interrupt so that the thread is
                    // re-marked as interrupted and correctly handled as
                    // an interrupted traversal
                    Thread.currentThread().interrupt();
                }
            });
            traversal.iterate();
        } catch (Exception ex) {
            exceptionThrown.set(ex instanceof TraversalInterruptedException);
        }
    }, name);

    t.start();

    // total time for test should not exceed 5 seconds - this prevents the test from just hanging and allows
    // it to finish with failure
    assertThat(startedIterating.await(5000, TimeUnit.MILLISECONDS), CoreMatchers.is(true));

    t.interrupt();
    t.join();

    // ensure that some but not all of the traversal was iterated and that the right exception was tossed
    assertThat(exceptionThrown.get(), CoreMatchers.is(true));
}
 
Example #7
Source File: HugeException.java    From hugegraph with Apache License 2.0 4 votes vote down vote up
public static boolean isInterrupted(Throwable e) {
    Throwable rootCause = HugeException.rootCause(e);
    return rootCause instanceof InterruptedException ||
           rootCause instanceof TraversalInterruptedException ||
           rootCause instanceof InterruptedIOException;
}
 
Example #8
Source File: TraversalTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public T next() {
    if (Thread.interrupted()) throw new TraversalInterruptedException();
    return itty.next();
}
 
Example #9
Source File: TraversalInterruptionTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Test
@LoadGraphWith(GRATEFUL)
public void shouldRespectThreadInterruptionInVertexStep() throws Exception {
    final AtomicBoolean exceptionThrown = new AtomicBoolean(false);
    final CountDownLatch startedIterating = new CountDownLatch(1);
    final Thread t = new Thread(() -> {
        final Traversal traversal = traversalAfterPause.apply(traversalBeforePause.apply(g).sideEffect(traverser -> {
            // let the first iteration flow through
            if (startedIterating.getCount() == 0) {
                // ensure that the whole traversal doesn't iterate out before we get a chance to interrupt
                // the next iteration should stop so we can force the interrupt to be handled by VertexStep
                try {
                    Thread.sleep(3000);
                } catch (Exception ignored) {
                    // make sure that the interrupt propagates in case the interrupt occurs during sleep.
                    // this should ensure VertexStep gets to try to throw the TraversalInterruptedException
                    Thread.currentThread().interrupt();
                }
            } else {
                startedIterating.countDown();
            }
        }));
        try {
            traversal.iterate();
        } catch (Exception ex) {
            exceptionThrown.set(ex instanceof TraversalInterruptedException);

            try {
                traversal.close();
            } catch (Exception iex) {
                logger.error("Error closing traversal after interruption", iex);
            }
        }

    }, name);

    t.start();

    // total time for test should not exceed 5 seconds - this prevents the test from just hanging and allows
    // it to finish with failure
    assertThat(startedIterating.await(5000, TimeUnit.MILLISECONDS), CoreMatchers.is(true));

    t.interrupt();
    t.join();

    // ensure that some but not all of the traversal was iterated and that the right exception was tossed
    assertThat(exceptionThrown.get(), CoreMatchers.is(true));
}
 
Example #10
Source File: GremlinExecutor.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle.
 *
 * @param script the script to evaluate
 * @param language the language to evaluate it in
 * @param boundVars the bindings to evaluate in the context of the script
 * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process
 */
public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars,  final LifeCycle lifeCycle) {
    final String lang = Optional.ofNullable(language).orElse("gremlin-groovy");

    logger.debug("Preparing to evaluate script - {} - in thread [{}]", script, Thread.currentThread().getName());

    final Bindings bindings = new SimpleBindings();
    bindings.putAll(globalBindings);
    bindings.putAll(boundVars);

    // override the timeout if the lifecycle has a value assigned
    final long scriptEvalTimeOut = lifeCycle.getEvaluationTimeoutOverride().orElse(evaluationTimeout);

    final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>();
    final FutureTask<Void> evalFuture = new FutureTask<>(() -> {
        try {
            lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings);

            logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName());

            // do this weirdo check until the now deprecated ScriptEngines is gutted
            final Object o = gremlinScriptEngineManager.getEngineByName(lang).eval(script, bindings);

            // apply a transformation before sending back the result - useful when trying to force serialization
            // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some
            // transactional constraints
            final Object result = lifeCycle.getTransformResult().isPresent() ?
                    lifeCycle.getTransformResult().get().apply(o) : o;

            // a mechanism for taking the final result and doing something with it in the same thread, but
            // AFTER the eval and transform are done and that future completed.  this provides a final means
            // for working with the result in the same thread as it was eval'd
            if (lifeCycle.getWithResult().isPresent()) lifeCycle.getWithResult().get().accept(result);

            lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings);

            // the evaluationFuture must be completed after all processing as an exception in lifecycle events
            // that must raise as an exception to the caller who has the returned evaluationFuture. in other words,
            // if it occurs before this point, then the handle() method won't be called again if there is an
            // exception that ends up below trying to completeExceptionally()
            evaluationFuture.complete(result);
        } catch (Throwable ex) {
            final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex);

            // thread interruptions will typically come as the result of a timeout, so in those cases,
            // check for that situation and convert to TimeoutException
            if (root instanceof InterruptedException
                    || root instanceof TraversalInterruptedException
                    || root instanceof InterruptedIOException) {
                lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings);
                evaluationFuture.completeExceptionally(new TimeoutException(
                        String.format("Evaluation exceeded the configured 'evaluationTimeout' threshold of %s ms or evaluation was otherwise cancelled directly for request [%s]: %s", scriptEvalTimeOut, script, root.getMessage())));
            } else {
                lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root);
                evaluationFuture.completeExceptionally(root);
            }
        }

        return null;
    });

    final WeakReference<CompletableFuture<Object>> evaluationFutureRef = new WeakReference<>(evaluationFuture);
    final Future<?> executionFuture = executorService.submit(evalFuture);
    if (scriptEvalTimeOut > 0) {
        // Schedule a timeout in the thread pool for future execution
        final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> {
            if (executionFuture.cancel(true)) {
                final CompletableFuture<Object> ef = evaluationFutureRef.get();
                if (ef != null) {
                    ef.completeExceptionally(new TimeoutException(
                            String.format("Evaluation exceeded the configured 'evaluationTimeout' threshold of %s ms or evaluation was otherwise cancelled directly for request [%s]", scriptEvalTimeOut, script)));
                }
            }
        }, scriptEvalTimeOut, TimeUnit.MILLISECONDS);

        // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed with exception
        evaluationFuture.handleAsync((v, t) -> {
            if (!sf.isDone()) {
                logger.debug("Killing scheduled timeout on script evaluation - {} - as the eval completed (possibly with exception).", script);
                sf.cancel(true);
            }

            // no return is necessary - nothing downstream is concerned with what happens in here
            return null;
        }, scheduledExecutorService);
    }

    return evaluationFuture;
}