Search in sources :

Example 16 with DbusEventBuffer

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

the class TestMultiConsumerCallback method test1ConsumerTimeout.

@Test
public void test1ConsumerTimeout() {
    LOG.info("\n\nstarting test1ConsumerTimeout()");
    //create dummy events
    Hashtable<Long, AtomicInteger> keyCounts = new Hashtable<Long, AtomicInteger>();
    DbusEventBuffer eventsBuf = new DbusEventBuffer(_generic100KBufferStaticConfig);
    eventsBuf.start(0);
    eventsBuf.startEvents();
    initBufferWithEvents(eventsBuf, 1, 2, (short) 1, keyCounts);
    initBufferWithEvents(eventsBuf, 3, 1, (short) 2, keyCounts);
    eventsBuf.endEvents(100L);
    DbusEventBuffer.DbusEventIterator iter = eventsBuf.acquireIterator("myIter1");
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    //skip over the first system event
    iter.next();
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    DbusEvent event1 = iter.next().createCopy();
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    DbusEvent event2 = iter.next().createCopy();
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    DbusEvent event3 = iter.next().createCopy();
    //make up some sources
    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);
    }
    //create the consumer mock up
    DatabusStreamConsumer mockConsumer1 = EasyMock.createStrictMock("consumer1", DatabusStreamConsumer.class);
    SelectingDatabusCombinedConsumer sdccMockConsumer1 = new SelectingDatabusCombinedConsumer(mockConsumer1);
    EasyMock.makeThreadSafe(mockConsumer1, true);
    DatabusV2ConsumerRegistration consumerReg = new DatabusV2ConsumerRegistration(sdccMockConsumer1, sources, null);
    EasyMock.expect(mockConsumer1.onStartConsumption()).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "startConsumption() called"), 150));
    EasyMock.expect(mockConsumer1.onStartDataEventSequence(null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartDataEventSequence() called"), 110));
    EasyMock.expect(mockConsumer1.onStartSource("source1", null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartSource() called"), 40));
    EasyMock.expect(mockConsumer1.onDataEvent(event1, null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onDataEvet(1) called"), 50));
    EasyMock.expect(mockConsumer1.onDataEvent(event2, null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onDataEvet(2) called"), 210));
    EasyMock.expect(mockConsumer1.onDataEvent(event1, null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onDataEvet(1) called"), 40));
    EasyMock.expect(mockConsumer1.onEndSource("source1", null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartSource() called"), 50));
    EasyMock.replay(mockConsumer1);
    ConsumerCallbackStats consumerStatsCollector = new ConsumerCallbackStats(1, "test", "test", true, false, null);
    UnifiedClientStats unifiedStatsCollector = new UnifiedClientStats(1, "test", "test.unified");
    //Create and fire up callbacks
    List<DatabusV2ConsumerRegistration> allRegistrations = Arrays.asList(consumerReg);
    MultiConsumerCallback callback = new MultiConsumerCallback(allRegistrations, Executors.newCachedThreadPool(), 100, new StreamConsumerCallbackFactory(consumerStatsCollector, unifiedStatsCollector), consumerStatsCollector, unifiedStatsCollector, null, null);
    callback.setSourceMap(sourcesMap);
    ConsumerCallbackResult startConsumptionRes = callback.onStartConsumption();
    Assert.assertTrue(ConsumerCallbackResult.isFailure(startConsumptionRes), "startConsumption() failed");
    ConsumerCallbackResult startWindowRes = callback.onStartDataEventSequence(null);
    Assert.assertTrue(ConsumerCallbackResult.isFailure(startWindowRes), "startDataEventSequence() failed");
    ConsumerCallbackResult startSourceRes = callback.onStartSource("source1", null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(startSourceRes), "startSources(source1) succeeded");
    ConsumerCallbackResult event1Res = callback.onDataEvent(event1, null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(event1Res), "onDataEvent(1) succeeded");
    ConsumerCallbackResult event2Res = callback.onDataEvent(event2, null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(event2Res), "onDataEvent(2) queued up");
    ConsumerCallbackResult event3Res = callback.onDataEvent(event1, null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(event3Res), "onDataEvent(1) queued up");
    ConsumerCallbackResult endSourceRes = callback.onEndSource("source1", null);
    Assert.assertTrue(ConsumerCallbackResult.isFailure(endSourceRes), "onEndSource fails because of timeout in onDataEvent(2)");
    EasyMock.reset(mockConsumer1);
    EasyMock.makeThreadSafe(mockConsumer1, true);
    EasyMock.expect(mockConsumer1.onStartSource("source2", null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartSource() called"), 150)).times(0, 1);
    EasyMock.expect(mockConsumer1.onDataEvent(event3, null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onDataEvet(3) called"), 40));
    EasyMock.expect(mockConsumer1.onEndSource("source2", null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartSource() called"), 60));
    EasyMock.replay(mockConsumer1);
    startSourceRes = callback.onStartSource("source2", null);
    Assert.assertTrue(ConsumerCallbackResult.isFailure(startSourceRes), "startSources(source2) fails");
    event1Res = callback.onDataEvent(event3, null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(event1Res), "onDataEvent(3) succeeded");
    endSourceRes = callback.onEndSource("source2", null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(endSourceRes), "onEndSource succeeds");
    long eventsErrProcessed = consumerStatsCollector.getNumErrorsProcessed();
    long totalEvents = consumerStatsCollector.getNumEventsReceived();
    long totalEventsProcessed = consumerStatsCollector.getNumEventsProcessed();
    System.out.println("eventsReceived = " + consumerStatsCollector.getNumEventsReceived() + " eventsProcessed=" + consumerStatsCollector.getNumEventsProcessed());
    System.out.println("eventsErrProcessed =" + consumerStatsCollector.getNumErrorsProcessed() + " eventsErrReceived=" + consumerStatsCollector.getNumErrorsReceived() + " totalEvents=" + consumerStatsCollector.getNumEventsReceived() + " totalEventsProcessed=" + totalEventsProcessed);
    //FIXME
    Assert.assertTrue(totalEvents >= totalEventsProcessed + eventsErrProcessed);
    Assert.assertTrue(eventsErrProcessed > 0);
    Assert.assertTrue(totalEventsProcessed < totalEvents);
//NOTE: We don't verify because all the canceled callbacks are not detected by EasyMock
//EasyMock.verify(mockConsumer1);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IdNamePair(com.linkedin.databus.core.util.IdNamePair) UnifiedClientStats(com.linkedin.databus.client.pub.mbean.UnifiedClientStats) DbusEvent(com.linkedin.databus.core.DbusEvent) DatabusStreamConsumer(com.linkedin.databus.client.pub.DatabusStreamConsumer) Hashtable(java.util.Hashtable) ConsumerCallbackStats(com.linkedin.databus.client.pub.mbean.ConsumerCallbackStats) ConsumerCallbackResult(com.linkedin.databus.client.pub.ConsumerCallbackResult) DbusEventBuffer(com.linkedin.databus.core.DbusEventBuffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) AfterTest(org.testng.annotations.AfterTest)

Example 17 with DbusEventBuffer

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

the class BootstrapPullThread method processBootstrapComplete.

/**
   * Update and persist checkpoint at the end of bootstrap phase so that
   * the online phase can continue from it.
   * @param cp
   * @throws IOException
   */
protected void processBootstrapComplete(Checkpoint cp, ConnectionState curState) throws IOException, DatabusException {
    logBootstrapPhase(DbusClientMode.BOOTSTRAP_CATCHUP, cp.getBootstrapSnapshotSourceIndex(), cp.getBootstrapCatchupSourceIndex());
    _log.info("Bootstrap got completed !! Checkpoint is :" + cp.toString());
    /*
     * DDS-989
     * WindowSCN need not match the bootstrapTargetSCN always when we are catching up multiple sources.
     * So set the windowSCN to be that of targetSCN as we are consistent as of targetSCN
     */
    cp.setWindowScn(cp.getBootstrapTargetScn());
    cp.setPrevScn(cp.getBootstrapTargetScn());
    cp.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
    // clear Bootstrap scns for future bootstraps
    cp.resetBootstrap();
    DbusEventBuffer eventBuffer = curState.getDataEventsBuffer();
    try {
        DbusEventInternalReadable cpEvent = getEventFactory().createCheckpointEvent(cp);
        boolean success = eventBuffer.injectEvent(cpEvent);
        if (!success) {
            _log.error("Unable to write bootstrap phase marker");
        } else {
            //TODO need real partition for partitioned bootstrap
            DbusEventInternalReadable eopEvent = curState.createEopEvent(cp, getEventFactory());
            success = eventBuffer.injectEvent(eopEvent);
            if (!success) {
                _log.error("Unable to write bootstrap EOP marker");
            }
        }
    } catch (InvalidEventException iee) {
        _log.error("Unable to write bootstrap phase marker", iee);
    }
    unlockV3Bootstrap();
}
Also used : DbusEventInternalReadable(com.linkedin.databus.core.DbusEventInternalReadable) InvalidEventException(com.linkedin.databus.core.InvalidEventException) DbusEventBuffer(com.linkedin.databus.core.DbusEventBuffer)

Example 18 with DbusEventBuffer

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

the class TestMultiConsumerCallback method test2ConsumerTimeout.

@Test
public void test2ConsumerTimeout() {
    Logger log = Logger.getLogger("TestMultiConsumerCallback.test2ConsumerTimeout");
    //Logger.getRootLogger().setLevel(Level.INFO);
    log.info("\n\nstarting test2ConsumerTimeout()");
    log.info("create dummy events");
    Hashtable<Long, AtomicInteger> keyCounts = new Hashtable<Long, AtomicInteger>();
    DbusEventBuffer eventsBuf = new DbusEventBuffer(_generic100KBufferStaticConfig);
    eventsBuf.start(0);
    eventsBuf.startEvents();
    initBufferWithEvents(eventsBuf, 1, 2, (short) 1, keyCounts);
    initBufferWithEvents(eventsBuf, 3, 1, (short) 2, keyCounts);
    eventsBuf.endEvents(100L);
    DbusEventBuffer.DbusEventIterator iter = eventsBuf.acquireIterator("myIter1");
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    //skip over the first system event
    iter.next();
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    DbusEvent event1 = iter.next().createCopy();
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    DbusEvent event2 = iter.next().createCopy();
    Assert.assertTrue(iter.hasNext(), "unable to read event");
    log.info("make up some sources");
    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);
    }
    log.info("create the consumer mock up");
    DatabusStreamConsumer mockConsumer1 = EasyMock.createStrictMock("consumer1", DatabusStreamConsumer.class);
    SelectingDatabusCombinedConsumer sdccMockConsumer1 = new SelectingDatabusCombinedConsumer(mockConsumer1);
    EasyMock.makeThreadSafe(mockConsumer1, true);
    DatabusV2ConsumerRegistration consumerReg = new DatabusV2ConsumerRegistration(sdccMockConsumer1, sources, null);
    EasyMock.expect(mockConsumer1.onStartConsumption()).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "startConsumption() called"), 1));
    EasyMock.expect(mockConsumer1.onStartDataEventSequence(null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartDataEventSequence() called"), 1));
    EasyMock.expect(mockConsumer1.onStartSource("source1", null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartSource() called"), 1));
    EasyMock.expect(mockConsumer1.onDataEvent(event1, null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onDataEvet(1) called"), 1));
    EasyMock.expect(mockConsumer1.onDataEvent(event2, null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onDataEvet(2) called"), 1));
    EasyMock.expect(mockConsumer1.onDataEvent(event1, null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onDataEvet(1) called"), 1));
    EasyMock.expect(mockConsumer1.onEndSource("source1", null)).andAnswer(new SleepingAnswer<ConsumerCallbackResult>(new LoggedAnswer<ConsumerCallbackResult>(ConsumerCallbackResult.SUCCESS, LOG, Level.DEBUG, "onStartSource() called"), 1));
    EasyMock.replay(mockConsumer1);
    ConsumerCallbackStats consumerStatsCollector = new ConsumerCallbackStats(1, "test", "test", true, false, null);
    UnifiedClientStats unifiedStatsCollector = new UnifiedClientStats(1, "test", "test.unified");
    log.info("Create and fire up callbacks");
    List<DatabusV2ConsumerRegistration> allRegistrations = Arrays.asList(consumerReg);
    TimingOutMultiConsumerCallback callback = new TimingOutMultiConsumerCallback(allRegistrations, Executors.newCachedThreadPool(), 300, new StreamConsumerCallbackFactory(consumerStatsCollector, unifiedStatsCollector), consumerStatsCollector, unifiedStatsCollector, 3);
    callback.setSourceMap(sourcesMap);
    ConsumerCallbackResult startConsumptionRes = callback.onStartConsumption();
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(startConsumptionRes), "startConsumption() succeeded: " + startConsumptionRes);
    ConsumerCallbackResult startWindowRes = callback.onStartDataEventSequence(null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(startWindowRes), "startDataEventSequence() succeeded");
    ConsumerCallbackResult startSourceRes = callback.onStartSource("source1", null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(startSourceRes), "startSources(source1) succeeded");
    ConsumerCallbackResult event1Res = callback.onDataEvent(event1, null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(event1Res), "onDataEvent(1) succeeded");
    ConsumerCallbackResult event2Res = callback.onDataEvent(event2, null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(event2Res), "onDataEvent(2) queued up");
    ConsumerCallbackResult event3Res = callback.onDataEvent(event1, null);
    Assert.assertTrue(ConsumerCallbackResult.isSuccess(event3Res), "onDataEvent(1) queued up");
    ConsumerCallbackResult endSourceRes = callback.onEndSource("source1", null);
    Assert.assertTrue(ConsumerCallbackResult.isFailure(endSourceRes), "onEndSource fails because of timeout in onDataEvent(2)");
    EasyMock.reset(mockConsumer1);
    log.info("test2ConsumerTimeout: end");
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Logger(org.apache.log4j.Logger) IdNamePair(com.linkedin.databus.core.util.IdNamePair) UnifiedClientStats(com.linkedin.databus.client.pub.mbean.UnifiedClientStats) DbusEvent(com.linkedin.databus.core.DbusEvent) DatabusStreamConsumer(com.linkedin.databus.client.pub.DatabusStreamConsumer) Hashtable(java.util.Hashtable) ConsumerCallbackStats(com.linkedin.databus.client.pub.mbean.ConsumerCallbackStats) ConsumerCallbackResult(com.linkedin.databus.client.pub.ConsumerCallbackResult) DbusEventBuffer(com.linkedin.databus.core.DbusEventBuffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) AfterTest(org.testng.annotations.AfterTest)

Example 19 with DbusEventBuffer

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

the class DatabusV2RegistrationImpl method start.

@Override
public synchronized boolean start() throws IllegalStateException, DatabusClientException {
    _log.info("Starting registration (" + toString() + ") !!");
    if (_state.isRunning()) {
        _log.info("Registration (" + _id + ") already started !!");
        return false;
    }
    if (_state != RegistrationState.REGISTERED)
        throw new IllegalStateException("Registration (" + _id + ") not in startable state !! Current State is :" + _state);
    if ((null == _sources) || (_sources.isEmpty()))
        throw new DatabusClientException("Registration (" + _id + ") does not have any sources to start !!");
    if ((null == _consumers) || (_consumers.isEmpty()))
        throw new DatabusClientException("Registration (" + _id + ") does not have any consumers to start !!");
    List<ServerInfo> relays = _client.getRelays();
    List<ServerInfo> bootstrapServers = _client.getBootstrapServices();
    List<DatabusCombinedConsumer> streamConsumers = new ArrayList<DatabusCombinedConsumer>();
    List<DatabusCombinedConsumer> bootstrapConsumers = new ArrayList<DatabusCombinedConsumer>();
    if ((null == relays) || (relays.isEmpty()))
        throw new DatabusClientException("No configured relays in the client to start");
    Set<ServerInfo> candidateRelays = new HashSet<ServerInfo>();
    for (ServerInfo s : relays) {
        if (canServe(s, _sources))
            candidateRelays.add(s);
    }
    if (candidateRelays.isEmpty())
        throw new DatabusClientException("No candidate relays for source : " + _sources);
    streamConsumers.addAll(_consumers);
    boolean canConsumerBootstrap = false;
    _streamConsumerRawRegistrations = new ArrayList<DatabusV2ConsumerRegistration>();
    _streamConsumerRawRegistrations.add(new DatabusV2ConsumerRegistration(streamConsumers, _sources, _filterConfig));
    for (DatabusCombinedConsumer c : _consumers) {
        if (c.canBootstrap()) {
            canConsumerBootstrap = true;
            bootstrapConsumers.add(c);
        }
    }
    boolean enableBootstrap = _client.getClientStaticConfig().getRuntime().getBootstrap().isEnabled();
    Set<ServerInfo> candidateBootstrapServers = new HashSet<ServerInfo>();
    if (enableBootstrap && canConsumerBootstrap) {
        if ((null == bootstrapServers) || (bootstrapServers.isEmpty()))
            throw new DatabusClientException("No configured bootstrap servers in the client to start");
        for (ServerInfo s : bootstrapServers) {
            if (canServe(s, _sources))
                candidateBootstrapServers.add(s);
        }
        if (candidateBootstrapServers.isEmpty())
            throw new DatabusClientException("No candidate bootstrap servers for source : " + _sources);
        _bootstrapConsumerRawRegistrations = new ArrayList<DatabusV2ConsumerRegistration>();
        ;
        _bootstrapConsumerRawRegistrations.add(new DatabusV2ConsumerRegistration(bootstrapConsumers, _sources, _filterConfig));
    }
    // All validations done. Setup and start
    initializeStatsCollectors();
    DatabusSourcesConnection.StaticConfig connConfig = _client.getClientStaticConfig().getConnection(_sources);
    if (null == connConfig)
        connConfig = _client.getClientStaticConfig().getConnectionDefaults();
    DbusEventBuffer eventBuffer = null;
    {
        DbusEventBuffer.StaticConfig cfg = connConfig.getEventBuffer();
        eventBuffer = new DbusEventBuffer(cfg.getMaxSize(), cfg.getMaxIndividualBufferSize(), cfg.getScnIndexSize(), cfg.getReadBufferSize(), cfg.getMaxEventSize(), cfg.getAllocationPolicy(), new File(cfg.getMmapDirectory().getAbsolutePath() + "_stream_" + _id), cfg.getQueuePolicy(), cfg.getTrace(), null, cfg.getAssertLevel(), cfg.getBufferRemoveWaitPeriod(), cfg.getRestoreMMappedBuffers(), cfg.getRestoreMMappedBuffersValidateEvents(), cfg.isEnableScnIndex(), _client.getEventFactory());
        eventBuffer.setDropOldEvents(true);
        eventBuffer.start(0);
    }
    DbusEventBuffer bootstrapBuffer = null;
    if (enableBootstrap && canConsumerBootstrap) {
        DbusEventBuffer.StaticConfig bstCfg = connConfig.getBstEventBuffer();
        bootstrapBuffer = new DbusEventBuffer(bstCfg.getMaxSize(), bstCfg.getMaxIndividualBufferSize(), bstCfg.getScnIndexSize(), bstCfg.getReadBufferSize(), bstCfg.getMaxEventSize(), bstCfg.getAllocationPolicy(), new File(bstCfg.getMmapDirectory().getAbsolutePath() + "_bootstrap_" + _id), bstCfg.getQueuePolicy(), bstCfg.getTrace(), null, bstCfg.getAssertLevel(), bstCfg.getBufferRemoveWaitPeriod(), bstCfg.getRestoreMMappedBuffers(), bstCfg.getRestoreMMappedBuffersValidateEvents(), bstCfg.isEnableScnIndex(), _client.getEventFactory());
        bootstrapBuffer.setDropOldEvents(false);
        bootstrapBuffer.start(0);
    }
    List<DatabusSubscription> subs = createSubscriptions(_sources);
    if (null != _checkpointPersistenceProvider && _client.getClientStaticConfig().getCheckpointPersistence().isClearBeforeUse()) {
        _log.info("Clearing checkpoint for sources :" + _sources + " with regId :" + _id);
        _checkpointPersistenceProvider.removeCheckpoint(_sources);
    }
    _sourcesConnection = createConnection(connConfig, subs, candidateRelays, candidateBootstrapServers, eventBuffer, bootstrapBuffer);
    _sourcesConnection.start();
    _state = RegistrationState.STARTED;
    _status.start();
    _state = RegistrationState.STARTED;
    return true;
}
Also used : DatabusV2ConsumerRegistration(com.linkedin.databus.client.consumer.DatabusV2ConsumerRegistration) ServerInfo(com.linkedin.databus.client.pub.ServerInfo) ArrayList(java.util.ArrayList) StaticConfig(com.linkedin.databus.client.DatabusSourcesConnection.StaticConfig) DatabusSubscription(com.linkedin.databus.core.data_model.DatabusSubscription) DatabusClientException(com.linkedin.databus.client.pub.DatabusClientException) DatabusSourcesConnection(com.linkedin.databus.client.DatabusSourcesConnection) DbusEventBuffer(com.linkedin.databus.core.DbusEventBuffer) StaticConfig(com.linkedin.databus.client.DatabusSourcesConnection.StaticConfig) File(java.io.File) DatabusCombinedConsumer(com.linkedin.databus.client.pub.DatabusCombinedConsumer) AbstractDatabusCombinedConsumer(com.linkedin.databus.client.consumer.AbstractDatabusCombinedConsumer) HashSet(java.util.HashSet)

Example 20 with DbusEventBuffer

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

the class MockBootstrapConnection method testBootstrapPendingEvent.

// Make sure that we suspend on error when we get the x-dbus-pending-size header with a size that is
// larger than our dbusevent size.
@Test
public void testBootstrapPendingEvent() throws Exception {
    List<String> sources = Arrays.asList("source1");
    Properties clientProps = new Properties();
    clientProps.setProperty("client.container.httpPort", "0");
    clientProps.setProperty("client.container.jmx.rmiEnabled", "false");
    clientProps.setProperty("client.runtime.bootstrap.enabled", "true");
    clientProps.setProperty("client.runtime.bootstrap.service(1).name", "bs1");
    clientProps.setProperty("client.runtime.bootstrap.service(1).host", "localhost");
    clientProps.setProperty("client.runtime.bootstrap.service(1).port", "10001");
    clientProps.setProperty("client.runtime.bootstrap.service(1).sources", "source1");
    clientProps.setProperty("client.runtime.relay(1).name", "relay1");
    clientProps.setProperty("client.runtime.relay(1).port", "10001");
    clientProps.setProperty("client.runtime.relay(1).sources", "source1");
    clientProps.setProperty("client.connectionDefaults.eventBuffer.maxSize", "100000");
    clientProps.setProperty("client.connectionDefaults.pullerRetries.maxRetryNum", "3");
    DatabusHttpClientImpl.Config clientConfBuilder = new DatabusHttpClientImpl.Config();
    ConfigLoader<DatabusHttpClientImpl.StaticConfig> configLoader = new ConfigLoader<DatabusHttpClientImpl.StaticConfig>("client.", clientConfBuilder);
    configLoader.loadConfig(clientProps);
    DatabusHttpClientImpl.StaticConfig clientConf = clientConfBuilder.build();
    DatabusSourcesConnection.StaticConfig srcConnConf = clientConf.getConnectionDefaults();
    DatabusHttpClientImpl client = new DatabusHttpClientImpl(clientConf);
    client.registerDatabusBootstrapListener(new LoggingConsumer(), null, "source1");
    Assert.assertNotNull(client, "client instantiation failed");
    DatabusHttpClientImpl.RuntimeConfig clientRtConf = clientConf.getRuntime().build();
    //we keep the index of the next server we expect to see
    AtomicInteger serverIdx = new AtomicInteger(-1);
    List<IdNamePair> sourcesResponse = new ArrayList<IdNamePair>();
    sourcesResponse.add(new IdNamePair(1L, "source1"));
    Map<Long, List<RegisterResponseEntry>> registerResponse = new HashMap<Long, List<RegisterResponseEntry>>();
    List<RegisterResponseEntry> regResponse = new ArrayList<RegisterResponseEntry>();
    regResponse.add(new RegisterResponseEntry(1L, (short) 1, SCHEMA$.toString()));
    registerResponse.put(1L, regResponse);
    ChunkedBodyReadableByteChannel channel = EasyMock.createMock(ChunkedBodyReadableByteChannel.class);
    // getting the pending-event-size header is called twice, once for checking and once for logging.
    EasyMock.expect(channel.getMetadata(DatabusHttpHeaders.DATABUS_PENDING_EVENT_SIZE)).andReturn("1000000").times(2);
    EasyMock.expect(channel.getMetadata("x-dbus-error-cause")).andReturn(null).times(2);
    EasyMock.expect(channel.getMetadata("x-dbus-error")).andReturn(null).times(2);
    EasyMock.replay(channel);
    DbusEventBuffer dbusBuffer = EasyMock.createMock(DbusEventBuffer.class);
    dbusBuffer.endEvents(false, -1, false, false, null);
    EasyMock.expectLastCall().anyTimes();
    EasyMock.expect(dbusBuffer.injectEvent(EasyMock.<DbusEventInternalReadable>notNull())).andReturn(true).anyTimes();
    EasyMock.expect(dbusBuffer.getEventSerializationVersion()).andReturn(DbusEventFactory.DBUS_EVENT_V1).anyTimes();
    EasyMock.expect(dbusBuffer.getMaxReadBufferCapacity()).andReturn(600).times(2);
    EasyMock.expect(dbusBuffer.getBufferFreeReadSpace()).andReturn(600000).times(2);
    EasyMock.expect(dbusBuffer.readEvents(EasyMock.<ReadableByteChannel>notNull())).andReturn(1).times(1);
    EasyMock.expect(dbusBuffer.readEvents(EasyMock.<ReadableByteChannel>notNull(), EasyMock.<List<InternalDatabusEventsListener>>notNull(), EasyMock.<DbusEventsStatisticsCollector>isNull())).andReturn(0).times(1);
    EasyMock.replay(dbusBuffer);
    ConnectionStateFactory connStateFactory = new ConnectionStateFactory(sources);
    //This guy succeeds on /sources but fails on /register
    MockBootstrapConnection mockSuccessConn = new MockBootstrapConnection(10, 10, channel, serverIdx, false);
    DatabusBootstrapConnectionFactory mockConnFactory = org.easymock.EasyMock.createMock("mockRelayFactory", DatabusBootstrapConnectionFactory.class);
    //each server should be tried MAX_RETRIES time until all retries are exhausted
    EasyMock.expect(mockConnFactory.createConnection(EasyMock.<ServerInfo>notNull(), EasyMock.<ActorMessageQueue>notNull(), EasyMock.<RemoteExceptionHandler>notNull())).andReturn(mockSuccessConn).anyTimes();
    List<DatabusSubscription> sourcesSubList = DatabusSubscription.createSubscriptionList(sources);
    DatabusSourcesConnection sourcesConn2 = EasyMock.createMock(DatabusSourcesConnection.class);
    EasyMock.expect(sourcesConn2.getSourcesNames()).andReturn(Arrays.asList("source1")).anyTimes();
    EasyMock.expect(sourcesConn2.getSubscriptions()).andReturn(sourcesSubList).anyTimes();
    EasyMock.expect(sourcesConn2.getConnectionConfig()).andReturn(srcConnConf).anyTimes();
    EasyMock.expect(sourcesConn2.getConnectionStatus()).andReturn(new DatabusComponentStatus("dummy")).anyTimes();
    EasyMock.expect(sourcesConn2.getLocalRelayCallsStatsCollector()).andReturn(null).anyTimes();
    EasyMock.expect(sourcesConn2.getRelayCallsStatsCollector()).andReturn(null).anyTimes();
    EasyMock.expect(sourcesConn2.getUnifiedClientStats()).andReturn(null).anyTimes();
    EasyMock.expect(sourcesConn2.getBootstrapConnFactory()).andReturn(mockConnFactory).anyTimes();
    EasyMock.expect(sourcesConn2.loadPersistentCheckpoint()).andReturn(null).anyTimes();
    EasyMock.expect(sourcesConn2.getDataEventsBuffer()).andReturn(dbusBuffer).anyTimes();
    EasyMock.expect(sourcesConn2.isBootstrapEnabled()).andReturn(true).anyTimes();
    EasyMock.expect(sourcesConn2.getBootstrapRegistrations()).andReturn(null).anyTimes();
    EasyMock.expect(sourcesConn2.getBootstrapServices()).andReturn(null).anyTimes();
    EasyMock.expect(sourcesConn2.getBootstrapEventsStatsCollector()).andReturn(null).anyTimes();
    EasyMock.makeThreadSafe(mockConnFactory, true);
    EasyMock.makeThreadSafe(sourcesConn2, true);
    EasyMock.replay(mockConnFactory);
    EasyMock.replay(sourcesConn2);
    BootstrapPullThread bsPuller = new BootstrapPullThread("RelayPuller", sourcesConn2, dbusBuffer, connStateFactory, clientRtConf.getBootstrap().getServicesSet(), new ArrayList<DbusKeyCompositeFilterConfig>(), clientConf.getPullerBufferUtilizationPct(), ManagementFactory.getPlatformMBeanServer(), new DbusEventV2Factory(), null, null);
    mockSuccessConn.setCallback(bsPuller);
    bsPuller.getComponentStatus().start();
    Checkpoint cp = _ckptHandlerSource1.createInitialBootstrapCheckpoint(null, 0L);
    //TODO remove
    //cp.setSnapshotSource("source1");
    //cp.setCatchupSource("source1");
    //cp.setConsumptionMode(DbusClientMode.BOOTSTRAP_SNAPSHOT);
    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_REQUEST_SUCCESS, "SUSPEND_ON_ERROR", null);
    EasyMock.verify(channel);
    EasyMock.verify(sourcesConn2);
    EasyMock.verify(dbusBuffer);
    EasyMock.verify(channel);
    EasyMock.verify(mockConnFactory);
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) DatabusComponentStatus(com.linkedin.databus.core.DatabusComponentStatus) HashMap(java.util.HashMap) DbusKeyCompositeFilterConfig(com.linkedin.databus2.core.filter.DbusKeyCompositeFilterConfig) ServerInfo(com.linkedin.databus.client.pub.ServerInfo) DbusEventInternalReadable(com.linkedin.databus.core.DbusEventInternalReadable) ArrayList(java.util.ArrayList) DbusEventsStatisticsCollector(com.linkedin.databus.core.monitoring.mbean.DbusEventsStatisticsCollector) Properties(java.util.Properties) IdNamePair(com.linkedin.databus.core.util.IdNamePair) ArrayList(java.util.ArrayList) List(java.util.List) RemoteExceptionHandler(com.linkedin.databus.client.netty.RemoteExceptionHandler) DbusKeyCompositeFilterConfig(com.linkedin.databus2.core.filter.DbusKeyCompositeFilterConfig) ConfigLoader(com.linkedin.databus.core.util.ConfigLoader) AbstractActorMessageQueue(com.linkedin.databus.core.async.AbstractActorMessageQueue) ActorMessageQueue(com.linkedin.databus.core.async.ActorMessageQueue) DatabusSubscription(com.linkedin.databus.core.data_model.DatabusSubscription) DbusEventBuffer(com.linkedin.databus.core.DbusEventBuffer) Checkpoint(com.linkedin.databus.core.Checkpoint) LoggingConsumer(com.linkedin.databus.client.consumer.LoggingConsumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RegisterResponseEntry(com.linkedin.databus2.core.container.request.RegisterResponseEntry) DbusEventV2Factory(com.linkedin.databus.core.DbusEventV2Factory) Test(org.testng.annotations.Test)

Aggregations

DbusEventBuffer (com.linkedin.databus.core.DbusEventBuffer)46 Test (org.testng.annotations.Test)29 ArrayList (java.util.ArrayList)22 HashMap (java.util.HashMap)19 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)19 Logger (org.apache.log4j.Logger)18 IdNamePair (com.linkedin.databus.core.util.IdNamePair)17 Checkpoint (com.linkedin.databus.core.Checkpoint)14 RegisterResponseEntry (com.linkedin.databus2.core.container.request.RegisterResponseEntry)12 ConditionCheck (com.linkedin.databus2.test.ConditionCheck)12 DbusEvent (com.linkedin.databus.core.DbusEvent)11 DbusEventsStatisticsCollector (com.linkedin.databus.core.monitoring.mbean.DbusEventsStatisticsCollector)11 Hashtable (java.util.Hashtable)11 DatabusStreamConsumer (com.linkedin.databus.client.pub.DatabusStreamConsumer)10 ServerInfo (com.linkedin.databus.client.pub.ServerInfo)10 DatabusSubscription (com.linkedin.databus.core.data_model.DatabusSubscription)9 AfterTest (org.testng.annotations.AfterTest)9 BeforeTest (org.testng.annotations.BeforeTest)9 InetSocketAddress (java.net.InetSocketAddress)7 NettyHttpDatabusRelayConnection (com.linkedin.databus.client.netty.NettyHttpDatabusRelayConnection)6