Search in sources :

Example 11 with DbusEventInternalReadable

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

the class DbusEventAppender method addBootstrapCheckpointEventToBuffer.

public void addBootstrapCheckpointEventToBuffer(long lastScn, long dataEventCount, int numCheckpoints) {
    Checkpoint cp = (_bootstrapCheckpoint == null) ? _bstCheckpointHandler.createInitialBootstrapCheckpoint(null, 0L) : _bootstrapCheckpoint;
    if (cp.getBootstrapStartScn() == Checkpoint.UNSET_BOOTSTRAP_START_SCN) {
        cp.setBootstrapStartScn(0L);
    }
    cp.setWindowScn(lastScn);
    cp.setSnapshotOffset(dataEventCount);
    DbusEventInternalReadable ev = new DbusEventV2Factory().createCheckpointEvent(cp);
    ByteBuffer b = ev.value();
    byte[] bytes = new byte[b.remaining()];
    b.get(bytes);
    for (int i = 0; i < numCheckpoints; ++i) {
        _buffer.appendEvent(new DbusEventKey(ev.key()), ev.physicalPartitionId(), ev.logicalPartitionId(), ev.timestampInNanos(), ev.srcId(), ev.schemaId(), bytes, false, _stats);
    }
}
Also used : Checkpoint(com.linkedin.databus.core.Checkpoint) DbusEventInternalReadable(com.linkedin.databus.core.DbusEventInternalReadable) DbusEventKey(com.linkedin.databus.core.DbusEventKey) DbusEventV2Factory(com.linkedin.databus.core.DbusEventV2Factory) ByteBuffer(java.nio.ByteBuffer) Checkpoint(com.linkedin.databus.core.Checkpoint)

Example 12 with DbusEventInternalReadable

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

the class MockBootstrapConnection method createBootstrapPullThread.

