Search in sources :

Example 41 with Checkpoint

use of com.linkedin.databus.core.Checkpoint in project databus by linkedin.

the class TestGenericDispatcher method testPartialWindowRollback.

@Test(groups = { "small", "functional" })
public /**
 * Tests the case where the dispatcher exits the main processing loop in {@link GenericDispatcher#doDispatchEvents()}
 * with a partial window and the flushing of the outstanding callbacks fails. We want to make sure that a rollback
 * is correctly triggered.
 *
 * The test simulates the following case: e1_1 e1_2 e1_3 <EOW> e2_1 e2_2 e2_3 <EOW> ... with a failure in the e2_2
 * callback.
 *
 * 1) Read full first window: e1_1 e1_2 e1_3 <EOW>
 * 2) Read partial second window: e2_1 e2_2
 * 3) The above should fail -- verify that rollback is called
 * 4) Read the rest
 */
void testPartialWindowRollback() throws Exception {
    final Logger log = Logger.getLogger("TestGenericDispatcher.testPartialWindowRollback");
    // log.setLevel(Level.INFO);
    log.info("start");
    final Level saveLevel = Logger.getLogger("com.linkedin.databus.client").getLevel();
    // Logger.getLogger("com.linkedin.databus.client").setLevel(Level.DEBUG);
    // generate events
    Vector<Short> srcIdList = new Vector<Short>();
    srcIdList.add((short) 1);
    DbusEventGenerator evGen = new DbusEventGenerator(0, srcIdList);
    Vector<DbusEvent> srcTestEvents = new Vector<DbusEvent>();
    final int numEvents = 9;
    // 1-based number of the event callback to fail
    final int numOfFailureEvent = 5;
    final int numEventsPerWindow = 3;
    final int payloadSize = 200;
    final int numWindows = (int) Math.ceil(1.0 * numEvents / numEventsPerWindow);
    Assert.assertTrue(evGen.generateEvents(numEvents, numEventsPerWindow, 500, payloadSize, srcTestEvents) > 0);
    // find out how much data we need to stream for the failure
    // account for the EOW event which is < payload size
    int win1Size = payloadSize - 1;
    int win2Size = 0;
    int eventN = 0;
    for (DbusEvent e : srcTestEvents) {
        eventN++;
        if (eventN <= numEventsPerWindow) {
            win1Size += e.size();
        } else if (eventN <= numOfFailureEvent) {
            win2Size += e.size();
        }
    }
    // serialize the events to a buffer so they can be sent to the client
    final TestGenericDispatcherEventBuffer srcEventsBuf = new TestGenericDispatcherEventBuffer(_generic100KBufferStaticConfig);
    DbusEventAppender eventProducer = new DbusEventAppender(srcTestEvents, srcEventsBuf, null, true);
    Thread tEmitter = new Thread(eventProducer);
    tEmitter.start();
    // Create destination (client) buffer
    final TestGenericDispatcherEventBuffer destEventsBuf = new TestGenericDispatcherEventBuffer(_generic100KBufferStaticConfig);
    // Create dispatcher
    final TimeoutTestConsumer mockConsumer = new TimeoutTestConsumer(100, 10, 0, numOfFailureEvent, 0, 1);
    SelectingDatabusCombinedConsumer sdccMockConsumer = new SelectingDatabusCombinedConsumer((DatabusStreamConsumer) mockConsumer);
    List<String> sources = new ArrayList<String>();
    Map<Long, IdNamePair> sourcesMap = new HashMap<Long, IdNamePair>();
    for (int i = 1; i <= 3; ++i) {
        IdNamePair sourcePair = new IdNamePair((long) i, "source" + i);
        sources.add(sourcePair.getName());
        sourcesMap.put(sourcePair.getId(), sourcePair);
    }
    DatabusV2ConsumerRegistration consumerReg = new DatabusV2ConsumerRegistration(sdccMockConsumer, sources, null);
    List<DatabusV2ConsumerRegistration> allRegistrations = Arrays.asList(consumerReg);
    final ConsumerCallbackStats callbackStats = new ConsumerCallbackStats(0, "test", "test", true, false, null);
    final UnifiedClientStats unifiedStats = new UnifiedClientStats(0, "test", "test.unified");
    MultiConsumerCallback callback = new MultiConsumerCallback(allRegistrations, Executors.newFixedThreadPool(2), 1000, new StreamConsumerCallbackFactory(callbackStats, unifiedStats), callbackStats, unifiedStats, null, null);
    callback.setSourceMap(sourcesMap);
    List<DatabusSubscription> subs = DatabusSubscription.createSubscriptionList(sources);
    final RelayDispatcher dispatcher = new RelayDispatcher("dispatcher", _genericRelayConnStaticConfig, subs, new InMemoryPersistenceProvider(), destEventsBuf, callback, null, null, null, null, null);
    dispatcher.setSchemaIdCheck(false);
    Thread dispatcherThread = new Thread(dispatcher);
    dispatcherThread.setDaemon(true);
    log.info("starting dispatcher thread");
    dispatcherThread.start();
    HashMap<Long, List<RegisterResponseEntry>> schemaMap = new HashMap<Long, List<RegisterResponseEntry>>();
    List<RegisterResponseEntry> l1 = new ArrayList<RegisterResponseEntry>();
    List<RegisterResponseEntry> l2 = new ArrayList<RegisterResponseEntry>();
    List<RegisterResponseEntry> l3 = new ArrayList<RegisterResponseEntry>();
    l1.add(new RegisterResponseEntry(1L, (short) 1, SOURCE1_SCHEMA_STR));
    l2.add(new RegisterResponseEntry(2L, (short) 1, SOURCE2_SCHEMA_STR));
    l3.add(new RegisterResponseEntry(3L, (short) 1, SOURCE3_SCHEMA_STR));
    schemaMap.put(1L, l1);
    schemaMap.put(2L, l2);
    schemaMap.put(3L, l3);
    dispatcher.enqueueMessage(SourcesMessage.createSetSourcesIdsMessage(sourcesMap.values()));
    dispatcher.enqueueMessage(SourcesMessage.createSetSourcesSchemasMessage(schemaMap));
    log.info("starting event dispatch");
    // stream the events from the source buffer without the EOW
    // comm channels between reader and writer
    Pipe pipe = Pipe.open();
    Pipe.SinkChannel writerStream = pipe.sink();
    Pipe.SourceChannel readerStream = pipe.source();
    writerStream.configureBlocking(true);
    readerStream.configureBlocking(false);
    // Event writer - Relay in the real world
    Checkpoint cp = Checkpoint.createFlexibleCheckpoint();
    // Event readers - Clients in the real world
    // Checkpoint pullerCheckpoint = Checkpoint.createFlexibleCheckpoint();
    DbusEventsStatisticsCollector clientStats = new DbusEventsStatisticsCollector(0, "client", true, false, null);
    DbusEventBufferReader reader = new DbusEventBufferReader(destEventsBuf, readerStream, null, clientStats);
    UncaughtExceptionTrackingThread tReader = new UncaughtExceptionTrackingThread(reader, "Reader");
    tReader.setDaemon(true);
    tReader.start();
    try {
        log.info("send first window -- that one should be OK");
        StreamEventsResult streamRes = srcEventsBuf.streamEvents(cp, writerStream, new StreamEventsArgs(win1Size));
        Assert.assertEquals(numEventsPerWindow + 1, streamRes.getNumEventsStreamed());
        TestUtil.assertWithBackoff(new ConditionCheck() {

            @Override
            public boolean check() {
                return 1 == callbackStats.getNumSysEventsProcessed();
            }
        }, "first window processed", 5000, log);
        log.info("send the second partial window -- that one should cause an error");
        streamRes = srcEventsBuf.streamEvents(cp, writerStream, new StreamEventsArgs(win2Size));
        Assert.assertEquals(numOfFailureEvent - numEventsPerWindow, streamRes.getNumEventsStreamed());
        log.info("wait for dispatcher to finish");
        TestUtil.assertWithBackoff(new ConditionCheck() {

            @Override
            public boolean check() {
                log.info("events received: " + callbackStats.getNumDataEventsReceived());
                return numOfFailureEvent <= callbackStats.getNumDataEventsProcessed();
            }
        }, "all events until the error processed", 5000, log);
        log.info("all data events have been received but no EOW");
        Assert.assertEquals(numOfFailureEvent, clientStats.getTotalStats().getNumDataEvents());
        Assert.assertEquals(1, clientStats.getTotalStats().getNumSysEvents());
        // at least one failing event therefore < numOfFailureEvent events can be processed
        Assert.assertTrue(numOfFailureEvent <= callbackStats.getNumDataEventsProcessed());
        // onDataEvent callbacks for e2_1 and e2_2 get cancelled
        Assert.assertEquals(2, callbackStats.getNumDataErrorsProcessed());
        // only one EOW
        Assert.assertEquals(1, callbackStats.getNumSysEventsProcessed());
        log.info("Send the remainder of the window");
        streamRes = srcEventsBuf.streamEvents(cp, writerStream, new StreamEventsArgs(100000));
        // remaining events + EOWs
        Assert.assertEquals(srcTestEvents.size() + numWindows - (numOfFailureEvent + 1), streamRes.getNumEventsStreamed());
        log.info("wait for the rollback");
        TestUtil.assertWithBackoff(new ConditionCheck() {

            @Override
            public boolean check() {
                return 1 == mockConsumer.getNumRollbacks();
            }
        }, "rollback seen", 5000, log);
        log.info("wait for dispatcher to finish after the rollback");
        TestUtil.assertWithBackoff(new ConditionCheck() {

            @Override
            public boolean check() {
                log.info("num windows processed: " + callbackStats.getNumSysEventsProcessed());
                return numWindows == callbackStats.getNumSysEventsProcessed();
            }
        }, "all events processed", 5000, log);
    } finally {
        reader.stop();
        dispatcher.shutdown();
        log.info("all events processed");
        verifyNoLocks(null, srcEventsBuf);
        verifyNoLocks(null, destEventsBuf);
    }
    Logger.getLogger("com.linkedin.databus.client").setLevel(saveLevel);
    log.info("end\n");
}
Also used : DbusEventAppender(com.linkedin.databus.core.test.DbusEventAppender) DatabusV2ConsumerRegistration(com.linkedin.databus.client.consumer.DatabusV2ConsumerRegistration) UncaughtExceptionTrackingThread(com.linkedin.databus.core.util.UncaughtExceptionTrackingThread) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DbusEventsStatisticsCollector(com.linkedin.databus.core.monitoring.mbean.DbusEventsStatisticsCollector) StreamEventsArgs(com.linkedin.databus.core.StreamEventsArgs) Logger(org.apache.log4j.Logger) IdNamePair(com.linkedin.databus.core.util.IdNamePair) List(java.util.List) ArrayList(java.util.ArrayList) Vector(java.util.Vector) DbusEventBufferReader(com.linkedin.databus.core.test.DbusEventBufferReader) ConditionCheck(com.linkedin.databus2.test.ConditionCheck) StreamConsumerCallbackFactory(com.linkedin.databus.client.consumer.StreamConsumerCallbackFactory) UnifiedClientStats(com.linkedin.databus.client.pub.mbean.UnifiedClientStats) DbusEvent(com.linkedin.databus.core.DbusEvent) StreamEventsResult(com.linkedin.databus.core.StreamEventsResult) ConsumerCallbackStats(com.linkedin.databus.client.pub.mbean.ConsumerCallbackStats) MultiConsumerCallback(com.linkedin.databus.client.consumer.MultiConsumerCallback) DbusEventGenerator(com.linkedin.databus.core.test.DbusEventGenerator) Pipe(java.nio.channels.Pipe) DatabusSubscription(com.linkedin.databus.core.data_model.DatabusSubscription) Checkpoint(com.linkedin.databus.core.Checkpoint) UncaughtExceptionTrackingThread(com.linkedin.databus.core.util.UncaughtExceptionTrackingThread) Checkpoint(com.linkedin.databus.core.Checkpoint) SelectingDatabusCombinedConsumer(com.linkedin.databus.client.consumer.SelectingDatabusCombinedConsumer) RegisterResponseEntry(com.linkedin.databus2.core.container.request.RegisterResponseEntry) Level(org.apache.log4j.Level) Test(org.testng.annotations.Test)

