use of io.cdap.cdap.logging.meta.KafkaOffset in project cdap by caskdata.
the class KafkaLogProcessorPipeline method startUp.
@Override
protected void startUp() throws Exception {
LOG.debug("Starting log processor pipeline for {} with configurations {}", name, config);
// Reads the existing checkpoints
Set<Integer> partitions = config.getPartitions();
for (Map.Entry<Integer, Checkpoint<KafkaOffset>> entry : checkpointManager.getCheckpoint(partitions).entrySet()) {
Checkpoint<KafkaOffset> checkpoint = entry.getValue();
KafkaOffset kafkaOffset = checkpoint.getOffset();
// Skip the partition that doesn't have previous checkpoint.
if (kafkaOffset.getNextOffset() >= 0 && kafkaOffset.getNextEventTime() >= 0 && checkpoint.getMaxEventTime() >= 0) {
checkpoints.put(entry.getKey(), new MutableCheckpoint(checkpoint));
}
}
context.start();
fetchExecutor = Executors.newFixedThreadPool(partitions.size(), Threads.createDaemonThreadFactory("fetcher-" + name + "-%d"));
// emit pipeline related config as metrics
emitConfigMetrics();
LOG.info("Log processor pipeline for {} with config {} started with checkpoint {}", name, config, checkpoints);
}
use of io.cdap.cdap.logging.meta.KafkaOffset in project cdap by caskdata.
the class KafkaLogProcessorPipeline method processMessages.
/**
* Processes log messages for given partition. This method will provide events iterator to event queue processor
* and update checkpoints and offsets based on events processed by event queue processor. If any of the events are
* processed by event queue processor, method returns true, otherwise false.
*/
private boolean processMessages(String topic, int partition, Future<Iterable<MessageAndOffset>> future) throws InterruptedException, KafkaException, IOException {
Iterable<MessageAndOffset> messages;
try {
messages = future.get();
} catch (ExecutionException e) {
try {
throw e.getCause();
} catch (OffsetOutOfRangeException cause) {
// This shouldn't happen under normal situation.
// If happened, usually is caused by race between kafka log rotation and fetching in here,
// hence just fetching from the beginning should be fine
offsets.put(partition, getLastOffset(partition, kafka.api.OffsetRequest.EarliestTime()));
return false;
} catch (KafkaException | IOException cause) {
throw cause;
} catch (Throwable t) {
// For other type of exceptions, just throw an IOException. It will be handled by caller.
throw new IOException(t);
}
}
// process all the messages
ProcessedEventMetadata<KafkaOffset> metadata = eventQueueProcessor.process(partition, new KafkaMessageTransformIterator(topic, partition, messages.iterator()));
// None of the events were processed.
if (metadata.getTotalEventsProcessed() <= 0) {
return false;
}
// only update checkpoints if some events were processed
unSyncedEvents += metadata.getTotalEventsProcessed();
for (Map.Entry<Integer, Checkpoint<KafkaOffset>> entry : metadata.getCheckpoints().entrySet()) {
MutableCheckpoint checkpoint = checkpoints.get(entry.getKey());
Checkpoint<KafkaOffset> checkpointMetadata = entry.getValue();
// Update checkpoints
KafkaOffset kafkaOffset = checkpointMetadata.getOffset();
if (checkpoint == null) {
checkpoint = new MutableCheckpoint(kafkaOffset, checkpointMetadata.getMaxEventTime());
checkpoints.put(entry.getKey(), checkpoint);
} else {
MutableKafkaOffset offset = checkpoint.getOffset();
offset.setNextOffset(kafkaOffset.getNextOffset());
offset.setNextEventTime(kafkaOffset.getNextEventTime());
checkpoint.setMaxEventTime(checkpointMetadata.getMaxEventTime());
}
}
// For each partition, if there is no more event in the event queue, update the checkpoint nextOffset
for (Int2LongMap.Entry entry : offsets.int2LongEntrySet()) {
if (eventQueueProcessor.isQueueEmpty(entry.getIntKey())) {
MutableCheckpoint checkpoint = checkpoints.get(entry.getIntKey());
long offset = entry.getLongValue();
// it means everything before the process offset must had been written to the appender.
if (checkpoint != null && offset > checkpoint.getOffset().getNextOffset()) {
checkpoint.getOffset().setNextOffset(offset);
}
}
}
return true;
}
use of io.cdap.cdap.logging.meta.KafkaOffset in project cdap by caskdata.
the class TestDistributedLogReader method generateCheckpointTime.
private static void generateCheckpointTime(LoggingContext loggingContext, int numExpectedEvents, String kafkaTopic) throws IOException {
FileLogReader logReader = injector.getInstance(FileLogReader.class);
List<LogEvent> events = Lists.newArrayList(logReader.getLog(loggingContext, 0, Long.MAX_VALUE, Filter.EMPTY_FILTER));
Assert.assertEquals(numExpectedEvents, events.size());
// Save checkpoint (time of last event)
TransactionRunner transactionRunner = injector.getInstance(TransactionRunner.class);
CheckpointManager<KafkaOffset> checkpointManager = new KafkaCheckpointManager(transactionRunner, Constants.Logging.SYSTEM_PIPELINE_CHECKPOINT_PREFIX + kafkaTopic);
long checkpointTime = events.get(numExpectedEvents - 1).getLoggingEvent().getTimeStamp();
checkpointManager.saveCheckpoints(ImmutableMap.of(stringPartitioner.partition(loggingContext.getLogPartition(), -1), new Checkpoint<>(new KafkaOffset(numExpectedEvents, checkpointTime), checkpointTime)));
}
use of io.cdap.cdap.logging.meta.KafkaOffset in project cdap by caskdata.
the class DistributedLogFrameworkTest method testFramework.
@Test
public void testFramework() throws Exception {
DistributedLogFramework framework = injector.getInstance(DistributedLogFramework.class);
CConfiguration cConf = injector.getInstance(CConfiguration.class);
framework.startAndWait();
// Send some logs to Kafka.
LoggingContext context = new ServiceLoggingContext(NamespaceId.SYSTEM.getNamespace(), Constants.Logging.COMPONENT_NAME, "test");
// Make sure all events get flushed in the same batch
long eventTimeBase = System.currentTimeMillis() + cConf.getInt(Constants.Logging.PIPELINE_EVENT_DELAY_MS);
final int msgCount = 50;
for (int i = 0; i < msgCount; i++) {
// Publish logs in descending timestamp order
publishLog(cConf.get(Constants.Logging.KAFKA_TOPIC), context, ImmutableList.of(createLoggingEvent("io.cdap.test." + i, Level.INFO, "Testing " + i, eventTimeBase - i)));
}
// Read the logs back. They should be sorted by timestamp order.
final FileMetaDataReader metaDataReader = injector.getInstance(FileMetaDataReader.class);
Tasks.waitFor(true, () -> {
List<LogLocation> locations = metaDataReader.listFiles(new LogPathIdentifier(NamespaceId.SYSTEM.getNamespace(), Constants.Logging.COMPONENT_NAME, "test"), 0, Long.MAX_VALUE);
if (locations.size() != 1) {
return false;
}
LogLocation location = locations.get(0);
int i = 0;
try {
try (CloseableIterator<LogEvent> iter = location.readLog(Filter.EMPTY_FILTER, 0, Long.MAX_VALUE, msgCount)) {
while (iter.hasNext()) {
String expectedMsg = "Testing " + (msgCount - i - 1);
LogEvent event = iter.next();
if (!expectedMsg.equals(event.getLoggingEvent().getMessage())) {
return false;
}
i++;
}
return i == msgCount;
}
} catch (Exception e) {
// and the time when actual content are flushed to the file
return false;
}
}, 10, TimeUnit.SECONDS, msgCount, TimeUnit.MILLISECONDS);
framework.stopAndWait();
String kafkaTopic = cConf.get(Constants.Logging.KAFKA_TOPIC);
// Check the checkpoint is persisted correctly. Since all messages are processed,
// the checkpoint should be the same as the message count.
CheckpointManager<KafkaOffset> checkpointManager = getCheckpointManager(kafkaTopic);
Checkpoint<KafkaOffset> checkpoint = checkpointManager.getCheckpoint(0);
Assert.assertEquals(msgCount, checkpoint.getOffset().getNextOffset());
}
Aggregations