private BootstrapPullThread createBootstrapPullThread(boolean failBsConnection, boolean throwBSConnException, boolean muteTransition, boolean readDataThrowException, boolean readDataException, String exceptionName, int freeReadSpace, int numBytesRead, boolean phaseCompleted, long startScn, long targetScn, String... sourceNames) throws Exception {
    List<String> sources = Arrays.asList(sourceNames);
    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.bootstrap.service(2).name", "bs2");
    clientProps.setProperty("client.runtime.bootstrap.service(2).host", "localhost");
    clientProps.setProperty("client.runtime.bootstrap.service(2).port", "10002");
    clientProps.setProperty("client.runtime.bootstrap.service(2).sources", "source1");
    clientProps.setProperty("client.runtime.bootstrap.service(3).name", "bs3");
    clientProps.setProperty("client.runtime.bootstrap.service(3).host", "localhost");
    clientProps.setProperty("client.runtime.bootstrap.service(3).port", "10003");
    clientProps.setProperty("client.runtime.bootstrap.service(3).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.runtime.relay(2).name", "relay2");
    clientProps.setProperty("client.runtime.relay(2).port", "10002");
    clientProps.setProperty("client.runtime.relay(2).sources", "source1");
    clientProps.setProperty("client.runtime.relay(3).name", "relay3");
    clientProps.setProperty("client.runtime.relay(3).port", "10003");
    clientProps.setProperty("client.runtime.relay(3).sources", "source1");
    clientProps.setProperty("client.connectionDefaults.eventBuffer.maxSize", "100000");
    clientProps.setProperty("client.connectionDefaults.pullerRetries.maxRetryNum", "9");
    clientProps.setProperty("client.connectionDefaults.pullerRetries.sleepIncFactor", "1.0");
    clientProps.setProperty("client.connectionDefaults.pullerRetries.sleepIncDelta", "1");
    clientProps.setProperty("client.connectionDefaults.pullerRetries.initSleep", "1");
    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 ok");
    DatabusHttpClientImpl.RuntimeConfig clientRtConf = clientConf.getRuntime().build();
    //we keep the index of the next server we expect to see
    AtomicInteger serverIdx = new AtomicInteger(-1);
    //generate the order in which we should see the servers
    List<ServerInfo> relayOrder = new ArrayList<ServerInfo>(clientRtConf.getRelays());
    if (LOG.isInfoEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (ServerInfo serverInfo : relayOrder) {
            sb.append(serverInfo.getName());
            sb.append(" ");
        }
        LOG.info("Relay order:" + sb.toString());
    }
    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);
    if (!readDataException) {
        EasyMock.expect(channel.getMetadata("x-dbus-error-cause")).andReturn(null).anyTimes();
        EasyMock.expect(channel.getMetadata("x-dbus-req-id")).andReturn(null).anyTimes();
        EasyMock.expect(channel.getMetadata("x-dbus-error")).andReturn(null).anyTimes();
    } else {
        EasyMock.expect(channel.getMetadata("x-dbus-error-cause")).andReturn(exceptionName).anyTimes();
        EasyMock.expect(channel.getMetadata("x-dbus-req-id")).andReturn(exceptionName).anyTimes();
        EasyMock.expect(channel.getMetadata("x-dbus-error")).andReturn(exceptionName).anyTimes();
    }
    if (phaseCompleted)
        EasyMock.expect(channel.getMetadata("PhaseCompleted")).andReturn("true").anyTimes();
    else
        EasyMock.expect(channel.getMetadata("PhaseCompleted")).andReturn(null).anyTimes();
    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.readEvents(EasyMock.<ReadableByteChannel>notNull(), org.easymock.EasyMock.<List<InternalDatabusEventsListener>>notNull(), org.easymock.EasyMock.<DbusEventsStatisticsCollector>isNull())).andReturn(numBytesRead).anyTimes();
    if (readDataThrowException) {
        EasyMock.expect(dbusBuffer.readEvents(EasyMock.<ReadableByteChannel>notNull())).andThrow(new RuntimeException("dummy")).anyTimes();
    } else {
        EasyMock.expect(dbusBuffer.readEvents(EasyMock.<ReadableByteChannel>notNull())).andReturn(numBytesRead).anyTimes();
    }
    EasyMock.expect(dbusBuffer.acquireIterator(EasyMock.<String>notNull())).andReturn(null).anyTimes();
    dbusBuffer.waitForFreeSpace((int) (10000 * 100.0 / clientConf.getPullerBufferUtilizationPct()));
    EasyMock.expectLastCall().anyTimes();
    EasyMock.expect(dbusBuffer.getBufferFreeReadSpace()).andReturn(freeReadSpace).anyTimes();
    EasyMock.replay(dbusBuffer);
    //This guy succeeds on /sources but fails on /register
    MockBootstrapConnection mockSuccessConn = new MockBootstrapConnection(startScn, targetScn, channel, serverIdx, muteTransition);
    DatabusBootstrapConnectionFactory mockConnFactory = org.easymock.EasyMock.createMock("mockRelayFactory", DatabusBootstrapConnectionFactory.class);
    if (throwBSConnException) {
        EasyMock.expect(mockConnFactory.createConnection(EasyMock.<ServerInfo>notNull(), EasyMock.<ActorMessageQueue>notNull(), EasyMock.<RemoteExceptionHandler>notNull())).andThrow(new RuntimeException("Mock Error")).anyTimes();
    } else if (failBsConnection) {
        EasyMock.expect(mockConnFactory.createConnection(EasyMock.<ServerInfo>notNull(), EasyMock.<ActorMessageQueue>notNull(), EasyMock.<RemoteExceptionHandler>notNull())).andReturn(null).anyTimes();
    } else {
        EasyMock.expect(mockConnFactory.createConnection(EasyMock.<ServerInfo>notNull(), EasyMock.<ActorMessageQueue>notNull(), EasyMock.<RemoteExceptionHandler>notNull())).andReturn(mockSuccessConn).anyTimes();
    }
    List<DatabusSubscription> sourcesSubList = DatabusSubscription.createSubscriptionList(sources);
    // Create ConnectionState
    ConnectionStateFactory connStateFactory = new ConnectionStateFactory(sources);
    // Mock Bootstrap Puller
    RelayPullThread mockRelayPuller = EasyMock.createMock("rpt", RelayPullThread.class);
    mockRelayPuller.enqueueMessage(EasyMock.notNull());
    EasyMock.expectLastCall().anyTimes();
    // Mock Relay Dispatcher
    BootstrapDispatcher mockDispatcher = EasyMock.createMock("rd", BootstrapDispatcher.class);
    mockDispatcher.enqueueMessage(EasyMock.notNull());
    EasyMock.expectLastCall().anyTimes();
    //Set up mock for sources connection
    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.expect(sourcesConn2.getRelayPullThread()).andReturn(mockRelayPuller).anyTimes();
    EasyMock.expect(sourcesConn2.getBootstrapDispatcher()).andReturn(mockDispatcher).anyTimes();
    EasyMock.makeThreadSafe(mockConnFactory, true);
    EasyMock.makeThreadSafe(mockDispatcher, true);
    EasyMock.makeThreadSafe(mockRelayPuller, true);
    EasyMock.makeThreadSafe(sourcesConn2, true);
    EasyMock.replay(mockConnFactory);
    EasyMock.replay(sourcesConn2);
    EasyMock.replay(mockDispatcher);
    EasyMock.replay(mockRelayPuller);
    BootstrapPullThread bsPuller = new BootstrapPullThread("RelayPuller", sourcesConn2, dbusBuffer, connStateFactory, clientRtConf.getBootstrap().getServicesSet(), new ArrayList<DbusKeyCompositeFilterConfig>(), clientConf.getPullerBufferUtilizationPct(), null, new DbusEventV2Factory(), null, null);
    mockSuccessConn.setCallback(bsPuller);
    return bsPuller;
}
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) 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)