Example 42 with Checkpoint

use of com.linkedin.databus.core.Checkpoint in project databus by linkedin.

the class BootstrapStartScnHttpResponseProcessor method finishResponse.

@Override
public void finishResponse() throws Exception {
    super.finishResponse();
    if (_errorHandled) {
        return;
    }
    try {
        String exceptionName = RemoteExceptionHandler.getExceptionName(_decorated);
        Throwable remoteException = _remoteExceptionHandler.getException(_decorated);
        if (null != remoteException && remoteException instanceof BootstrapDatabaseTooOldException) {
            _remoteExceptionHandler.handleException(remoteException);
        } else if (null != exceptionName) {
            LOG.error("/startScn response error: " + RemoteExceptionHandler.getExceptionMessage(_decorated));
            _stateReuse.switchToStartScnResponseError();
            LOG.error("Failed to process /startscn response");
        } else {
            String hostHdr = DbusConstants.UNKNOWN_HOST;
            String svcHdr = DbusConstants.UNKNOWN_SERVICE_ID;
            if (null != getParent()) {
                hostHdr = getParent().getRemoteHost();
                svcHdr = getParent().getRemoteService();
                LOG.info("initiated bootstrap sesssion to host " + hostHdr + " service " + svcHdr);
            }
            InputStream bodyStream = Channels.newInputStream(_decorated);
            ObjectMapper mapper = new ObjectMapper();
            String scnString = mapper.readValue(bodyStream, String.class);
            ServerInfo serverInfo = null;
            String serverHostPort = _decorated.getMetadata(DbusConstants.SERVER_INFO_HOSTPORT_HEADER_PARAM);
            try {
                serverInfo = ServerInfo.buildServerInfoFromHostPort(serverHostPort, DbusConstants.HOSTPORT_DELIMITER);
            } catch (Exception ex) {
                LOG.error("Unable to extract Boostrap Server info from StartSCN response. ServerInfo was :" + serverHostPort, ex);
            }
            LOG.info("Response startScn:" + scnString + ", from bootstrap Server :" + serverHostPort);
            long startScn = Long.parseLong(scnString);
            Checkpoint ckpt = _checkpoint;
            if (startScn < 0) {
                LOG.error("unexpected value for startSCN: " + startScn);
                _stateReuse.switchToStartScnResponseError();
            } else if (ckpt.getConsumptionMode() != DbusClientMode.BOOTSTRAP_SNAPSHOT) {
                LOG.error("StartScnResponseProcessor:" + " expecting in client mode: " + DbusClientMode.BOOTSTRAP_SNAPSHOT + " while in the incorrect mode: " + ckpt.getConsumptionMode());
            } else {
                LOG.info("Start SCN " + startScn + " received for bootstrap snapshot source " + ckpt.getSnapshotSource());
                ckpt.setBootstrapStartScn(startScn);
                ckpt.setBootstrapServerInfo(serverHostPort);
                /*
           * No need to create a seperate BootstrapConnection as we are guaranteed to have a bootstrap Connection
           * at this point.
           */
                _stateReuse.switchToStartScnSuccess(_checkpoint, null, serverInfo);
            }
        }
    } catch (Exception ex) {
        LOG.error("Failed to process /startscn response", ex);
        _stateReuse.switchToStartScnResponseError();
    }
    _callback.enqueueMessage(_stateReuse);
}
Also used : BootstrapDatabaseTooOldException(com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException) Checkpoint(com.linkedin.databus.core.Checkpoint) InputStream(java.io.InputStream) ServerInfo(com.linkedin.databus.client.pub.ServerInfo) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) BootstrapDatabaseTooOldException(com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException) InvalidCheckpointException(com.linkedin.databus.core.InvalidCheckpointException)

