Search in sources :

Example 1 with KafkaOffset

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);
}
Also used : Checkpoint(io.cdap.cdap.logging.meta.Checkpoint) KafkaOffset(io.cdap.cdap.logging.meta.KafkaOffset) HashMap(java.util.HashMap) Int2LongMap(it.unimi.dsi.fastutil.ints.Int2LongMap) Map(java.util.Map) Int2LongOpenHashMap(it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) Int2ObjectMap(it.unimi.dsi.fastutil.ints.Int2ObjectMap)

Example 2 with KafkaOffset

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;
}
Also used : MessageAndOffset(kafka.message.MessageAndOffset) IOException(java.io.IOException) Checkpoint(io.cdap.cdap.logging.meta.Checkpoint) KafkaOffset(io.cdap.cdap.logging.meta.KafkaOffset) Int2LongMap(it.unimi.dsi.fastutil.ints.Int2LongMap) ExecutionException(java.util.concurrent.ExecutionException) OffsetOutOfRangeException(org.apache.kafka.common.errors.OffsetOutOfRangeException) HashMap(java.util.HashMap) Int2LongMap(it.unimi.dsi.fastutil.ints.Int2LongMap) Map(java.util.Map) Int2LongOpenHashMap(it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) Int2ObjectMap(it.unimi.dsi.fastutil.ints.Int2ObjectMap)

Example 3 with KafkaOffset

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)));
}
Also used : KafkaCheckpointManager(io.cdap.cdap.logging.meta.KafkaCheckpointManager) Checkpoint(io.cdap.cdap.logging.meta.Checkpoint) LogEvent(io.cdap.cdap.logging.read.LogEvent) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) KafkaOffset(io.cdap.cdap.logging.meta.KafkaOffset) FileLogReader(io.cdap.cdap.logging.read.FileLogReader)

Example 4 with KafkaOffset

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());
}
Also used : LoggingContext(io.cdap.cdap.common.logging.LoggingContext) ServiceLoggingContext(io.cdap.cdap.common.logging.ServiceLoggingContext) LogEvent(io.cdap.cdap.logging.read.LogEvent) ServiceLoggingContext(io.cdap.cdap.common.logging.ServiceLoggingContext) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) Checkpoint(io.cdap.cdap.logging.meta.Checkpoint) IOException(java.io.IOException) LogLocation(io.cdap.cdap.logging.write.LogLocation) KafkaOffset(io.cdap.cdap.logging.meta.KafkaOffset) FileMetaDataReader(io.cdap.cdap.logging.meta.FileMetaDataReader) LogPathIdentifier(io.cdap.cdap.logging.appender.system.LogPathIdentifier) Test(org.junit.Test)

Aggregations

Checkpoint (io.cdap.cdap.logging.meta.Checkpoint)4 KafkaOffset (io.cdap.cdap.logging.meta.KafkaOffset)4 LogEvent (io.cdap.cdap.logging.read.LogEvent)2 Int2LongMap (it.unimi.dsi.fastutil.ints.Int2LongMap)2 Int2LongOpenHashMap (it.unimi.dsi.fastutil.ints.Int2LongOpenHashMap)2 Int2ObjectMap (it.unimi.dsi.fastutil.ints.Int2ObjectMap)2 Int2ObjectOpenHashMap (it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)1 LoggingContext (io.cdap.cdap.common.logging.LoggingContext)1 ServiceLoggingContext (io.cdap.cdap.common.logging.ServiceLoggingContext)1 LogPathIdentifier (io.cdap.cdap.logging.appender.system.LogPathIdentifier)1 FileMetaDataReader (io.cdap.cdap.logging.meta.FileMetaDataReader)1 KafkaCheckpointManager (io.cdap.cdap.logging.meta.KafkaCheckpointManager)1 FileLogReader (io.cdap.cdap.logging.read.FileLogReader)1 LogLocation (io.cdap.cdap.logging.write.LogLocation)1 TransactionRunner (io.cdap.cdap.spi.data.transaction.TransactionRunner)1 ExecutionException (java.util.concurrent.ExecutionException)1