Example 13 with DbusEventInternalReadable

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

the class BootstrapPullThread method doSetResumeCheckpoint.

private void doSetResumeCheckpoint(CheckpointMessage cpMessage) {
    _resumeCkpt = cpMessage.getCheckpoint();
    if (null != _resumeCkpt) {
        DbusEventInternalReadable cpEvent = getEventFactory().createCheckpointEvent(_resumeCkpt);
        boolean success;
        try {
            success = _currentState.getDataEventsBuffer().injectEvent(cpEvent);
        } catch (InvalidEventException e) {
            _log.error("unable to create checkpoint event for checkpoint " + _resumeCkpt + "; error: " + e, e);
            success = false;
        }
        if (!success) {
            _log.error("Unable to write bootstrap phase marker");
        }
    }
    _log.info("resume checkpoint: " + _resumeCkpt);
}
Also used : DbusEventInternalReadable(com.linkedin.databus.core.DbusEventInternalReadable) InvalidEventException(com.linkedin.databus.core.InvalidEventException)

Example 14 with DbusEventInternalReadable

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

the class BootstrapPullThread method doReadBootstrapEvents.

protected void doReadBootstrapEvents(ConnectionState curState) {
    boolean success = true;
    boolean debugEnabled = _log.isDebugEnabled();
    boolean enqueueMessage = true;
    try {
        Checkpoint cp = curState.getCheckpoint();
        DbusEventBuffer eventBuffer = curState.getDataEventsBuffer();
        if (debugEnabled)
            _log.debug("Sending bootstrap events to buffer");
        //eventBuffer.startEvents();
        DbusEventInternalReadable cpEvent = getEventFactory().createCheckpointEvent(cp);
        byte[] cpEventBytes = new byte[cpEvent.size()];
        if (debugEnabled) {
            _log.debug("checkpoint event size: " + cpEventBytes.length);
            _log.debug("checkpoint event:" + cpEvent.toString());
        }
        cpEvent.getRawBytes().get(cpEventBytes);
        ByteArrayInputStream cpIs = new ByteArrayInputStream(cpEventBytes);
        ReadableByteChannel cpRbc = Channels.newChannel(cpIs);
        UnifiedClientStats unifiedClientStats = _sourcesConn.getUnifiedClientStats();
        sendHeartbeat(unifiedClientStats);
        int ecnt = eventBuffer.readEvents(cpRbc);
        success = (ecnt > 0);
        if (!success) {
            _log.error("Unable to write bootstrap phase marker");
        } else {
            ChunkedBodyReadableByteChannel readChannel = curState.getReadChannel();
            String remoteErrorName = RemoteExceptionHandler.getExceptionName(readChannel);
            Throwable remoteError = _remoteExceptionHandler.getException(readChannel);
            if (null != remoteError && remoteError instanceof BootstrapDatabaseTooOldException) {
                _log.error("Bootstrap database is too old!");
                _remoteExceptionHandler.handleException(remoteError);
                curState.switchToStreamResponseError();
            } else if (null != remoteErrorName) {
                //remote processing error
                _log.error("read events error: " + RemoteExceptionHandler.getExceptionMessage(readChannel));
                curState.switchToStreamResponseError();
            } else {
                sendHeartbeat(unifiedClientStats);
                int eventsNum = eventBuffer.readEvents(readChannel, curState.getListeners(), _sourcesConn.getBootstrapEventsStatsCollector());
                if (eventsNum == 0 && _remoteExceptionHandler.getPendingEventSize(readChannel) > eventBuffer.getMaxReadBufferCapacity()) {
                    String err = "ReadBuffer max capacity(" + eventBuffer.getMaxReadBufferCapacity() + ") is less than event size(" + _remoteExceptionHandler.getPendingEventSize(readChannel) + "). Increase databus.client.connectionDefaults.bstEventBuffer.maxEventSize and restart.";
                    _log.fatal(err);
                    enqueueMessage(LifecycleMessage.createSuspendOnErroMessage(new PendingEventTooLargeException(err)));
                    return;
                } else {
                    resetServerRetries();
                    if (debugEnabled)
                        _log.debug("Sending events to buffer");
                    numEventsInCurrentState += eventsNum;
                    _log.info("Bootstrap events read so far: " + numEventsInCurrentState);
                    String status = readChannel.getMetadata("PhaseCompleted");
                    final BootstrapCheckpointHandler ckptHandler = curState.getBstCheckpointHandler();
                    if (status != null) {
                        // set status in checkpoint to indicate that we are done with the current source
                        if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_CATCHUP) {
                            ckptHandler.finalizeCatchupPhase(cp);
                        } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_SNAPSHOT) {
                            ckptHandler.finalizeSnapshotPhase(cp);
                        } else {
                            throw new RuntimeException("Invalid bootstrap phase: " + cp.getConsumptionMode());
                        }
                        _log.info("Bootstrap events read :" + numEventsInCurrentState + " during phase:" + cp.getConsumptionMode() + " [" + cp.getBootstrapSnapshotSourceIndex() + "," + cp.getBootstrapCatchupSourceIndex() + "]");
                        numEventsInCurrentState = 0;
                    } else {
                        // question: how is snapshotOffset maintained in ckpt
                        if (eventsNum > 0) {
                            cp.bootstrapCheckPoint();
                        }
                    }
                    curState.switchToStreamResponseDone();
                }
            }
        }
    } catch (InterruptedException ie) {
        _log.error("interupted", ie);
        success = false;
    } catch (InvalidEventException e) {
        _log.error("error reading events from server: " + e.getMessage(), e);
        success = false;
    } catch (RuntimeException e) {
        _log.error("runtime error reading events from server: " + e.getMessage(), e);
        success = false;
    }
    if (toTearConnAfterHandlingResponse()) {
        tearConnectionAndEnqueuePickServer();
        enqueueMessage = false;
    } else if (!success) {
        curState.switchToPickServer();
    }
    if (enqueueMessage)
        enqueueMessage(curState);
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) UnifiedClientStats(com.linkedin.databus.client.pub.mbean.UnifiedClientStats) PendingEventTooLargeException(com.linkedin.databus.core.PendingEventTooLargeException) DbusEventInternalReadable(com.linkedin.databus.core.DbusEventInternalReadable) Checkpoint(com.linkedin.databus.core.Checkpoint) BootstrapCheckpointHandler(com.linkedin.databus.core.BootstrapCheckpointHandler) DbusEventBuffer(com.linkedin.databus.core.DbusEventBuffer) BootstrapDatabaseTooOldException(com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException) Checkpoint(com.linkedin.databus.core.Checkpoint) ByteArrayInputStream(java.io.ByteArrayInputStream) InvalidEventException(com.linkedin.databus.core.InvalidEventException)