Example 43 with Checkpoint

use of com.linkedin.databus.core.Checkpoint in project databus by linkedin.

the class TestGenericDispatcher method testRollbackFailure.

@Test(groups = { "small", "functional" })
public /**
 * Test a relatively big window which forces a checkpoint which fails. Then trigger
 * a rollback. The dispatcher should shutdown.
 */
void testRollbackFailure() throws InvalidConfigException {
    final Logger log = Logger.getLogger("TestGenericDispatcher.testRollbackFailure");
    // log.setLevel(Level.DEBUG);
    log.info("start");
    final TestGenericDispatcherEventBuffer eventsBuf = new TestGenericDispatcherEventBuffer(_generic100KBufferStaticConfig);
    eventsBuf.start(0);
    eventsBuf.startEvents();
    initBufferWithEvents(eventsBuf, 1, 100, (short) 1, null, null);
    eventsBuf.endEvents(100L, null);
    RollbackFailingConsumer mockConsumer = new RollbackFailingConsumer(new StateVerifyingStreamConsumer(null), LOG, 2);
    List<String> sources = new ArrayList<String>();
    Map<Long, IdNamePair> sourcesMap = new HashMap<Long, IdNamePair>();
    for (int i = 1; i <= 3; ++i) {
        IdNamePair sourcePair = new IdNamePair((long) i, "source" + i);
        sources.add(sourcePair.getName());
        sourcesMap.put(sourcePair.getId(), sourcePair);
    }
    DatabusV2ConsumerRegistration consumerReg = new DatabusV2ConsumerRegistration(mockConsumer, sources, null);
    List<DatabusV2ConsumerRegistration> allRegistrations = Arrays.asList(consumerReg);
    MultiConsumerCallback callback = new MultiConsumerCallback(allRegistrations, Executors.newSingleThreadExecutor(), 1000, new StreamConsumerCallbackFactory(null, null), null, null, null, null);
    callback.setSourceMap(sourcesMap);
    DatabusSourcesConnection.Config connCfgBuilder = new DatabusSourcesConnection.Config();
    connCfgBuilder.setConsumerParallelism(1);
    connCfgBuilder.setEventBuffer(_generic100KBufferConfig);
    connCfgBuilder.setFreeBufferThreshold(10000);
    connCfgBuilder.setConsumerTimeBudgetMs(1000);
    connCfgBuilder.setCheckpointThresholdPct(5.0);
    connCfgBuilder.getDispatcherRetries().setMaxRetryNum(10);
    DatabusSourcesConnection.StaticConfig connStaticCfg = connCfgBuilder.build();
    List<DatabusSubscription> subs = DatabusSubscription.createSubscriptionList(sources);
    final RelayDispatcher dispatcher = new RelayDispatcher("dispatcher", connStaticCfg, subs, new InMemoryPersistenceProvider(), eventsBuf, callback, null, null, null, null, null);
    Thread dispatcherThread = new Thread(dispatcher);
    // dispatcherThread.setDaemon(true);
    dispatcherThread.start();
    HashMap<Long, List<RegisterResponseEntry>> schemaMap = new HashMap<Long, List<RegisterResponseEntry>>();
    List<RegisterResponseEntry> l1 = new ArrayList<RegisterResponseEntry>();
    List<RegisterResponseEntry> l2 = new ArrayList<RegisterResponseEntry>();
    List<RegisterResponseEntry> l3 = new ArrayList<RegisterResponseEntry>();
    l1.add(new RegisterResponseEntry(1L, (short) 1, SOURCE1_SCHEMA_STR));
    l2.add(new RegisterResponseEntry(2L, (short) 1, SOURCE2_SCHEMA_STR));
    l3.add(new RegisterResponseEntry(3L, (short) 1, SOURCE3_SCHEMA_STR));
    schemaMap.put(1L, l1);
    schemaMap.put(2L, l2);
    schemaMap.put(3L, l3);
    dispatcher.enqueueMessage(SourcesMessage.createSetSourcesIdsMessage(sourcesMap.values()));
    dispatcher.enqueueMessage(SourcesMessage.createSetSourcesSchemasMessage(schemaMap));
    try {
        TestUtil.assertWithBackoff(new ConditionCheck() {

            @Override
            public boolean check() {
                LOG.info(dispatcher.getStatus().getStatus().toString());
                LOG.info(String.valueOf(dispatcher.getStatus().getStatus() == DatabusComponentStatus.Status.SHUTDOWN));
                return dispatcher.getStatus().getStatus() == DatabusComponentStatus.Status.SHUTDOWN;
            }
        }, "dispatcher shtudown", 50000, LOG);
    } finally {
        dispatcher.shutdown();
    }
    verifyNoLocks(null, eventsBuf);
    log.info("end\n");
}
Also used : DatabusV2ConsumerRegistration(com.linkedin.databus.client.consumer.DatabusV2ConsumerRegistration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Logger(org.apache.log4j.Logger) IdNamePair(com.linkedin.databus.core.util.IdNamePair) List(java.util.List) ArrayList(java.util.ArrayList) ConditionCheck(com.linkedin.databus2.test.ConditionCheck) StreamConsumerCallbackFactory(com.linkedin.databus.client.consumer.StreamConsumerCallbackFactory) MultiConsumerCallback(com.linkedin.databus.client.consumer.MultiConsumerCallback) DatabusSubscription(com.linkedin.databus.core.data_model.DatabusSubscription) Checkpoint(com.linkedin.databus.core.Checkpoint) UncaughtExceptionTrackingThread(com.linkedin.databus.core.util.UncaughtExceptionTrackingThread) RegisterResponseEntry(com.linkedin.databus2.core.container.request.RegisterResponseEntry) Test(org.testng.annotations.Test)

Example 44 with Checkpoint

use of com.linkedin.databus.core.Checkpoint in project databus by linkedin.

the class MockBootstrapConnection method testTransition_StartSCNResponseSuccessNoSI.

@Test
public /**
 * Test bootstrap transition: StartSCN_Response_Success : when no ServerInfo
 */
void testTransition_StartSCNResponseSuccessNoSI() throws Exception {
    BootstrapPullThread bsPuller = createBootstrapPullThread(false, false, false);
    Checkpoint cp = _ckptHandlerTwoSources.createInitialBootstrapCheckpoint(null, 0L);
    bsPuller.getComponentStatus().start();
    ConnectionState connState = bsPuller.getConnectionState();
    connState.switchToBootstrap(cp);
    testTransitionCase(bsPuller, StateId.BOOTSTRAP, StateId.REQUEST_START_SCN, cp);
    bsPuller.getMessageQueue().clear();
    testTransitionCase(bsPuller, StateId.REQUEST_START_SCN, StateId.START_SCN_RESPONSE_SUCCESS, null);
    bsPuller.getMessageQueue().clear();
    Map<Long, List<RegisterResponseEntry>> entries = new HashMap<Long, List<RegisterResponseEntry>>();
    entries.put(1L, new ArrayList<RegisterResponseEntry>());
    connState.setSourcesSchemas(entries);
    connState.setCurrentBSServerInfo(null);
    testTransitionCase(bsPuller, StateId.START_SCN_RESPONSE_SUCCESS, StateId.START_SCN_RESPONSE_ERROR, null);
}
Also used : Checkpoint(com.linkedin.databus.core.Checkpoint) HashMap(java.util.HashMap) RegisterResponseEntry(com.linkedin.databus2.core.container.request.RegisterResponseEntry) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.testng.annotations.Test)

