Search in sources :

Example 1 with RetrierGiveUpException

use of com.torodb.core.retrier.RetrierGiveUpException in project torodb by torodb.

the class ContinuousOplogFetcher method fetch.

@Override
public OplogBatch fetch() throws StopReplicationException, RollbackReplicationException {
    if (state.isClosed()) {
        return FinishedOplogBatch.getInstance();
    }
    try {
        return retrier.retry(() -> {
            try {
                if (state.isClosed()) {
                    return FinishedOplogBatch.getInstance();
                }
                state.prepareToFetch();
                MongoCursor<OplogOperation> cursor = state.getLastUsedMongoCursor();
                Batch<OplogOperation> batch = cursor.tryFetchBatch();
                if (batch == null || !batch.hasNext()) {
                    Thread.sleep(1000);
                    batch = cursor.tryFetchBatch();
                    if (batch == null || !batch.hasNext()) {
                        return NotReadyForMoreOplogBatch.getInstance();
                    }
                }
                List<OplogOperation> fetchedOps = null;
                long fetchTime = 0;
                /*
           * As we already modify the cursor by fetching the batch, we cannot retry the whole block
           * (as the cursor would be reused and the previous batch will be discarted).
           *
           * Then, if we leave the following try section with an error, we need to discard the
           * cursor, so the next iteration starts from the last batch we returned. On the other
           * hand, if we finished successfully, then we need to update the state.
           */
                boolean successful = false;
                try {
                    fetchedOps = batch.asList();
                    fetchTime = batch.getFetchTime();
                    postBatchChecks(cursor, fetchedOps);
                    OplogBatch result = new NormalOplogBatch(fetchedOps, true);
                    successful = true;
                    return result;
                } finally {
                    if (!successful) {
                        cursor.close();
                    } else {
                        assert fetchedOps != null;
                        assert fetchTime != 0;
                        state.updateState(fetchedOps, fetchTime);
                    }
                }
            } catch (RestartFetchException ex) {
                //lets choose a new reader
                state.discardReader();
                //and then try again
                throw new RollbackException(ex);
            } catch (DeadCursorException ex) {
                //lets retry the whole block with the same reader
                throw new RollbackException(ex);
            } catch (StopReplicationException | RollbackReplicationException ex) {
                //do not try again
                throw new RetrierAbortException(ex);
            } catch (MongoServerException ex) {
                //TODO: Fix this violation on the abstraction!
                LOGGER.debug("Found an unwrapped MongodbServerException");
                //lets choose a new reader
                state.discardReader();
                //rollback and hopefully use another member
                throw new RollbackException(ex);
            } catch (MongoException | MongoRuntimeException ex) {
                LOGGER.warn("Catched an error while reading the remote " + "oplog: {}", ex.getLocalizedMessage());
                //lets choose a new reader
                state.discardReader();
                //rollback and hopefully use another member
                throw new RollbackException(ex);
            }
        }, Hint.CRITICAL, Hint.TIME_SENSIBLE);
    } catch (RetrierGiveUpException ex) {
        this.close();
        throw new StopReplicationException("Stopping replication after several attepts to " + "fetch the remote oplog", ex);
    } catch (RetrierAbortException ex) {
        this.close();
        Throwable cause = ex.getCause();
        if (cause != null) {
            if (cause instanceof StopReplicationException) {
                throw (StopReplicationException) cause;
            }
            if (cause instanceof RollbackReplicationException) {
                throw (RollbackReplicationException) cause;
            }
        }
        throw new StopReplicationException("Stopping replication after a unknown abort " + "exception", ex);
    }
}
Also used : DeadCursorException(com.eightkdata.mongowp.server.api.pojos.MongoCursor.DeadCursorException) MongoException(com.eightkdata.mongowp.exceptions.MongoException) MongoRuntimeException(com.eightkdata.mongowp.server.api.MongoRuntimeException) RollbackReplicationException(com.torodb.mongodb.repl.oplogreplier.RollbackReplicationException) RollbackException(com.torodb.core.transaction.RollbackException) RetrierGiveUpException(com.torodb.core.retrier.RetrierGiveUpException) NormalOplogBatch(com.torodb.mongodb.repl.oplogreplier.NormalOplogBatch) RetrierAbortException(com.torodb.core.retrier.RetrierAbortException) FinishedOplogBatch(com.torodb.mongodb.repl.oplogreplier.FinishedOplogBatch) OplogBatch(com.torodb.mongodb.repl.oplogreplier.OplogBatch) NotReadyForMoreOplogBatch(com.torodb.mongodb.repl.oplogreplier.NotReadyForMoreOplogBatch) NormalOplogBatch(com.torodb.mongodb.repl.oplogreplier.NormalOplogBatch) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation) MongoServerException(com.mongodb.MongoServerException) StopReplicationException(com.torodb.mongodb.repl.oplogreplier.StopReplicationException)

