Search in sources :

Example 1 with OplogOperation

use of com.eightkdata.mongowp.server.api.oplog.OplogOperation 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 OplogOperation

use of com.eightkdata.mongowp.server.api.oplog.OplogOperation in project torodb by torodb.

the class FilteredOplogFetcher method fetch.

@Override
public OplogBatch fetch() throws StopReplicationException, RollbackReplicationException {
    OplogBatch batch = delegate.fetch();
    List<OplogOperation> filteredBatch = batch.getOps().stream().filter(filter).collect(Collectors.toList());
    if (filteredBatch.isEmpty()) {
        if (batch.isLastOne()) {
            return FinishedOplogBatch.getInstance();
        } else {
            return NotReadyForMoreOplogBatch.getInstance();
        }
    } else {
        if (batch.isLastOne()) {
            throw new AssertionError("Batchs produced by a finished oplog fetcher cannot " + "contain ops");
        }
        return new NormalOplogBatch(filteredBatch, batch.isReadyForMore());
    }
}
Also used : NormalOplogBatch(com.torodb.mongodb.repl.oplogreplier.NormalOplogBatch) NotReadyForMoreOplogBatch(com.torodb.mongodb.repl.oplogreplier.NotReadyForMoreOplogBatch) FinishedOplogBatch(com.torodb.mongodb.repl.oplogreplier.FinishedOplogBatch) NormalOplogBatch(com.torodb.mongodb.repl.oplogreplier.NormalOplogBatch) OplogBatch(com.torodb.mongodb.repl.oplogreplier.OplogBatch) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation)

Example 3 with OplogOperation

use of com.eightkdata.mongowp.server.api.oplog.OplogOperation in project torodb by torodb.

the class SimpleAnalyzedOplogBatchExecutorTest method testVisit_CudAnalyzedOplog_Success.

@Test
public void testVisit_CudAnalyzedOplog_Success() throws Exception {
    //GIVEN
    OplogOperation lastOp = mock(OplogOperation.class);
    CudAnalyzedOplogBatch batch = mock(CudAnalyzedOplogBatch.class);
    ApplierContext applierContext = new ApplierContext.Builder().setReapplying(true).setUpdatesAsUpserts(true).build();
    given(batch.getOriginalBatch()).willReturn(Lists.newArrayList(mock(OplogOperation.class), mock(OplogOperation.class), mock(OplogOperation.class), lastOp));
    Timer timer = mock(Timer.class);
    Context context = mock(Context.class);
    given(metrics.getCudBatchTimer()).willReturn(timer);
    given(timer.time()).willReturn(context);
    doNothing().when(executor).execute(eq(batch), any());
    //WHEN
    OplogOperation result = executor.visit(batch, applierContext);
    //THEN
    then(metrics).should().getCudBatchTimer();
    then(timer).should().time();
    then(context).should().close();
    then(executor).should(times(1)).execute(batch, applierContext);
    assertEquals(lastOp, result);
}
Also used : ApplierContext(com.torodb.mongodb.repl.oplogreplier.ApplierContext) Context(com.codahale.metrics.Timer.Context) Timer(com.codahale.metrics.Timer) OplogOperation(com.eightkdata.mongowp.server.api.oplog.OplogOperation) ApplierContext(com.torodb.mongodb.repl.oplogreplier.ApplierContext) Test(org.junit.Test)

Example 4 with OplogOperation

use of com.eightkdata.mongowp.server.api.oplog.OplogOperation 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 5 with OplogOperation

use of com.eightkdata.mongowp.server.api.oplog.OplogOperation 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)

Aggregations

OplogOperation (com.eightkdata.mongowp.server.api.oplog.OplogOperation)23 ApplierContext (com.torodb.mongodb.repl.oplogreplier.ApplierContext)10 Test (org.junit.Test)10 Context (com.codahale.metrics.Timer.Context)8 Timer (com.codahale.metrics.Timer)7 RetrierGiveUpException (com.torodb.core.retrier.RetrierGiveUpException)7 RollbackException (com.torodb.core.transaction.RollbackException)6 MongoException (com.eightkdata.mongowp.exceptions.MongoException)5 RetrierAbortException (com.torodb.core.retrier.RetrierAbortException)5 InsertOplogOperation (com.eightkdata.mongowp.server.api.oplog.InsertOplogOperation)4 OplogBatch (com.torodb.mongodb.repl.oplogreplier.OplogBatch)4 OpTime (com.eightkdata.mongowp.OpTime)3 UserException (com.torodb.core.exceptions.user.UserException)3 OplogManagerPersistException (com.torodb.mongodb.repl.OplogManager.OplogManagerPersistException)3 WriteOplogTransaction (com.torodb.mongodb.repl.OplogManager.WriteOplogTransaction)3 OplogStartMissingException (com.eightkdata.mongowp.exceptions.OplogStartMissingException)2 FinishedOplogBatch (com.torodb.mongodb.repl.oplogreplier.FinishedOplogBatch)2 NormalOplogBatch (com.torodb.mongodb.repl.oplogreplier.NormalOplogBatch)2 NotReadyForMoreOplogBatch (com.torodb.mongodb.repl.oplogreplier.NotReadyForMoreOplogBatch)2 OplogFetcher (com.torodb.mongodb.repl.oplogreplier.fetcher.OplogFetcher)2