Example 45 with Checkpoint

use of com.linkedin.databus.core.Checkpoint in project databus by linkedin.

the class MockBootstrapConnection method testServerSetChange_TargetScnRequestSent.

@Test
public /**
 * Tests ServerSet change when in Target_Scn_Request_Sent
 */
void testServerSetChange_TargetScnRequestSent() throws Exception {
    BootstrapPullThread bsPuller = createBootstrapPullThread(false, false, false, false, false, null, 12000, 1, true);
    Checkpoint cp = _ckptHandlerSource1.createInitialBootstrapCheckpoint(null, 0L);
    // TODO remove
    // cp.setConsumptionMode(DbusClientMode.BOOTSTRAP_SNAPSHOT);
    // cp.setSnapshotSource("source1");
    // cp.setCatchupSource("source1");
    bsPuller.getComponentStatus().start();
    ConnectionState connState = bsPuller.getConnectionState();
    connState.switchToBootstrap(cp);
    testTransitionCase(bsPuller, StateId.BOOTSTRAP, StateId.REQUEST_START_SCN, cp);
    bsPuller.getMessageQueue().clear();
    testTransitionCase(bsPuller, StateId.REQUEST_START_SCN, StateId.START_SCN_RESPONSE_SUCCESS, null);
    bsPuller.getMessageQueue().clear();
    Map<Long, List<RegisterResponseEntry>> entries = new HashMap<Long, List<RegisterResponseEntry>>();
    entries.put(1L, new ArrayList<RegisterResponseEntry>());
    connState.setSourcesSchemas(entries);
    connState.setCurrentBSServerInfo(bsPuller.getCurentServer());
    testTransitionCase(bsPuller, StateId.START_SCN_RESPONSE_SUCCESS, StateId.REQUEST_STREAM, null);
    bsPuller.getMessageQueue().clear();
    connState.getSourcesNameMap().put("source1", new IdNamePair(1L, "source1"));
    connState.getSourceIdMap().put(1L, new IdNamePair(1L, "source1"));
    testTransitionCase(bsPuller, StateId.REQUEST_STREAM, StateId.STREAM_REQUEST_SUCCESS, null);
    bsPuller.getMessageQueue().clear();
    testTransitionCase(bsPuller, StateId.STREAM_REQUEST_SUCCESS, StateId.STREAM_RESPONSE_DONE, null);
    bsPuller.getMessageQueue().clear();
    cp.setSnapshotOffset(-1);
    testTransitionCase(bsPuller, StateId.STREAM_RESPONSE_DONE, StateId.REQUEST_TARGET_SCN, null);
    Assert.assertTrue(cp.isSnapShotSourceCompleted(), "Phase completed");
    Assert.assertEquals(cp.getConsumptionMode(), DbusClientMode.BOOTSTRAP_SNAPSHOT, "Consumption Mode check");
    Assert.assertFalse(cp.isBootstrapTargetScnSet());
    bsPuller.getMessageQueue().clear();
    MockBootstrapConnection mockConn = (MockBootstrapConnection) connState.getBootstrapConnection();
    mockConn.setMuteTransition(true);
    testTransitionCase(bsPuller, StateId.REQUEST_TARGET_SCN, StateId.TARGET_SCN_REQUEST_SENT, "", null);
    // ServerSetChange when New Set includes CurrentServer
    {
        Assert.assertEquals(bsPuller.getCurrentServerIdx() != -1, true, "Current Server Index defined");
        Assert.assertEquals(bsPuller.getCurentServer() != null, true, "Current Server not Null");
        ServerInfo oldServer = bsPuller.getCurentServer();
        Assert.assertEquals(bsPuller.getServers(), EXP_SERVERINFO_1, "Server Set");
        entries = new HashMap<Long, List<RegisterResponseEntry>>();
        entries.put(1L, new ArrayList<RegisterResponseEntry>());
        connState.setSourcesSchemas(entries);
        doExecuteAndChangeState(bsPuller, createSetServerMessage(true, bsPuller));
        Assert.assertEquals(bsPuller.getCurrentServerIdx() != -1, true, "Current Server Index defined");
        Assert.assertEquals(bsPuller.getCurentServer(), oldServer, "Current Server unchanged");
        Assert.assertEquals(bsPuller.getServers(), EXP_SERVERINFO_2, "Server Set");
        Assert.assertEquals(bsPuller.toTearConnAfterHandlingResponse(), false, "Tear Conn After Handling Response");
        Assert.assertEquals(connState.getStateId(), StateId.TARGET_SCN_REQUEST_SENT, "ServerSetChange while TARGET_SCN_REQUEST_SENT");
        Assert.assertEquals(bsPuller.getQueueListString(), "RelayPuller queue: []", "Queue :ServerSetChange while TARGET_SCN_REQUEST_SENT");
        Assert.assertTrue(cp.isSnapShotSourceCompleted(), "Phase completed");
        Assert.assertEquals(cp.getConsumptionMode(), DbusClientMode.BOOTSTRAP_SNAPSHOT, "Consumption Mode check");
    }
    // ServerSetChange when New Set excludes CurrentServer and SuccessFul Response
    {
        int oldServerIndex = bsPuller.getCurrentServerIdx();
        ServerInfo oldServer = bsPuller.getCurentServer();
        Assert.assertEquals(bsPuller.getServers(), EXP_SERVERINFO_2, "Server Set");
        entries = new HashMap<Long, List<RegisterResponseEntry>>();
        entries.put(1L, new ArrayList<RegisterResponseEntry>());
        connState.setSourcesSchemas(entries);
        doExecuteAndChangeState(bsPuller, createSetServerMessage(false, bsPuller));
        Assert.assertEquals(bsPuller.getCurrentServerIdx(), oldServerIndex, "Current Server Index unchanged");
        Assert.assertEquals(bsPuller.getCurentServer(), oldServer, "Current Server unchanged");
        Assert.assertEquals(bsPuller.getServers(), EXP_SERVERINFO_3, "Server Set");
        Assert.assertEquals(bsPuller.toTearConnAfterHandlingResponse(), true, "Tear Conn After Handling Response");
        Assert.assertEquals(connState.getStateId(), StateId.TARGET_SCN_REQUEST_SENT, "ServerSetChange while TARGET_SCN_REQUEST_SENT");
        Assert.assertEquals(bsPuller.getQueueListString(), "RelayPuller queue: []", "Queue :ServerSetChange while TARGET_SCN_REQUEST_SENT");
        // Now Response arrives
        connState.switchToStartScnSuccess(cp, null, null);
        testTransitionCase(bsPuller, StateId.TARGET_SCN_REQUEST_SENT, StateId.PICK_SERVER, null);
        Assert.assertEquals(bsPuller.toTearConnAfterHandlingResponse(), false, "Tear Conn After Handling Response");
        Assert.assertEquals(bsPuller.getCurrentServerIdx() == -1, true, "Current Server Index undefined");
        Assert.assertEquals(bsPuller.getCurentServer() == null, true, "Current Server Null");
        Assert.assertTrue(cp.isSnapShotSourceCompleted(), "Phase completed");
        Assert.assertEquals(cp.getConsumptionMode(), DbusClientMode.BOOTSTRAP_SNAPSHOT, "Consumption Mode check");
    }
}
Also used : HashMap(java.util.HashMap) ServerInfo(com.linkedin.databus.client.pub.ServerInfo) ArrayList(java.util.ArrayList) Checkpoint(com.linkedin.databus.core.Checkpoint) RegisterResponseEntry(com.linkedin.databus2.core.container.request.RegisterResponseEntry) ArrayList(java.util.ArrayList) List(java.util.List) IdNamePair(com.linkedin.databus.core.util.IdNamePair) Test(org.testng.annotations.Test)

Aggregations

Checkpoint (com.linkedin.databus.core.Checkpoint)139 Test (org.testng.annotations.Test)88 ArrayList (java.util.ArrayList)46 RegisterResponseEntry (com.linkedin.databus2.core.container.request.RegisterResponseEntry)42 HashMap (java.util.HashMap)42 List (java.util.List)42 IdNamePair (com.linkedin.databus.core.util.IdNamePair)34 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)29 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)27 DefaultHttpChunk (org.jboss.netty.handler.codec.http.DefaultHttpChunk)25 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)23 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)22 BootstrapDatabaseTooOldException (com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException)20 DefaultHttpChunkTrailer (org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer)16 HttpChunkTrailer (org.jboss.netty.handler.codec.http.HttpChunkTrailer)16 ServerInfo (com.linkedin.databus.client.pub.ServerInfo)15 DatabusSubscription (com.linkedin.databus.core.data_model.DatabusSubscription)15 IOException (java.io.IOException)15 Logger (org.apache.log4j.Logger)14 InetSocketAddress (java.net.InetSocketAddress)13