use of com.linkedin.databus.core.DbusEventBufferMult.PhysicalPartitionKey in project databus by linkedin.
the class TestDbusEventBufferMult method testEnableStreamFromLatest.
@Test
public void testEnableStreamFromLatest() throws DatabusException, IOException {
CheckpointMult cp = null;
Collection<PhysicalPartitionKey> phyPartitions = new ArrayList<PhysicalPartitionKey>();
DbusEventBufferMult db = new DbusEventBufferMult();
DbusEventBufferMult.DbusEventBufferBatchReader dbr = db.new DbusEventBufferBatchReader(cp, phyPartitions, null);
// Return true only once if streamFromLatest == true
PhysicalPartitionKey pk = new PhysicalPartitionKey();
Set<PhysicalPartitionKey> sls = new HashSet<PhysicalPartitionKey>();
boolean streamFromLatestScn = true;
// The set is initially empty - meaning none of the partitions have been served
Assert.assertTrue(dbr.computeStreamFromLatestScnForPartition(pk, sls, streamFromLatestScn));
Assert.assertEquals(sls.size(), 1);
Assert.assertFalse(dbr.computeStreamFromLatestScnForPartition(pk, sls, streamFromLatestScn));
sls.clear();
// Check null input
Assert.assertFalse(dbr.computeStreamFromLatestScnForPartition(null, sls, streamFromLatestScn));
streamFromLatestScn = false;
// The set is initially empty - meaning none of the partitions have been served
Assert.assertFalse(dbr.computeStreamFromLatestScnForPartition(pk, sls, streamFromLatestScn));
Assert.assertEquals(sls.size(), 0);
Assert.assertFalse(dbr.computeStreamFromLatestScnForPartition(pk, sls, streamFromLatestScn));
Assert.assertEquals(sls.size(), 0);
// Check null input
Assert.assertFalse(dbr.computeStreamFromLatestScnForPartition(null, sls, streamFromLatestScn));
return;
}
use of com.linkedin.databus.core.DbusEventBufferMult.PhysicalPartitionKey in project databus by linkedin.
the class HttpRelay method dropDatabase.
@Override
public void dropDatabase(String dbName) throws DatabusException {
_schemaRegistryService.dropDatabase(dbName);
DbusEventBufferMult eventMult = getEventBuffer();
/*
* Close the buffers
*/
for (DbusEventBuffer dBuf : eventMult.bufIterable()) {
PhysicalPartition pp = dBuf.getPhysicalPartition();
if (pp.getName().equals(dbName)) {
dBuf.closeBuffer(false);
dBuf.removeMMapFiles();
PhysicalPartitionKey pKey = new PhysicalPartitionKey(pp);
eventMult.removeBuffer(pKey, null);
}
}
eventMult.deallocateRemovedBuffers(true);
return;
}
use of com.linkedin.databus.core.DbusEventBufferMult.PhysicalPartitionKey in project databus by linkedin.
the class PhysicalBuffersRequestProcessor method process.
@Override
public DatabusRequest process(DatabusRequest request) throws IOException, RequestProcessingException {
ObjectMapper mapper = new ObjectMapper();
boolean pretty = request.getParams().getProperty("pretty") != null;
// create pretty or regular writer
ObjectWriter writer = pretty ? mapper.defaultPrettyPrintingWriter() : mapper.writer();
StringWriter out = new StringWriter(10240);
DbusEventBufferMult multBuf = _relay.getEventBuffer();
Set<PhysicalPartitionKey> keys = multBuf.getAllPhysicalPartitionKeys();
// creat map to output partId=>PhysicalSources...
Map<PhysicalPartition, Set<PhysicalSource>> map = new HashMap<PhysicalPartition, Set<PhysicalSource>>(keys.size());
for (PhysicalPartitionKey key : keys) {
Set<PhysicalSource> set = multBuf.getPhysicalSourcesForPartition(key.getPhysicalPartition());
map.put(key.getPhysicalPartition(), set);
}
if (keys.isEmpty()) {
writer.writeValue(out, new HashSet<PhysicalPartition>());
} else {
writer.writeValue(out, map);
}
byte[] resultBytes = out.toString().getBytes(Charset.defaultCharset());
request.getResponseContent().write(ByteBuffer.wrap(resultBytes));
return request;
}
use of com.linkedin.databus.core.DbusEventBufferMult.PhysicalPartitionKey in project databus by linkedin.
the class ReadEventsRequestProcessor method process.
@Override
public DatabusRequest process(DatabusRequest request) throws IOException, RequestProcessingException, DatabusException {
boolean isDebug = LOG.isDebugEnabled();
try {
ObjectMapper objMapper = new ObjectMapper();
String checkpointString = request.getParams().getProperty(CHECKPOINT_PARAM, null);
String checkpointStringMult = request.getParams().getProperty(CHECKPOINT_PARAM_MULT, null);
int fetchSize = request.getRequiredIntParam(FETCH_SIZE_PARAM);
String formatStr = request.getRequiredStringParam(OUTPUT_FORMAT_PARAM);
Encoding enc = Encoding.valueOf(formatStr.toUpperCase());
String sourcesListStr = request.getParams().getProperty(SOURCES_PARAM, null);
String subsStr = request.getParams().getProperty(SUBS_PARAM, null);
String partitionInfoStr = request.getParams().getProperty(PARTITION_INFO_STRING);
String streamFromLatestSCNStr = request.getParams().getProperty(STREAM_FROM_LATEST_SCN);
String clientMaxEventVersionStr = request.getParams().getProperty(DatabusHttpHeaders.MAX_EVENT_VERSION);
int clientEventVersion = (clientMaxEventVersionStr != null) ? Integer.parseInt(clientMaxEventVersionStr) : DbusEventFactory.DBUS_EVENT_V1;
if (clientEventVersion < 0 || clientEventVersion == 1 || clientEventVersion > DbusEventFactory.DBUS_EVENT_V2) {
throw new InvalidRequestParamValueException(COMMAND_NAME, DatabusHttpHeaders.MAX_EVENT_VERSION, clientMaxEventVersionStr);
}
if (null == sourcesListStr && null == subsStr) {
throw new InvalidRequestParamValueException(COMMAND_NAME, SOURCES_PARAM + "|" + SUBS_PARAM, "null");
}
//TODO for now we separte the code paths to limit the impact on existing Databus 2 deployments (DDSDBUS-79)
//We have to get rid of this eventually and have a single data path.
boolean v2Mode = null == subsStr;
DbusKeyCompositeFilter keyCompositeFilter = null;
if (null != partitionInfoStr) {
try {
Map<Long, DbusKeyFilter> fMap = KeyFilterConfigJSONFactory.parseSrcIdFilterConfigMap(partitionInfoStr);
keyCompositeFilter = new DbusKeyCompositeFilter();
keyCompositeFilter.setFilterMap(fMap);
if (isDebug)
LOG.debug("keyCompositeFilter is :" + keyCompositeFilter);
} catch (Exception ex) {
String msg = "Got exception while parsing partition Configs. PartitionInfo is:" + partitionInfoStr;
LOG.error(msg, ex);
throw new InvalidRequestParamValueException(COMMAND_NAME, PARTITION_INFO_STRING, partitionInfoStr);
}
}
boolean streamFromLatestSCN = false;
if (null != streamFromLatestSCNStr) {
streamFromLatestSCN = Boolean.valueOf(streamFromLatestSCNStr);
}
long start = System.currentTimeMillis();
List<DatabusSubscription> subs = null;
//parse source ids
SourceIdNameRegistry srcRegistry = _relay.getSourcesIdNameRegistry();
HashSet<Integer> sourceIds = new HashSet<Integer>();
if (null != sourcesListStr) {
String[] sourcesList = sourcesListStr.split(",");
for (String sourceId : sourcesList) {
try {
Integer srcId = Integer.valueOf(sourceId);
sourceIds.add(srcId);
} catch (NumberFormatException nfe) {
HttpStatisticsCollector globalHttpStatsCollector = _relay.getHttpStatisticsCollector();
if (null != globalHttpStatsCollector) {
globalHttpStatsCollector.registerInvalidStreamRequest();
}
throw new InvalidRequestParamValueException(COMMAND_NAME, SOURCES_PARAM, sourceId);
}
}
}
//process explicit subscriptions and generate respective logical partition filters
NavigableSet<PhysicalPartitionKey> ppartKeys = null;
if (null != subsStr) {
List<DatabusSubscription.Builder> subsBuilder = null;
subsBuilder = objMapper.readValue(subsStr, new TypeReference<List<DatabusSubscription.Builder>>() {
});
subs = new ArrayList<DatabusSubscription>(subsBuilder.size());
for (DatabusSubscription.Builder subBuilder : subsBuilder) {
subs.add(subBuilder.build());
}
ppartKeys = new TreeSet<PhysicalPartitionKey>();
for (DatabusSubscription sub : subs) {
PhysicalPartition ppart = sub.getPhysicalPartition();
if (ppart.isAnyPartitionWildcard()) {
ppartKeys = _eventBuffer.getAllPhysicalPartitionKeys();
break;
} else {
ppartKeys.add(new PhysicalPartitionKey(ppart));
}
}
}
// Need to make sure that we don't have tests that send requests in this form.
if (subs != null && checkpointStringMult == null && checkpointString != null) {
throw new RequestProcessingException("Both Subscriptions and CheckpointMult should be present");
}
//convert source ids into subscriptions
if (null == subs)
subs = new ArrayList<DatabusSubscription>();
for (Integer srcId : sourceIds) {
LogicalSource lsource = srcRegistry.getSource(srcId);
if (lsource == null)
throw new InvalidRequestParamValueException(COMMAND_NAME, SOURCES_PARAM, srcId.toString());
if (isDebug)
LOG.debug("registry returns " + lsource + " for srcid=" + srcId);
DatabusSubscription newSub = DatabusSubscription.createSimpleSourceSubscription(lsource);
subs.add(newSub);
}
DbusFilter ppartFilters = null;
if (subs.size() > 0) {
try {
ppartFilters = _eventBuffer.constructFilters(subs);
} catch (DatabusException de) {
throw new RequestProcessingException("unable to generate physical partitions filters:" + de.getMessage(), de);
}
}
ConjunctionDbusFilter filters = new ConjunctionDbusFilter();
// Source filter comes first
if (v2Mode)
filters.addFilter(new SourceDbusFilter(sourceIds));
else if (null != ppartFilters)
filters.addFilter(ppartFilters);
/*
// Key range filter comes next
if ((keyMin >0) && (keyMax > 0))
{
filters.addFilter(new KeyRangeFilter(keyMin, keyMax));
}
*/
if (null != keyCompositeFilter) {
filters.addFilter(keyCompositeFilter);
}
// need to update registerStreamRequest to support Mult checkpoint TODO (DDSDBUS-80)
// temp solution
// 3 options:
// 1. checkpointStringMult not null - generate checkpoint from it
// 2. checkpointStringMult null, checkpointString not null - create empty CheckpointMult
// and add create Checkpoint(checkpointString) and add it to cpMult;
// 3 both are null - create empty CheckpointMult and add empty Checkpoint to it for each ppartition
PhysicalPartition pPartition;
Checkpoint cp = null;
CheckpointMult cpMult = null;
if (checkpointStringMult != null) {
try {
cpMult = new CheckpointMult(checkpointStringMult);
} catch (InvalidParameterSpecException e) {
LOG.error("Invalid CheckpointMult:" + checkpointStringMult, e);
throw new InvalidRequestParamValueException("stream", "CheckpointMult", checkpointStringMult);
}
} else {
// there is no checkpoint - create an empty one
cpMult = new CheckpointMult();
Iterator<Integer> it = sourceIds.iterator();
while (it.hasNext()) {
Integer srcId = it.next();
pPartition = _eventBuffer.getPhysicalPartition(srcId);
if (pPartition == null)
throw new RequestProcessingException("unable to find physical partitions for source:" + srcId);
if (checkpointString != null) {
cp = new Checkpoint(checkpointString);
} else {
cp = new Checkpoint();
cp.setFlexible();
}
cpMult.addCheckpoint(pPartition, cp);
}
}
if (isDebug)
LOG.debug("checkpointStringMult = " + checkpointStringMult + ";singlecheckpointString=" + checkpointString + ";CPM=" + cpMult);
// of the server context.
if (cpMult.getCursorPartition() == null) {
cpMult.setCursorPartition(request.getCursorPartition());
}
if (isDebug) {
if (cpMult.getCursorPartition() != null) {
LOG.debug("Using physical paritition cursor " + cpMult.getCursorPartition());
}
}
// for registerStreamRequest we need a single Checkpoint (TODO - fix it) (DDSDBUS-81)
if (cp == null) {
Iterator<Integer> it = sourceIds.iterator();
if (it.hasNext()) {
Integer srcId = it.next();
pPartition = _eventBuffer.getPhysicalPartition(srcId);
cp = cpMult.getCheckpoint(pPartition);
} else {
cp = new Checkpoint();
cp.setFlexible();
}
}
if (null != checkpointString && isDebug)
LOG.debug("About to stream from cp: " + checkpointString.toString());
HttpStatisticsCollector globalHttpStatsCollector = _relay.getHttpStatisticsCollector();
HttpStatisticsCollector connHttpStatsCollector = null;
if (null != globalHttpStatsCollector) {
connHttpStatsCollector = (HttpStatisticsCollector) request.getParams().get(globalHttpStatsCollector.getName());
}
if (null != globalHttpStatsCollector)
globalHttpStatsCollector.registerStreamRequest(cp, sourceIds);
StatsCollectors<DbusEventsStatisticsCollector> statsCollectors = _relay.getOutBoundStatsCollectors();
try {
DbusEventBufferBatchReadable bufRead = v2Mode ? _eventBuffer.getDbusEventBufferBatchReadable(sourceIds, cpMult, statsCollectors) : _eventBuffer.getDbusEventBufferBatchReadable(cpMult, ppartKeys, statsCollectors);
int eventsRead = 0;
int minPendingEventSize = 0;
StreamEventsResult result = null;
bufRead.setClientMaxEventVersion(clientEventVersion);
if (v2Mode) {
result = bufRead.streamEvents(streamFromLatestSCN, fetchSize, request.getResponseContent(), enc, filters);
eventsRead = result.getNumEventsStreamed();
minPendingEventSize = result.getSizeOfPendingEvent();
if (isDebug) {
LOG.debug("Process: streamed " + eventsRead + " from sources " + Arrays.toString(sourceIds.toArray()));
//can be used for debugging to stream from a cp
LOG.debug("CP=" + cpMult);
}
//if (null != statsCollectors) statsCollectors.mergeStatsCollectors();
} else {
result = bufRead.streamEvents(streamFromLatestSCN, fetchSize, request.getResponseContent(), enc, filters);
eventsRead = result.getNumEventsStreamed();
minPendingEventSize = result.getSizeOfPendingEvent();
if (isDebug)
LOG.debug("Process: streamed " + eventsRead + " with subscriptions " + subs);
cpMult = bufRead.getCheckpointMult();
if (cpMult != null) {
request.setCursorPartition(cpMult.getCursorPartition());
}
}
if (eventsRead == 0 && minPendingEventSize > 0) {
// Append a header to indicate to the client that we do have at least one event to
// send, but it is too large to fit into client's offered buffer.
request.getResponseContent().addMetadata(DatabusHttpHeaders.DATABUS_PENDING_EVENT_SIZE, minPendingEventSize);
LOG.debug("Returning 0 events but have pending event of size " + minPendingEventSize);
}
} catch (ScnNotFoundException snfe) {
if (null != globalHttpStatsCollector) {
globalHttpStatsCollector.registerScnNotFoundStreamResponse();
}
throw new RequestProcessingException(snfe);
} catch (OffsetNotFoundException snfe) {
LOG.error("OffsetNotFound", snfe);
if (null != globalHttpStatsCollector) {
globalHttpStatsCollector.registerScnNotFoundStreamResponse();
}
throw new RequestProcessingException(snfe);
}
if (null != connHttpStatsCollector) {
connHttpStatsCollector.registerStreamResponse(System.currentTimeMillis() - start);
globalHttpStatsCollector.merge(connHttpStatsCollector);
connHttpStatsCollector.reset();
} else if (null != globalHttpStatsCollector) {
globalHttpStatsCollector.registerStreamResponse(System.currentTimeMillis() - start);
}
} catch (InvalidRequestParamValueException e) {
HttpStatisticsCollector globalHttpStatsCollector = _relay.getHttpStatisticsCollector();
if (null != globalHttpStatsCollector) {
globalHttpStatsCollector.registerInvalidStreamRequest();
}
throw e;
}
return request;
}
use of com.linkedin.databus.core.DbusEventBufferMult.PhysicalPartitionKey in project databus by linkedin.
the class TestDbusEventBufferMult method testMultiPPartionStreamFromLatest.
@Test
public void testMultiPPartionStreamFromLatest() throws Exception {
createBufMult();
PhysicalPartition[] p = { _pConfigs[0].getPhysicalPartition(), _pConfigs[1].getPhysicalPartition(), _pConfigs[2].getPhysicalPartition() };
//generate a bunch of windows for 3 partitions
int windowsNum = 10;
for (int i = 1; i <= windowsNum; ++i) {
DbusEventBufferAppendable buf = _eventBufferMult.getDbusEventBufferAppendable(p[0]);
buf.startEvents();
byte[] schema = "abcdefghijklmnop".getBytes(Charset.defaultCharset());
assertTrue(buf.appendEvent(new DbusEventKey(1), (short) 100, (short) 0, System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[10], false, null));
buf.endEvents(100 * i, null);
buf = _eventBufferMult.getDbusEventBufferAppendable(p[1]);
buf.startEvents();
assertTrue(buf.appendEvent(new DbusEventKey(1), (short) 101, (short) 2, System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
assertTrue(buf.appendEvent(new DbusEventKey(2), (short) 101, (short) 2, System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[10], false, null));
buf.endEvents(100 * i + 1, null);
buf = _eventBufferMult.getDbusEventBufferAppendable(p[2]);
buf.startEvents();
assertTrue(buf.appendEvent(new DbusEventKey(1), (short) 101, (short) 2, System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[100], false, null));
assertTrue(buf.appendEvent(new DbusEventKey(2), (short) 101, (short) 2, System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[10], false, null));
assertTrue(buf.appendEvent(new DbusEventKey(3), (short) 101, (short) 2, System.currentTimeMillis() * 1000000, (short) 2, schema, new byte[10], false, null));
buf.endEvents(100 * i + 2, null);
}
String[] pnames = new String[p.length];
int count = 0;
for (PhysicalPartition ip : p) {
pnames[count++] = ip.toSimpleString();
}
StatsCollectors<DbusEventsStatisticsCollector> statsColl = createStats(pnames);
PhysicalPartitionKey[] pkeys = { new PhysicalPartitionKey(p[0]), new PhysicalPartitionKey(p[1]), new PhysicalPartitionKey(p[2]) };
CheckpointMult cpMult = new CheckpointMult();
for (int i = 0; i < 3; ++i) {
Checkpoint cp = new Checkpoint();
cp.setFlexible();
cp.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION);
cpMult.addCheckpoint(p[i], cp);
}
DbusEventBufferBatchReadable reader = _eventBufferMult.getDbusEventBufferBatchReadable(cpMult, Arrays.asList(pkeys), statsColl);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableByteChannel writeChannel = Channels.newChannel(baos);
// Set streamFromLatestScn == true
reader.streamEvents(true, 1000000, writeChannel, Encoding.BINARY, new AllowAllDbusFilter());
writeChannel.close();
baos.close();
//make sure we got the physical partition names right
List<String> ppartNames = statsColl.getStatsCollectorKeys();
assertEquals(ppartNames.size(), 3);
HashSet<String> expectedPPartNames = new HashSet<String>(Arrays.asList(p[0].toSimpleString(), p[1].toSimpleString(), p[2].toSimpleString()));
for (String ppartName : ppartNames) {
assertTrue(expectedPPartNames.contains(ppartName));
}
//verify event counts per partition
DbusEventsTotalStats[] ppartStats = { statsColl.getStatsCollector(p[0].toSimpleString()).getTotalStats(), statsColl.getStatsCollector(p[1].toSimpleString()).getTotalStats(), statsColl.getStatsCollector(p[2].toSimpleString()).getTotalStats() };
// Only the last window is returned in each of the partitions
assertEquals(ppartStats[0].getNumDataEvents(), 1);
assertEquals(ppartStats[1].getNumDataEvents(), 2);
assertEquals(ppartStats[2].getNumDataEvents(), 3);
assertEquals(ppartStats[0].getNumSysEvents(), 1);
assertEquals(ppartStats[1].getNumSysEvents(), 1);
assertEquals(ppartStats[2].getNumSysEvents(), 1);
assertEquals(statsColl.getStatsCollector().getTotalStats().getNumDataEvents(), (1 + 2 + 3));
assertEquals(statsColl.getStatsCollector().getTotalStats().getNumSysEvents(), (1 + 1 + 1));
assertEquals(statsColl.getStatsCollector().getTotalStats().getMaxTimeLag(), Math.max(ppartStats[0].getTimeLag(), Math.max(ppartStats[1].getTimeLag(), ppartStats[2].getTimeLag())));
assertEquals(statsColl.getStatsCollector().getTotalStats().getMinTimeLag(), Math.min(ppartStats[0].getTimeLag(), Math.min(ppartStats[1].getTimeLag(), ppartStats[2].getTimeLag())));
}
Aggregations