Example 2 with RetrierGiveUpException

use of com.torodb.core.retrier.RetrierGiveUpException in project torodb by torodb.

the class AkkaDbCloner method prepareCollection.

private void prepareCollection(MongodServer localServer, String dstDb, Entry colEntry) throws RetrierAbortException {
    try {
        retrier.retry(() -> {
            try (WriteMongodTransaction transaction = createWriteMongodTransaction(localServer)) {
                dropCollection(transaction, dstDb, colEntry.getCollectionName());
                createCollection(transaction, dstDb, colEntry.getCollectionName(), colEntry.getCollectionOptions());
                transaction.commit();
                return null;
            } catch (UserException ex) {
                throw new RetrierAbortException("An unexpected user exception was catched", ex);
            }
        });
    } catch (RetrierGiveUpException ex) {
        throw new CloningException(ex);
    }
}
Also used : WriteMongodTransaction(com.torodb.mongodb.core.WriteMongodTransaction) RetrierAbortException(com.torodb.core.retrier.RetrierAbortException) UserException(com.torodb.core.exceptions.user.UserException) RetrierGiveUpException(com.torodb.core.retrier.RetrierGiveUpException)

Example 3 with RetrierGiveUpException

use of com.torodb.core.retrier.RetrierGiveUpException in project torodb by torodb.

the class SimpleAnalyzedOplogBatchExecutorTest method testVisit_SingleOp_NotRepyingRollback.

/**
   * Test the behaviour of the method
   * {@link SimpleAnalyzedOplogBatchExecutor#visit(com.torodb.mongodb.repl.oplogreplier.batch.SingleOpAnalyzedOplogBatch, com.torodb.mongodb.repl.oplogreplier.ApplierContext) that visits a single op}
   * when
   * {@link SimpleAnalyzedOplogBatchExecutor#execute(com.eightkdata.mongowp.server.api.oplog.OplogOperation, com.torodb.mongodb.repl.oplogreplier.ApplierContext) the execution}
   * fails until the given attempt.
   *
   *
   * @param myRetrier
   * @param atteptsToSucceed
   * @return true if the execution finishes or false if it throw an exception.
   * @throws Exception
   */
private boolean testVisit_SingleOp_NotRepyingRollback(Retrier myRetrier, int atteptsToSucceed) throws Exception {
    //GIVEN
    OplogOperation operation = mock(OplogOperation.class);
    SingleOpAnalyzedOplogBatch batch = new SingleOpAnalyzedOplogBatch(operation);
    ApplierContext applierContext = new ApplierContext.Builder().setReapplying(true).setUpdatesAsUpserts(false).build();
    executor = spy(new SimpleAnalyzedOplogBatchExecutor(metrics, applier, server, myRetrier, namespaceJobExecutor));
    Timer timer = mock(Timer.class);
    Context context = mock(Context.class);
    given(metrics.getSingleOpTimer(operation)).willReturn(timer);
    given(timer.time()).willReturn(context);
    doAnswer(new Answer() {

        int attempts = 0;

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            try {
                ApplierContext context = invocation.getArgument(1);
                if (attempts == 0) {
                    assert !context.treatUpdateAsUpsert() : "on this test, first attept should be not trying updates as upserts";
                    throw new RollbackException("Forcing a rollback on the first attempt");
                }
                assert context.treatUpdateAsUpsert() : "on this test, only the first attept should be " + "not trying updates as upserts, but " + attempts + " is not trying updates as upserts";
                if (attempts < (atteptsToSucceed - 1)) {
                    throw new RollbackException("forcing a rollback on the " + attempts + "th attempt");
                }
                return null;
            } finally {
                attempts++;
            }
        }
    }).when(executor).execute(eq(operation), any());
    try {
        //WHEN
        OplogOperation result = executor.visit(batch, applierContext);
        //THEN
        then(executor).should(times(atteptsToSucceed)).execute(eq(operation), any());
        assertEquals(operation, result);
        return true;
    } catch (RetrierGiveUpException ignore) {
        return false;
    } finally {
        then(metrics).should().getSingleOpTimer(operation);
        then(timer).should().time();
    }
}
Also used : ApplierContext(com.torodb.mongodb.repl.oplogreplier.ApplierContext) Context(com.codahale.metrics.Timer.Context) RollbackException(com.torodb.core.transaction.RollbackException) RetrierGiveUpException(com.torodb.core.retrier.RetrierGiveUpException) ApplierContext(com.torodb.mongodb.repl.oplogreplier.ApplierContext) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Timer(com.codahale.metrics.Timer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation)