Aggregations

DbusEventInternalReadable (com.linkedin.databus.core.DbusEventInternalReadable)14 Checkpoint (com.linkedin.databus.core.Checkpoint)4 DbusEventBuffer (com.linkedin.databus.core.DbusEventBuffer)4 InvalidEventException (com.linkedin.databus.core.InvalidEventException)4 ByteBuffer (java.nio.ByteBuffer)4 ReadableByteChannel (java.nio.channels.ReadableByteChannel)4 DbusEventKey (com.linkedin.databus.core.DbusEventKey)3 DbusEventV2Factory (com.linkedin.databus.core.DbusEventV2Factory)3 LoggingConsumer (com.linkedin.databus.client.consumer.LoggingConsumer)2 RemoteExceptionHandler (com.linkedin.databus.client.netty.RemoteExceptionHandler)2 ServerInfo (com.linkedin.databus.client.pub.ServerInfo)2 DatabusComponentStatus (com.linkedin.databus.core.DatabusComponentStatus)2 AbstractActorMessageQueue (com.linkedin.databus.core.async.AbstractActorMessageQueue)2 ActorMessageQueue (com.linkedin.databus.core.async.ActorMessageQueue)2 DatabusSubscription (com.linkedin.databus.core.data_model.DatabusSubscription)2 DbusEventsStatisticsCollector (com.linkedin.databus.core.monitoring.mbean.DbusEventsStatisticsCollector)2 ConfigLoader (com.linkedin.databus.core.util.ConfigLoader)2 IdNamePair (com.linkedin.databus.core.util.IdNamePair)2 BootstrapDatabaseTooOldException (com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException)2 RegisterResponseEntry (com.linkedin.databus2.core.container.request.RegisterResponseEntry)2