Example 4 with RetrierGiveUpException

use of com.torodb.core.retrier.RetrierGiveUpException in project torodb by torodb.

the class SimpleAnalyzedOplogBatchExecutorTest method testVisit_CudAnalyzedOplog_NotRepyingRollback.

/**
   * Test the behaviour of the method
   * {@link SimpleAnalyzedOplogBatchExecutor#visit(com.torodb.mongodb.repl.oplogreplier.batch.CudAnalyzedOplogBatch, com.torodb.mongodb.repl.oplogreplier.ApplierContext)  that visits a cud batch}
   * when
   * {@link SimpleAnalyzedOplogBatchExecutor#execute(com.torodb.mongodb.repl.oplogreplier.batch.CudAnalyzedOplogBatch, com.torodb.mongodb.repl.oplogreplier.ApplierContext) the execution}
   * fails until the given attempt.
   *
   *
   * @param myRetrier
   * @param atteptsToSucceed
   * @return true if the execution finishes or false if it throw an exception.
   * @throws Exception
   */
private boolean testVisit_CudAnalyzedOplog_NotRepyingRollback(Retrier myRetrier, int atteptsToSucceed) throws Exception {
    //GIVEN
    OplogOperation lastOp = mock(OplogOperation.class);
    CudAnalyzedOplogBatch batch = mock(CudAnalyzedOplogBatch.class);
    ApplierContext applierContext = new ApplierContext.Builder().setReapplying(true).setUpdatesAsUpserts(false).build();
    given(batch.getOriginalBatch()).willReturn(Lists.newArrayList(mock(OplogOperation.class), mock(OplogOperation.class), mock(OplogOperation.class), lastOp));
    executor = spy(new SimpleAnalyzedOplogBatchExecutor(metrics, applier, server, myRetrier, namespaceJobExecutor));
    Timer timer = mock(Timer.class);
    Context context = mock(Context.class);
    given(metrics.getCudBatchTimer()).willReturn(timer);
    given(timer.time()).willReturn(context);
    doAnswer(new Answer() {

        int attempts = 0;

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            try {
                ApplierContext context = invocation.getArgument(1);
                if (attempts == 0) {
                    assert !context.treatUpdateAsUpsert() : "on this test, first attept should be not trying updates as upserts";
                    throw new RollbackException("Forcing a rollback on the first attempt");
                }
                assert context.treatUpdateAsUpsert() : "on this test, only the first attept should be " + "not trying updates as upserts, but " + attempts + " is not trying updates as upserts";
                if (attempts < (atteptsToSucceed - 1)) {
                    throw new RollbackException("forcing a rollback on the " + attempts + "th attempt");
                }
                return null;
            } finally {
                attempts++;
            }
        }
    }).when(executor).execute(eq(batch), any());
    boolean success;
    try {
        //WHEN
        OplogOperation result = executor.visit(batch, applierContext);
        //THEN
        then(executor).should(times(atteptsToSucceed)).execute(eq(batch), any());
        assertEquals(lastOp, result);
        success = true;
    } catch (RetrierGiveUpException ignore) {
        success = false;
    }
    then(metrics.getCudBatchSize()).should().update(batch.getOriginalBatch().size());
    then(metrics).should().getCudBatchTimer();
    then(metrics.getCudBatchTimer()).should().time();
    return success;
}
Also used : ApplierContext(com.torodb.mongodb.repl.oplogreplier.ApplierContext) Context(com.codahale.metrics.Timer.Context) RollbackException(com.torodb.core.transaction.RollbackException) RetrierGiveUpException(com.torodb.core.retrier.RetrierGiveUpException) ApplierContext(com.torodb.mongodb.repl.oplogreplier.ApplierContext) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Timer(com.codahale.metrics.Timer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation)

Example 5 with RetrierGiveUpException

use of com.torodb.core.retrier.RetrierGiveUpException in project torodb by torodb.

the class TorodbSafeRequestProcessor method execute.

@Override
public <A, R> Status<R> execute(Request req, Command<? super A, ? super R> command, A arg, MongodConnection connection) {
    mongodMetrics.getCommands().mark();
    Timer timer = mongodMetrics.getTimer(command);
    try (Timer.Context ctx = timer.time()) {
        Callable<Status<R>> callable;
        RequiredTransaction commandType = commandsLibrary.getCommandType(command);
        switch(commandType) {
            case NO_TRANSACTION:
                callable = () -> {
                    return connection.getCommandsExecutor().execute(req, command, arg, connection);
                };
                break;
            case READ_TRANSACTION:
                callable = () -> {
                    try (ReadOnlyMongodTransaction trans = connection.openReadOnlyTransaction()) {
                        return trans.execute(req, command, arg);
                    }
                };
                break;
            case WRITE_TRANSACTION:
                callable = () -> {
                    try (WriteMongodTransaction trans = connection.openWriteTransaction(true)) {
                        Status<R> result = trans.execute(req, command, arg);
                        if (result.isOk()) {
                            trans.commit();
                        }
                        return result;
                    }
                };
                break;
            case EXCLUSIVE_WRITE_TRANSACTION:
                callable = () -> {
                    try (ExclusiveWriteMongodTransaction trans = connection.openExclusiveWriteTransaction(true)) {
                        Status<R> result = trans.execute(req, command, arg);
                        if (result.isOk()) {
                            trans.commit();
                        }
                        return result;
                    }
                };
                break;
            default:
                throw new AssertionError("Unexpected command type" + commandType);
        }
        try {
            return retrier.retry(callable);
        } catch (RetrierGiveUpException ex) {
            return Status.from(ErrorCode.CONFLICTING_OPERATION_IN_PROGRESS, "It was impossible to execute " + command.getCommandName() + " after several attempts");
        }
    }
}
Also used : Status(com.eightkdata.mongowp.Status) ExclusiveWriteMongodTransaction(com.torodb.mongodb.core.ExclusiveWriteMongodTransaction) WriteMongodTransaction(com.torodb.mongodb.core.WriteMongodTransaction) Timer(com.codahale.metrics.Timer) RequiredTransaction(com.torodb.mongodb.commands.TorodbCommandsLibrary.RequiredTransaction) ReadOnlyMongodTransaction(com.torodb.mongodb.core.ReadOnlyMongodTransaction) ExclusiveWriteMongodTransaction(com.torodb.mongodb.core.ExclusiveWriteMongodTransaction) RetrierGiveUpException(com.torodb.core.retrier.RetrierGiveUpException)

Aggregations

RetrierGiveUpException (com.torodb.core.retrier.RetrierGiveUpException)11 RetrierAbortException (com.torodb.core.retrier.RetrierAbortException)8 OplogOperation (com.eightkdata.mongowp.server.api.oplog.OplogOperation)7 Timer (com.codahale.metrics.Timer)6 Context (com.codahale.metrics.Timer.Context)6 ApplierContext (com.torodb.mongodb.repl.oplogreplier.ApplierContext)6 MongoException (com.eightkdata.mongowp.exceptions.MongoException)4 RollbackException (com.torodb.core.transaction.RollbackException)4 UserException (com.torodb.core.exceptions.user.UserException)3 WriteMongodTransaction (com.torodb.mongodb.core.WriteMongodTransaction)3 Test (org.junit.Test)3 Request (com.eightkdata.mongowp.server.api.Request)2 BsonDocumentBuilder (com.eightkdata.mongowp.utils.BsonDocumentBuilder)2 DatabaseNotFoundException (com.torodb.core.exceptions.user.DatabaseNotFoundException)2 Locked (com.torodb.mongodb.annotations.Locked)2 ReadOnlyMongodTransaction (com.torodb.mongodb.core.ReadOnlyMongodTransaction)2 Mockito.doAnswer (org.mockito.Mockito.doAnswer)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 Answer (org.mockito.stubbing.Answer)2 OpTime (com.eightkdata.mongowp.OpTime)1