You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@nifi.apache.org by "exceptionfactory (via GitHub)" <gi...@apache.org> on 2025/09/04 20:28:05 UTC
Re: [PR] NIFI-14727 Create new ConsumeKinesis Processor [nifi]
exceptionfactory commented on code in PR #10077:
URL: https://github.com/apache/nifi/pull/10077#discussion_r2323375003
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/resources/docs/org.apache.nifi.processors.aws.kinesis.ConsumeKinesis/additionalDetails.md:
##########
@@ -0,0 +1,35 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+# ConsumeKinesis
+
+## Record processing
+
+When _Record Reader_ and _Record Writer_ properties are set, _ConsumeKinesis_ operates in Record mode.
+In this mode, the processor reads records from Kinesis streams using the configured _Record Reader_,
+and writes them to FlowFiles using the configured _Record Writer_.
Review Comment:
This should be removed and an explicit property added, following the `Processing Strategy` property approach in `ConsumeKafka`.
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
Review Comment:
I recommend calling this simply `Stream Name` since the Processor already implies Kinesis as the context for all properties.
```suggestion
static final PropertyDescriptor STREAM_NAME = new PropertyDescriptor.Builder()
.name("Stream Name")
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
+ }
+
+ /**
+ * Creating Kinesis HTTP client, as per
+ * {@link software.amazon.kinesis.common.KinesisClientUtil#adjustKinesisClientBuilder(KinesisAsyncClientBuilder)}.
+ */
+ private static SdkAsyncHttpClient createKinesisHttpClient(final ProcessContext context) {
+ final int maxConcurrency = KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK * context.getMaxConcurrentTasks();
+
+ return createHttpClientBuilder(context)
+ .protocol(Protocol.HTTP2)
+ .maxConcurrency(maxConcurrency)
+ .http2Configuration(Http2Configuration.builder()
+ .initialWindowSize(KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES)
+ .healthCheckPingPeriod(KINESIS_HTTP_HEALTH_CHECK_PERIOD)
+ .build())
+ .build();
+ }
+
+ private static NettyNioAsyncHttpClient.Builder createHttpClientBuilder(final ProcessContext context) {
+ final NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder()
+ .connectionTimeout(HTTP_CLIENTS_CONNECTION_TIMEOUT)
+ .readTimeout(HTTP_CLIENTS_READ_TIMEOUT);
+
+ final ProxyConfigurationService proxyConfigService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
+ if (proxyConfigService != null) {
+ final ProxyConfiguration proxyConfig = proxyConfigService.getConfiguration();
+
+ final software.amazon.awssdk.http.nio.netty.ProxyConfiguration.Builder proxyConfigBuilder = software.amazon.awssdk.http.nio.netty.ProxyConfiguration.builder()
+ .host(proxyConfig.getProxyServerHost())
+ .port(proxyConfig.getProxyServerPort());
+
+ if (proxyConfig.hasCredential()) {
+ proxyConfigBuilder.username(proxyConfig.getProxyUserName());
+ proxyConfigBuilder.password(proxyConfig.getProxyUserPassword());
+ }
+
+ builder.proxyConfiguration(proxyConfigBuilder.build());
+ }
+
+ return builder;
+ }
+
+ private static InitialPositionInStreamExtended getInitialPosition(final ProcessContext context) {
+ final InitialPosition initialPosition = context.getProperty(INITIAL_STREAM_POSITION).asAllowableValue(InitialPosition.class);
+ return switch (initialPosition) {
+ case TRIM_HORIZON ->
+ InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.TRIM_HORIZON);
+ case LATEST -> InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.LATEST);
+ case AT_TIMESTAMP -> {
+ final String timestampValue = context.getProperty(STREAM_POSITION_TIMESTAMP).getValue();
+ final Instant timestamp = Instant.parse(timestampValue);
+ yield InitialPositionInStreamExtended.newInitialPositionAtTimestamp(Date.from(timestamp));
+ }
+ };
+ }
+
+ private static @Nullable MetricsFactory configureMetricsFactory(final ProcessContext context) {
+ final MetricsDestination destination = context.getProperty(METRICS_DESTINATION).asAllowableValue(MetricsDestination.class);
+ return switch (destination) {
+ case NONE -> new NullMetricsFactory();
+ case LOGS -> new LogMetricsFactory();
+ case CLOUDWATCH -> null; // If no metrics factory was provided, CloudWatch metrics factory is used by default.
+ };
+ }
+
+ @OnStopped
+ public void onStopped() {
+ if (kinesisScheduler != null) {
+ kinesisScheduler.shutdown();
+ }
+ if (kinesisClient != null) {
+ kinesisClient.close();
+ }
+ if (dynamoDbClient != null) {
+ dynamoDbClient.close();
+ }
+ if (cloudWatchClient != null) {
+ cloudWatchClient.close();
+ }
+
+ recordBuffer = null;
+ readerRecordProcessor = Optional.empty();
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+ final Optional<ShardBufferLease> maybeLease = recordBuffer.acquireBufferLease();
+
+ maybeLease.ifPresentOrElse(
+ lease -> processRecordsFromBuffer(session, lease),
+ context::yield
+ );
+ }
+
+ private void processRecordsFromBuffer(final ProcessSession session, final ShardBufferLease lease) {
+ try {
+ final List<KinesisClientRecord> records = recordBuffer.consumeRecords(lease);
+
+ if (records.isEmpty()) {
+ recordBuffer.returnBufferLease(lease);
+ return;
+ }
+
+ final String shardId = lease.shardId();
+ readerRecordProcessor.ifPresentOrElse(
+ p -> processRecordsWithReader(p, session, shardId, records),
+ () -> processRecordsAsRaw(session, shardId, records)
+ );
+
+ session.adjustCounter("Records Processed", records.size(), false);
+
+ session.commitAsync(
+ () -> commitRecords(lease),
+ __ -> rollbackRecords(lease)
+ );
+ } catch (final RuntimeException e) {
+ getLogger().error("Failed to process records from Kinesis stream: {}", e.getMessage());
Review Comment:
Since the exception is thrown, this log can be removed.
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
+ }
+
+ /**
+ * Creating Kinesis HTTP client, as per
+ * {@link software.amazon.kinesis.common.KinesisClientUtil#adjustKinesisClientBuilder(KinesisAsyncClientBuilder)}.
+ */
+ private static SdkAsyncHttpClient createKinesisHttpClient(final ProcessContext context) {
+ final int maxConcurrency = KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK * context.getMaxConcurrentTasks();
+
+ return createHttpClientBuilder(context)
+ .protocol(Protocol.HTTP2)
+ .maxConcurrency(maxConcurrency)
+ .http2Configuration(Http2Configuration.builder()
+ .initialWindowSize(KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES)
+ .healthCheckPingPeriod(KINESIS_HTTP_HEALTH_CHECK_PERIOD)
+ .build())
+ .build();
+ }
+
+ private static NettyNioAsyncHttpClient.Builder createHttpClientBuilder(final ProcessContext context) {
+ final NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder()
+ .connectionTimeout(HTTP_CLIENTS_CONNECTION_TIMEOUT)
+ .readTimeout(HTTP_CLIENTS_READ_TIMEOUT);
+
+ final ProxyConfigurationService proxyConfigService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
+ if (proxyConfigService != null) {
+ final ProxyConfiguration proxyConfig = proxyConfigService.getConfiguration();
+
+ final software.amazon.awssdk.http.nio.netty.ProxyConfiguration.Builder proxyConfigBuilder = software.amazon.awssdk.http.nio.netty.ProxyConfiguration.builder()
+ .host(proxyConfig.getProxyServerHost())
+ .port(proxyConfig.getProxyServerPort());
+
+ if (proxyConfig.hasCredential()) {
+ proxyConfigBuilder.username(proxyConfig.getProxyUserName());
+ proxyConfigBuilder.password(proxyConfig.getProxyUserPassword());
+ }
+
+ builder.proxyConfiguration(proxyConfigBuilder.build());
+ }
+
+ return builder;
+ }
+
+ private static InitialPositionInStreamExtended getInitialPosition(final ProcessContext context) {
+ final InitialPosition initialPosition = context.getProperty(INITIAL_STREAM_POSITION).asAllowableValue(InitialPosition.class);
+ return switch (initialPosition) {
+ case TRIM_HORIZON ->
+ InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.TRIM_HORIZON);
+ case LATEST -> InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.LATEST);
+ case AT_TIMESTAMP -> {
+ final String timestampValue = context.getProperty(STREAM_POSITION_TIMESTAMP).getValue();
+ final Instant timestamp = Instant.parse(timestampValue);
+ yield InitialPositionInStreamExtended.newInitialPositionAtTimestamp(Date.from(timestamp));
+ }
+ };
+ }
+
+ private static @Nullable MetricsFactory configureMetricsFactory(final ProcessContext context) {
+ final MetricsDestination destination = context.getProperty(METRICS_DESTINATION).asAllowableValue(MetricsDestination.class);
+ return switch (destination) {
+ case NONE -> new NullMetricsFactory();
+ case LOGS -> new LogMetricsFactory();
+ case CLOUDWATCH -> null; // If no metrics factory was provided, CloudWatch metrics factory is used by default.
+ };
+ }
+
+ @OnStopped
+ public void onStopped() {
+ if (kinesisScheduler != null) {
+ kinesisScheduler.shutdown();
+ }
+ if (kinesisClient != null) {
+ kinesisClient.close();
+ }
+ if (dynamoDbClient != null) {
+ dynamoDbClient.close();
+ }
+ if (cloudWatchClient != null) {
+ cloudWatchClient.close();
+ }
+
+ recordBuffer = null;
+ readerRecordProcessor = Optional.empty();
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+ final Optional<ShardBufferLease> maybeLease = recordBuffer.acquireBufferLease();
+
+ maybeLease.ifPresentOrElse(
+ lease -> processRecordsFromBuffer(session, lease),
+ context::yield
+ );
+ }
+
+ private void processRecordsFromBuffer(final ProcessSession session, final ShardBufferLease lease) {
+ try {
+ final List<KinesisClientRecord> records = recordBuffer.consumeRecords(lease);
+
+ if (records.isEmpty()) {
+ recordBuffer.returnBufferLease(lease);
+ return;
+ }
+
+ final String shardId = lease.shardId();
+ readerRecordProcessor.ifPresentOrElse(
+ p -> processRecordsWithReader(p, session, shardId, records),
+ () -> processRecordsAsRaw(session, shardId, records)
+ );
+
+ session.adjustCounter("Records Processed", records.size(), false);
+
+ session.commitAsync(
+ () -> commitRecords(lease),
+ __ -> rollbackRecords(lease)
+ );
+ } catch (final RuntimeException e) {
+ getLogger().error("Failed to process records from Kinesis stream: {}", e.getMessage());
+ rollbackRecords(lease);
+ throw e;
+ }
+ }
+
+ private void commitRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.commitConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void rollbackRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.rollbackConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void processRecordsAsRaw(final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ for (final KinesisClientRecord record : records) {
+ FlowFile flowFile = session.create();
+ flowFile = session.putAllAttributes(flowFile, ConsumeKinesisAttributes.fromKinesisRecords(streamName, shardId, record, record));
+
+ flowFile = session.write(flowFile, out -> Channels.newChannel(out).write(record.data()));
+
+ session.transfer(flowFile, REL_SUCCESS);
+ }
+ }
+
+ private void processRecordsWithReader(final ReaderRecordProcessor recordProcessor, final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ final ProcessingResult result = recordProcessor.processRecords(session, streamName, shardId, records);
+
+ session.transfer(result.successFlowFiles(), REL_SUCCESS);
+ session.transfer(result.parseFailureFlowFiles(), REL_PARSE_FAILURE);
+ }
+
+ /**
+ * An adapter between Kinesis Consumer Library and {@link RecordBuffer}.
+ */
+ private static class ConsumeKinesisRecordProcessor implements ShardRecordProcessor {
+
+ private final RecordBuffer.ForKinesisClientLibrary recordBuffer;
+ private volatile @Nullable ShardBufferId bufferId;
+
+ ConsumeKinesisRecordProcessor(final MemoryBoundRecordBuffer recordBuffer) {
+ this.recordBuffer = recordBuffer;
+ }
+
+ @Override
+ public void initialize(final InitializationInput initializationInput) {
+ bufferId = recordBuffer.createBuffer(initializationInput.shardId());
+ }
+
+ @Override
+ public void processRecords(final ProcessRecordsInput processRecordsInput) {
+ if (bufferId == null) {
+ throw new IllegalStateException("Tried to process records before initialize.");
+ }
+ recordBuffer.addRecords(bufferId, processRecordsInput.records(), processRecordsInput.checkpointer());
+ }
+
+ @Override
+ public void leaseLost(final LeaseLostInput leaseLostInput) {
+ if (bufferId != null) {
+ recordBuffer.consumerLeaseLost(bufferId);
+ }
+ }
+
+ @Override
+ public void shardEnded(final ShardEndedInput shardEndedInput) {
+ if (bufferId != null) {
+ recordBuffer.checkpointEndedShard(bufferId, shardEndedInput.checkpointer());
+ }
+ }
+
+ @Override
+ public void shutdownRequested(final ShutdownRequestedInput shutdownRequestedInput) {
+ if (bufferId != null) {
+ recordBuffer.shutdownShardConsumption(bufferId, shutdownRequestedInput.checkpointer());
+ }
+ }
+ }
+
+ public enum InitialPosition implements DescribedValue {
+ TRIM_HORIZON("Trim Horizon", "Start reading at the last untrimmed record in the shard in the system, which is the oldest data record in the shard."),
+ LATEST("Latest", "Start reading just after the most recent record in the shard, so that you always read the most recent data in the shard."),
+ AT_TIMESTAMP("At Timestamp", "Start reading at the record with the specified timestamp.");
+
+ private final String displayName;
+ private final String description;
+
+ InitialPosition(final String displayName, final String description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ @Override
+ public String getValue() {
+ return name();
+ }
+
+ @Override
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+ }
+
+ public enum MetricsDestination implements DescribedValue {
+ NONE("None", "The Kinesis Client Library won't publish any metrics."),
+ LOGS("Logs", "The Kinesis Client Library will publish metrics with the standard logger."),
+ CLOUDWATCH("CloudWatch", "The Kinesis Client Library will publish metrics to Amazon CloudWatch.");
Review Comment:
The description should be in terms of Processor behavior, not library behavior:
```suggestion
NONE("None", "No metrics published"),
LOGS("Logs", "Metrics published to application logs"),
CLOUDWATCH("CloudWatch", "Metrics published to Amazon CloudWatch");
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/MemoryBoundRecordBuffer.java:
##########
@@ -0,0 +1,674 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import software.amazon.kinesis.exceptions.InvalidStateException;
+import software.amazon.kinesis.exceptions.KinesisClientLibDependencyException;
+import software.amazon.kinesis.exceptions.ShutdownException;
+import software.amazon.kinesis.exceptions.ThrottlingException;
+import software.amazon.kinesis.processor.RecordProcessorCheckpointer;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.nio.ByteBuffer;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.util.Collections.emptyList;
+
+/**
+ * A record buffer which limits the maximum memory usage across all shard buffers.
+ * If the memory limit is reached, adding new records will block until enough memory is freed.
+ */
+final class MemoryBoundRecordBuffer implements RecordBuffer.ForKinesisClientLibrary, RecordBuffer.ForProcessor {
+
+ private final ComponentLog logger;
+
+ private final long checkpointIntervalMillis;
+ private final BlockingMemoryTracker memoryTracker;
+
+ private final AtomicLong bufferIdCounter = new AtomicLong(0);
+ private final ConcurrentMap<ShardBufferId, ShardBuffer> shardBuffers = new ConcurrentHashMap<>();
+
+ /**
+ * A queue with ids shard buffers available for leasing.
+ * <p>
+ * Note: when a buffer is invalidated its id is NOT removed from the queue immediately.
+ */
+ private final Queue<ShardBufferId> buffersToLease = new ConcurrentLinkedQueue<>();
+
+ MemoryBoundRecordBuffer(final ComponentLog logger, final long maxMemoryBytes, final Duration checkpointInterval) {
+ this.logger = logger;
+ this.memoryTracker = new BlockingMemoryTracker(logger, maxMemoryBytes);
+ this.checkpointIntervalMillis = checkpointInterval.toMillis();
+ }
+
+ @Override
+ public ShardBufferId createBuffer(final String shardId) {
+ final ShardBufferId id = new ShardBufferId(shardId, bufferIdCounter.getAndIncrement());
+
+ logger.info("Creating new buffer for shard {} with id {}", shardId, id);
+
+ shardBuffers.put(id, new ShardBuffer(id, logger, checkpointIntervalMillis));
+ buffersToLease.add(id);
+ return id;
+ }
+
+ @Override
+ public void addRecords(final ShardBufferId bufferId, final List<KinesisClientRecord> records, final RecordProcessorCheckpointer checkpointer) {
+ if (records.isEmpty()) {
+ return;
+ }
+
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot add records with sequence and subsequence numbers: {}.{} - {}.{}",
+ bufferId,
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber());
+ return;
+ }
+
+ final RecordBatch recordBatch = new RecordBatch(records, checkpointer, calculateMemoryUsage(records));
+ memoryTracker.reserveMemory(recordBatch);
+ final boolean addedRecords = buffer.offer(recordBatch);
+
+ if (addedRecords) {
+ logger.debug("Successfully added records with sequence and subsequence numbers: {}.{} - {}.{} to buffer with id {}",
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber(),
+ bufferId);
+ } else {
+ logger.debug("Buffer with id {} was invalidated. Cannot add records with sequence and subsequence numbers: {}.{} - {}.{}",
+ bufferId,
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber());
+ // If the buffer was invalidated, we should free memory reserved for these records.
+ memoryTracker.freeMemory(List.of(recordBatch));
+ }
+ }
+
+ @Override
+ public void checkpointEndedShard(final ShardBufferId bufferId, final RecordProcessorCheckpointer checkpointer) {
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot checkpoint the ended shard", bufferId);
+ return;
+ }
+
+ logger.info("Finishing consumption for buffer {}. Checkpointing the ended shard", bufferId);
+ buffer.checkpointEndedShard(checkpointer);
+
+ logger.debug("Removing buffer with id {} after successful ended shard checkpoint", bufferId);
+ shardBuffers.remove(bufferId);
+ }
+
+ @Override
+ public void shutdownShardConsumption(final ShardBufferId bufferId, final RecordProcessorCheckpointer checkpointer) {
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot shutdown shard consumption", bufferId);
+ return;
+ }
+
+ logger.info("Shutting down the buffer {}. Checkpointing last consumed record", bufferId);
+ buffer.shutdownBuffer(checkpointer);
+
+ logger.debug("Removing buffer with id {} after successful last consumed record checkpoint", bufferId);
+ shardBuffers.remove(bufferId);
+ }
+
+ @Override
+ public void consumerLeaseLost(final ShardBufferId bufferId) {
+ final ShardBuffer buffer = shardBuffers.remove(bufferId);
+
+ logger.info("Lease lost for buffer {}. Invalidating it", bufferId);
Review Comment:
```suggestion
logger.info("Lease lost for buffer {}: Invalidating", bufferId);
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
Review Comment:
The thread should be named. Recommend naming it `ConsumeKinesis-Scheduler-componentId` where `componentId` comes from `getIdentifier()`
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
Review Comment:
Does this need to be a configurable property? Automatically setting the value to `ConsumeKinesis` plus the component identifier would produce a unique value for each Processor. Alternatively, keeping the property enables reusing an existing reference, is that needed?
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
Review Comment:
It looks like this thread is never stopped, is that correct? Is it stopped automatically as a result of stopping of the other components in the `onStopped` method?
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/MemoryBoundRecordBuffer.java:
##########
@@ -0,0 +1,674 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import software.amazon.kinesis.exceptions.InvalidStateException;
+import software.amazon.kinesis.exceptions.KinesisClientLibDependencyException;
+import software.amazon.kinesis.exceptions.ShutdownException;
+import software.amazon.kinesis.exceptions.ThrottlingException;
+import software.amazon.kinesis.processor.RecordProcessorCheckpointer;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.nio.ByteBuffer;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.util.Collections.emptyList;
+
+/**
+ * A record buffer which limits the maximum memory usage across all shard buffers.
+ * If the memory limit is reached, adding new records will block until enough memory is freed.
+ */
+final class MemoryBoundRecordBuffer implements RecordBuffer.ForKinesisClientLibrary, RecordBuffer.ForProcessor {
+
+ private final ComponentLog logger;
+
+ private final long checkpointIntervalMillis;
+ private final BlockingMemoryTracker memoryTracker;
+
+ private final AtomicLong bufferIdCounter = new AtomicLong(0);
+ private final ConcurrentMap<ShardBufferId, ShardBuffer> shardBuffers = new ConcurrentHashMap<>();
+
+ /**
+ * A queue with ids shard buffers available for leasing.
+ * <p>
+ * Note: when a buffer is invalidated its id is NOT removed from the queue immediately.
+ */
+ private final Queue<ShardBufferId> buffersToLease = new ConcurrentLinkedQueue<>();
+
+ MemoryBoundRecordBuffer(final ComponentLog logger, final long maxMemoryBytes, final Duration checkpointInterval) {
+ this.logger = logger;
+ this.memoryTracker = new BlockingMemoryTracker(logger, maxMemoryBytes);
+ this.checkpointIntervalMillis = checkpointInterval.toMillis();
+ }
+
+ @Override
+ public ShardBufferId createBuffer(final String shardId) {
+ final ShardBufferId id = new ShardBufferId(shardId, bufferIdCounter.getAndIncrement());
+
+ logger.info("Creating new buffer for shard {} with id {}", shardId, id);
Review Comment:
This seems more appropriate as a debug level message.
```suggestion
logger.debug("Creating new buffer for shard {} with id {}", shardId, id);
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
Review Comment:
Instead making this optional, recommend adding a new `Processing Strategy` property with `FLOW_FILE` and `RECORD` as values, then making these and Record Writer depend on the Record strategy.
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
+ }
+
+ /**
+ * Creating Kinesis HTTP client, as per
+ * {@link software.amazon.kinesis.common.KinesisClientUtil#adjustKinesisClientBuilder(KinesisAsyncClientBuilder)}.
+ */
+ private static SdkAsyncHttpClient createKinesisHttpClient(final ProcessContext context) {
+ final int maxConcurrency = KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK * context.getMaxConcurrentTasks();
+
+ return createHttpClientBuilder(context)
+ .protocol(Protocol.HTTP2)
+ .maxConcurrency(maxConcurrency)
+ .http2Configuration(Http2Configuration.builder()
+ .initialWindowSize(KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES)
+ .healthCheckPingPeriod(KINESIS_HTTP_HEALTH_CHECK_PERIOD)
+ .build())
+ .build();
+ }
+
+ private static NettyNioAsyncHttpClient.Builder createHttpClientBuilder(final ProcessContext context) {
+ final NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder()
+ .connectionTimeout(HTTP_CLIENTS_CONNECTION_TIMEOUT)
+ .readTimeout(HTTP_CLIENTS_READ_TIMEOUT);
+
+ final ProxyConfigurationService proxyConfigService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
+ if (proxyConfigService != null) {
+ final ProxyConfiguration proxyConfig = proxyConfigService.getConfiguration();
+
+ final software.amazon.awssdk.http.nio.netty.ProxyConfiguration.Builder proxyConfigBuilder = software.amazon.awssdk.http.nio.netty.ProxyConfiguration.builder()
+ .host(proxyConfig.getProxyServerHost())
+ .port(proxyConfig.getProxyServerPort());
+
+ if (proxyConfig.hasCredential()) {
+ proxyConfigBuilder.username(proxyConfig.getProxyUserName());
+ proxyConfigBuilder.password(proxyConfig.getProxyUserPassword());
+ }
+
+ builder.proxyConfiguration(proxyConfigBuilder.build());
+ }
+
+ return builder;
+ }
+
+ private static InitialPositionInStreamExtended getInitialPosition(final ProcessContext context) {
+ final InitialPosition initialPosition = context.getProperty(INITIAL_STREAM_POSITION).asAllowableValue(InitialPosition.class);
+ return switch (initialPosition) {
+ case TRIM_HORIZON ->
+ InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.TRIM_HORIZON);
+ case LATEST -> InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.LATEST);
+ case AT_TIMESTAMP -> {
+ final String timestampValue = context.getProperty(STREAM_POSITION_TIMESTAMP).getValue();
+ final Instant timestamp = Instant.parse(timestampValue);
+ yield InitialPositionInStreamExtended.newInitialPositionAtTimestamp(Date.from(timestamp));
+ }
+ };
+ }
+
+ private static @Nullable MetricsFactory configureMetricsFactory(final ProcessContext context) {
+ final MetricsDestination destination = context.getProperty(METRICS_DESTINATION).asAllowableValue(MetricsDestination.class);
+ return switch (destination) {
+ case NONE -> new NullMetricsFactory();
+ case LOGS -> new LogMetricsFactory();
+ case CLOUDWATCH -> null; // If no metrics factory was provided, CloudWatch metrics factory is used by default.
+ };
+ }
+
+ @OnStopped
+ public void onStopped() {
+ if (kinesisScheduler != null) {
+ kinesisScheduler.shutdown();
+ }
+ if (kinesisClient != null) {
+ kinesisClient.close();
+ }
+ if (dynamoDbClient != null) {
+ dynamoDbClient.close();
+ }
+ if (cloudWatchClient != null) {
+ cloudWatchClient.close();
+ }
+
+ recordBuffer = null;
+ readerRecordProcessor = Optional.empty();
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+ final Optional<ShardBufferLease> maybeLease = recordBuffer.acquireBufferLease();
+
+ maybeLease.ifPresentOrElse(
Review Comment:
Instead of using `maybe`, recommend calling this `leaseAcquired`.
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
+ }
+
+ /**
+ * Creating Kinesis HTTP client, as per
+ * {@link software.amazon.kinesis.common.KinesisClientUtil#adjustKinesisClientBuilder(KinesisAsyncClientBuilder)}.
+ */
+ private static SdkAsyncHttpClient createKinesisHttpClient(final ProcessContext context) {
+ final int maxConcurrency = KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK * context.getMaxConcurrentTasks();
+
+ return createHttpClientBuilder(context)
+ .protocol(Protocol.HTTP2)
+ .maxConcurrency(maxConcurrency)
+ .http2Configuration(Http2Configuration.builder()
+ .initialWindowSize(KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES)
+ .healthCheckPingPeriod(KINESIS_HTTP_HEALTH_CHECK_PERIOD)
+ .build())
+ .build();
+ }
+
+ private static NettyNioAsyncHttpClient.Builder createHttpClientBuilder(final ProcessContext context) {
+ final NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder()
+ .connectionTimeout(HTTP_CLIENTS_CONNECTION_TIMEOUT)
+ .readTimeout(HTTP_CLIENTS_READ_TIMEOUT);
+
+ final ProxyConfigurationService proxyConfigService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
+ if (proxyConfigService != null) {
+ final ProxyConfiguration proxyConfig = proxyConfigService.getConfiguration();
+
+ final software.amazon.awssdk.http.nio.netty.ProxyConfiguration.Builder proxyConfigBuilder = software.amazon.awssdk.http.nio.netty.ProxyConfiguration.builder()
+ .host(proxyConfig.getProxyServerHost())
+ .port(proxyConfig.getProxyServerPort());
+
+ if (proxyConfig.hasCredential()) {
+ proxyConfigBuilder.username(proxyConfig.getProxyUserName());
+ proxyConfigBuilder.password(proxyConfig.getProxyUserPassword());
+ }
+
+ builder.proxyConfiguration(proxyConfigBuilder.build());
+ }
+
+ return builder;
+ }
+
+ private static InitialPositionInStreamExtended getInitialPosition(final ProcessContext context) {
+ final InitialPosition initialPosition = context.getProperty(INITIAL_STREAM_POSITION).asAllowableValue(InitialPosition.class);
+ return switch (initialPosition) {
+ case TRIM_HORIZON ->
+ InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.TRIM_HORIZON);
+ case LATEST -> InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.LATEST);
+ case AT_TIMESTAMP -> {
+ final String timestampValue = context.getProperty(STREAM_POSITION_TIMESTAMP).getValue();
+ final Instant timestamp = Instant.parse(timestampValue);
+ yield InitialPositionInStreamExtended.newInitialPositionAtTimestamp(Date.from(timestamp));
+ }
+ };
+ }
+
+ private static @Nullable MetricsFactory configureMetricsFactory(final ProcessContext context) {
+ final MetricsDestination destination = context.getProperty(METRICS_DESTINATION).asAllowableValue(MetricsDestination.class);
+ return switch (destination) {
+ case NONE -> new NullMetricsFactory();
+ case LOGS -> new LogMetricsFactory();
+ case CLOUDWATCH -> null; // If no metrics factory was provided, CloudWatch metrics factory is used by default.
+ };
+ }
+
+ @OnStopped
+ public void onStopped() {
+ if (kinesisScheduler != null) {
+ kinesisScheduler.shutdown();
+ }
+ if (kinesisClient != null) {
+ kinesisClient.close();
+ }
+ if (dynamoDbClient != null) {
+ dynamoDbClient.close();
+ }
+ if (cloudWatchClient != null) {
+ cloudWatchClient.close();
+ }
+
+ recordBuffer = null;
+ readerRecordProcessor = Optional.empty();
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+ final Optional<ShardBufferLease> maybeLease = recordBuffer.acquireBufferLease();
+
+ maybeLease.ifPresentOrElse(
+ lease -> processRecordsFromBuffer(session, lease),
+ context::yield
+ );
+ }
+
+ private void processRecordsFromBuffer(final ProcessSession session, final ShardBufferLease lease) {
+ try {
+ final List<KinesisClientRecord> records = recordBuffer.consumeRecords(lease);
+
+ if (records.isEmpty()) {
+ recordBuffer.returnBufferLease(lease);
+ return;
+ }
+
+ final String shardId = lease.shardId();
+ readerRecordProcessor.ifPresentOrElse(
+ p -> processRecordsWithReader(p, session, shardId, records),
+ () -> processRecordsAsRaw(session, shardId, records)
+ );
+
+ session.adjustCounter("Records Processed", records.size(), false);
+
+ session.commitAsync(
+ () -> commitRecords(lease),
+ __ -> rollbackRecords(lease)
+ );
+ } catch (final RuntimeException e) {
+ getLogger().error("Failed to process records from Kinesis stream: {}", e.getMessage());
+ rollbackRecords(lease);
+ throw e;
+ }
+ }
+
+ private void commitRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.commitConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void rollbackRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.rollbackConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void processRecordsAsRaw(final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ for (final KinesisClientRecord record : records) {
+ FlowFile flowFile = session.create();
+ flowFile = session.putAllAttributes(flowFile, ConsumeKinesisAttributes.fromKinesisRecords(streamName, shardId, record, record));
+
+ flowFile = session.write(flowFile, out -> Channels.newChannel(out).write(record.data()));
+
+ session.transfer(flowFile, REL_SUCCESS);
+ }
+ }
+
+ private void processRecordsWithReader(final ReaderRecordProcessor recordProcessor, final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ final ProcessingResult result = recordProcessor.processRecords(session, streamName, shardId, records);
+
+ session.transfer(result.successFlowFiles(), REL_SUCCESS);
+ session.transfer(result.parseFailureFlowFiles(), REL_PARSE_FAILURE);
+ }
+
+ /**
+ * An adapter between Kinesis Consumer Library and {@link RecordBuffer}.
+ */
+ private static class ConsumeKinesisRecordProcessor implements ShardRecordProcessor {
+
+ private final RecordBuffer.ForKinesisClientLibrary recordBuffer;
+ private volatile @Nullable ShardBufferId bufferId;
+
+ ConsumeKinesisRecordProcessor(final MemoryBoundRecordBuffer recordBuffer) {
+ this.recordBuffer = recordBuffer;
+ }
+
+ @Override
+ public void initialize(final InitializationInput initializationInput) {
+ bufferId = recordBuffer.createBuffer(initializationInput.shardId());
+ }
+
+ @Override
+ public void processRecords(final ProcessRecordsInput processRecordsInput) {
+ if (bufferId == null) {
+ throw new IllegalStateException("Tried to process records before initialize.");
Review Comment:
In general, the `.` character should not be used to end error messages.
```suggestion
throw new IllegalStateException("Buffer ID not found: Record Processor not initialized");
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
+ }
+
+ /**
+ * Creating Kinesis HTTP client, as per
+ * {@link software.amazon.kinesis.common.KinesisClientUtil#adjustKinesisClientBuilder(KinesisAsyncClientBuilder)}.
+ */
+ private static SdkAsyncHttpClient createKinesisHttpClient(final ProcessContext context) {
+ final int maxConcurrency = KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK * context.getMaxConcurrentTasks();
+
+ return createHttpClientBuilder(context)
+ .protocol(Protocol.HTTP2)
+ .maxConcurrency(maxConcurrency)
+ .http2Configuration(Http2Configuration.builder()
+ .initialWindowSize(KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES)
+ .healthCheckPingPeriod(KINESIS_HTTP_HEALTH_CHECK_PERIOD)
+ .build())
+ .build();
+ }
+
+ private static NettyNioAsyncHttpClient.Builder createHttpClientBuilder(final ProcessContext context) {
+ final NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder()
+ .connectionTimeout(HTTP_CLIENTS_CONNECTION_TIMEOUT)
+ .readTimeout(HTTP_CLIENTS_READ_TIMEOUT);
+
+ final ProxyConfigurationService proxyConfigService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
+ if (proxyConfigService != null) {
+ final ProxyConfiguration proxyConfig = proxyConfigService.getConfiguration();
+
+ final software.amazon.awssdk.http.nio.netty.ProxyConfiguration.Builder proxyConfigBuilder = software.amazon.awssdk.http.nio.netty.ProxyConfiguration.builder()
+ .host(proxyConfig.getProxyServerHost())
+ .port(proxyConfig.getProxyServerPort());
+
+ if (proxyConfig.hasCredential()) {
+ proxyConfigBuilder.username(proxyConfig.getProxyUserName());
+ proxyConfigBuilder.password(proxyConfig.getProxyUserPassword());
+ }
+
+ builder.proxyConfiguration(proxyConfigBuilder.build());
+ }
+
+ return builder;
+ }
+
+ private static InitialPositionInStreamExtended getInitialPosition(final ProcessContext context) {
+ final InitialPosition initialPosition = context.getProperty(INITIAL_STREAM_POSITION).asAllowableValue(InitialPosition.class);
+ return switch (initialPosition) {
+ case TRIM_HORIZON ->
+ InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.TRIM_HORIZON);
+ case LATEST -> InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.LATEST);
+ case AT_TIMESTAMP -> {
+ final String timestampValue = context.getProperty(STREAM_POSITION_TIMESTAMP).getValue();
+ final Instant timestamp = Instant.parse(timestampValue);
+ yield InitialPositionInStreamExtended.newInitialPositionAtTimestamp(Date.from(timestamp));
+ }
+ };
+ }
+
+ private static @Nullable MetricsFactory configureMetricsFactory(final ProcessContext context) {
+ final MetricsDestination destination = context.getProperty(METRICS_DESTINATION).asAllowableValue(MetricsDestination.class);
+ return switch (destination) {
+ case NONE -> new NullMetricsFactory();
+ case LOGS -> new LogMetricsFactory();
+ case CLOUDWATCH -> null; // If no metrics factory was provided, CloudWatch metrics factory is used by default.
+ };
+ }
+
+ @OnStopped
+ public void onStopped() {
+ if (kinesisScheduler != null) {
+ kinesisScheduler.shutdown();
+ }
+ if (kinesisClient != null) {
+ kinesisClient.close();
+ }
+ if (dynamoDbClient != null) {
+ dynamoDbClient.close();
+ }
+ if (cloudWatchClient != null) {
+ cloudWatchClient.close();
+ }
+
+ recordBuffer = null;
+ readerRecordProcessor = Optional.empty();
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+ final Optional<ShardBufferLease> maybeLease = recordBuffer.acquireBufferLease();
+
+ maybeLease.ifPresentOrElse(
+ lease -> processRecordsFromBuffer(session, lease),
+ context::yield
+ );
+ }
+
+ private void processRecordsFromBuffer(final ProcessSession session, final ShardBufferLease lease) {
+ try {
+ final List<KinesisClientRecord> records = recordBuffer.consumeRecords(lease);
+
+ if (records.isEmpty()) {
+ recordBuffer.returnBufferLease(lease);
+ return;
+ }
+
+ final String shardId = lease.shardId();
+ readerRecordProcessor.ifPresentOrElse(
+ p -> processRecordsWithReader(p, session, shardId, records),
+ () -> processRecordsAsRaw(session, shardId, records)
+ );
+
+ session.adjustCounter("Records Processed", records.size(), false);
+
+ session.commitAsync(
+ () -> commitRecords(lease),
+ __ -> rollbackRecords(lease)
+ );
+ } catch (final RuntimeException e) {
+ getLogger().error("Failed to process records from Kinesis stream: {}", e.getMessage());
+ rollbackRecords(lease);
+ throw e;
+ }
+ }
+
+ private void commitRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.commitConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void rollbackRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.rollbackConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void processRecordsAsRaw(final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ for (final KinesisClientRecord record : records) {
+ FlowFile flowFile = session.create();
+ flowFile = session.putAllAttributes(flowFile, ConsumeKinesisAttributes.fromKinesisRecords(streamName, shardId, record, record));
+
+ flowFile = session.write(flowFile, out -> Channels.newChannel(out).write(record.data()));
+
+ session.transfer(flowFile, REL_SUCCESS);
+ }
+ }
+
+ private void processRecordsWithReader(final ReaderRecordProcessor recordProcessor, final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ final ProcessingResult result = recordProcessor.processRecords(session, streamName, shardId, records);
+
+ session.transfer(result.successFlowFiles(), REL_SUCCESS);
+ session.transfer(result.parseFailureFlowFiles(), REL_PARSE_FAILURE);
+ }
+
+ /**
+ * An adapter between Kinesis Consumer Library and {@link RecordBuffer}.
+ */
+ private static class ConsumeKinesisRecordProcessor implements ShardRecordProcessor {
+
+ private final RecordBuffer.ForKinesisClientLibrary recordBuffer;
+ private volatile @Nullable ShardBufferId bufferId;
+
+ ConsumeKinesisRecordProcessor(final MemoryBoundRecordBuffer recordBuffer) {
+ this.recordBuffer = recordBuffer;
+ }
+
+ @Override
+ public void initialize(final InitializationInput initializationInput) {
+ bufferId = recordBuffer.createBuffer(initializationInput.shardId());
+ }
+
+ @Override
+ public void processRecords(final ProcessRecordsInput processRecordsInput) {
+ if (bufferId == null) {
+ throw new IllegalStateException("Tried to process records before initialize.");
+ }
+ recordBuffer.addRecords(bufferId, processRecordsInput.records(), processRecordsInput.checkpointer());
+ }
+
+ @Override
+ public void leaseLost(final LeaseLostInput leaseLostInput) {
+ if (bufferId != null) {
+ recordBuffer.consumerLeaseLost(bufferId);
+ }
+ }
+
+ @Override
+ public void shardEnded(final ShardEndedInput shardEndedInput) {
+ if (bufferId != null) {
+ recordBuffer.checkpointEndedShard(bufferId, shardEndedInput.checkpointer());
+ }
+ }
+
+ @Override
+ public void shutdownRequested(final ShutdownRequestedInput shutdownRequestedInput) {
+ if (bufferId != null) {
+ recordBuffer.shutdownShardConsumption(bufferId, shutdownRequestedInput.checkpointer());
+ }
+ }
+ }
+
+ public enum InitialPosition implements DescribedValue {
+ TRIM_HORIZON("Trim Horizon", "Start reading at the last untrimmed record in the shard in the system, which is the oldest data record in the shard."),
+ LATEST("Latest", "Start reading just after the most recent record in the shard, so that you always read the most recent data in the shard."),
+ AT_TIMESTAMP("At Timestamp", "Start reading at the record with the specified timestamp.");
+
+ private final String displayName;
+ private final String description;
+
+ InitialPosition(final String displayName, final String description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ @Override
+ public String getValue() {
+ return name();
+ }
+
+ @Override
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+ }
+
+ public enum MetricsDestination implements DescribedValue {
+ NONE("None", "The Kinesis Client Library won't publish any metrics."),
Review Comment:
Recommend `DISABLED` instead of `None`:
```suggestion
DISABLED("Disabled", "The Kinesis Client Library won't publish any metrics."),
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
+ }
+
+ /**
+ * Creating Kinesis HTTP client, as per
+ * {@link software.amazon.kinesis.common.KinesisClientUtil#adjustKinesisClientBuilder(KinesisAsyncClientBuilder)}.
+ */
+ private static SdkAsyncHttpClient createKinesisHttpClient(final ProcessContext context) {
+ final int maxConcurrency = KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK * context.getMaxConcurrentTasks();
+
+ return createHttpClientBuilder(context)
+ .protocol(Protocol.HTTP2)
+ .maxConcurrency(maxConcurrency)
+ .http2Configuration(Http2Configuration.builder()
+ .initialWindowSize(KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES)
+ .healthCheckPingPeriod(KINESIS_HTTP_HEALTH_CHECK_PERIOD)
+ .build())
+ .build();
+ }
+
+ private static NettyNioAsyncHttpClient.Builder createHttpClientBuilder(final ProcessContext context) {
+ final NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder()
+ .connectionTimeout(HTTP_CLIENTS_CONNECTION_TIMEOUT)
+ .readTimeout(HTTP_CLIENTS_READ_TIMEOUT);
+
+ final ProxyConfigurationService proxyConfigService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
+ if (proxyConfigService != null) {
+ final ProxyConfiguration proxyConfig = proxyConfigService.getConfiguration();
+
+ final software.amazon.awssdk.http.nio.netty.ProxyConfiguration.Builder proxyConfigBuilder = software.amazon.awssdk.http.nio.netty.ProxyConfiguration.builder()
+ .host(proxyConfig.getProxyServerHost())
+ .port(proxyConfig.getProxyServerPort());
+
+ if (proxyConfig.hasCredential()) {
+ proxyConfigBuilder.username(proxyConfig.getProxyUserName());
+ proxyConfigBuilder.password(proxyConfig.getProxyUserPassword());
+ }
+
+ builder.proxyConfiguration(proxyConfigBuilder.build());
+ }
+
+ return builder;
+ }
+
+ private static InitialPositionInStreamExtended getInitialPosition(final ProcessContext context) {
+ final InitialPosition initialPosition = context.getProperty(INITIAL_STREAM_POSITION).asAllowableValue(InitialPosition.class);
+ return switch (initialPosition) {
+ case TRIM_HORIZON ->
+ InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.TRIM_HORIZON);
+ case LATEST -> InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.LATEST);
+ case AT_TIMESTAMP -> {
+ final String timestampValue = context.getProperty(STREAM_POSITION_TIMESTAMP).getValue();
+ final Instant timestamp = Instant.parse(timestampValue);
+ yield InitialPositionInStreamExtended.newInitialPositionAtTimestamp(Date.from(timestamp));
+ }
+ };
+ }
+
+ private static @Nullable MetricsFactory configureMetricsFactory(final ProcessContext context) {
+ final MetricsDestination destination = context.getProperty(METRICS_DESTINATION).asAllowableValue(MetricsDestination.class);
+ return switch (destination) {
+ case NONE -> new NullMetricsFactory();
+ case LOGS -> new LogMetricsFactory();
+ case CLOUDWATCH -> null; // If no metrics factory was provided, CloudWatch metrics factory is used by default.
+ };
+ }
+
+ @OnStopped
+ public void onStopped() {
+ if (kinesisScheduler != null) {
+ kinesisScheduler.shutdown();
+ }
+ if (kinesisClient != null) {
+ kinesisClient.close();
+ }
+ if (dynamoDbClient != null) {
+ dynamoDbClient.close();
+ }
+ if (cloudWatchClient != null) {
+ cloudWatchClient.close();
+ }
+
+ recordBuffer = null;
+ readerRecordProcessor = Optional.empty();
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+ final Optional<ShardBufferLease> maybeLease = recordBuffer.acquireBufferLease();
+
+ maybeLease.ifPresentOrElse(
+ lease -> processRecordsFromBuffer(session, lease),
+ context::yield
+ );
+ }
+
+ private void processRecordsFromBuffer(final ProcessSession session, final ShardBufferLease lease) {
+ try {
+ final List<KinesisClientRecord> records = recordBuffer.consumeRecords(lease);
+
+ if (records.isEmpty()) {
+ recordBuffer.returnBufferLease(lease);
+ return;
+ }
+
+ final String shardId = lease.shardId();
+ readerRecordProcessor.ifPresentOrElse(
+ p -> processRecordsWithReader(p, session, shardId, records),
+ () -> processRecordsAsRaw(session, shardId, records)
+ );
+
+ session.adjustCounter("Records Processed", records.size(), false);
+
+ session.commitAsync(
+ () -> commitRecords(lease),
+ __ -> rollbackRecords(lease)
+ );
+ } catch (final RuntimeException e) {
+ getLogger().error("Failed to process records from Kinesis stream: {}", e.getMessage());
+ rollbackRecords(lease);
+ throw e;
+ }
+ }
+
+ private void commitRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.commitConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void rollbackRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.rollbackConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void processRecordsAsRaw(final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ for (final KinesisClientRecord record : records) {
+ FlowFile flowFile = session.create();
+ flowFile = session.putAllAttributes(flowFile, ConsumeKinesisAttributes.fromKinesisRecords(streamName, shardId, record, record));
+
+ flowFile = session.write(flowFile, out -> Channels.newChannel(out).write(record.data()));
+
+ session.transfer(flowFile, REL_SUCCESS);
+ }
+ }
+
+ private void processRecordsWithReader(final ReaderRecordProcessor recordProcessor, final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ final ProcessingResult result = recordProcessor.processRecords(session, streamName, shardId, records);
+
+ session.transfer(result.successFlowFiles(), REL_SUCCESS);
+ session.transfer(result.parseFailureFlowFiles(), REL_PARSE_FAILURE);
+ }
+
+ /**
+ * An adapter between Kinesis Consumer Library and {@link RecordBuffer}.
+ */
+ private static class ConsumeKinesisRecordProcessor implements ShardRecordProcessor {
+
+ private final RecordBuffer.ForKinesisClientLibrary recordBuffer;
+ private volatile @Nullable ShardBufferId bufferId;
+
+ ConsumeKinesisRecordProcessor(final MemoryBoundRecordBuffer recordBuffer) {
+ this.recordBuffer = recordBuffer;
+ }
+
+ @Override
+ public void initialize(final InitializationInput initializationInput) {
+ bufferId = recordBuffer.createBuffer(initializationInput.shardId());
+ }
+
+ @Override
+ public void processRecords(final ProcessRecordsInput processRecordsInput) {
+ if (bufferId == null) {
+ throw new IllegalStateException("Tried to process records before initialize.");
+ }
+ recordBuffer.addRecords(bufferId, processRecordsInput.records(), processRecordsInput.checkpointer());
+ }
+
+ @Override
+ public void leaseLost(final LeaseLostInput leaseLostInput) {
+ if (bufferId != null) {
+ recordBuffer.consumerLeaseLost(bufferId);
+ }
+ }
+
+ @Override
+ public void shardEnded(final ShardEndedInput shardEndedInput) {
+ if (bufferId != null) {
+ recordBuffer.checkpointEndedShard(bufferId, shardEndedInput.checkpointer());
+ }
+ }
+
+ @Override
+ public void shutdownRequested(final ShutdownRequestedInput shutdownRequestedInput) {
+ if (bufferId != null) {
+ recordBuffer.shutdownShardConsumption(bufferId, shutdownRequestedInput.checkpointer());
+ }
+ }
+ }
+
+ public enum InitialPosition implements DescribedValue {
+ TRIM_HORIZON("Trim Horizon", "Start reading at the last untrimmed record in the shard in the system, which is the oldest data record in the shard."),
+ LATEST("Latest", "Start reading just after the most recent record in the shard, so that you always read the most recent data in the shard."),
+ AT_TIMESTAMP("At Timestamp", "Start reading at the record with the specified timestamp.");
+
+ private final String displayName;
+ private final String description;
+
+ InitialPosition(final String displayName, final String description) {
+ this.displayName = displayName;
+ this.description = description;
+ }
+
+ @Override
+ public String getValue() {
+ return name();
+ }
+
+ @Override
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+ }
+
+ public enum MetricsDestination implements DescribedValue {
Review Comment:
```suggestion
enum MetricsDestination implements DescribedValue {
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/MemoryBoundRecordBuffer.java:
##########
@@ -0,0 +1,674 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import software.amazon.kinesis.exceptions.InvalidStateException;
+import software.amazon.kinesis.exceptions.KinesisClientLibDependencyException;
+import software.amazon.kinesis.exceptions.ShutdownException;
+import software.amazon.kinesis.exceptions.ThrottlingException;
+import software.amazon.kinesis.processor.RecordProcessorCheckpointer;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.nio.ByteBuffer;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.util.Collections.emptyList;
+
+/**
+ * A record buffer which limits the maximum memory usage across all shard buffers.
+ * If the memory limit is reached, adding new records will block until enough memory is freed.
+ */
+final class MemoryBoundRecordBuffer implements RecordBuffer.ForKinesisClientLibrary, RecordBuffer.ForProcessor {
+
+ private final ComponentLog logger;
+
+ private final long checkpointIntervalMillis;
+ private final BlockingMemoryTracker memoryTracker;
+
+ private final AtomicLong bufferIdCounter = new AtomicLong(0);
+ private final ConcurrentMap<ShardBufferId, ShardBuffer> shardBuffers = new ConcurrentHashMap<>();
+
+ /**
+ * A queue with ids shard buffers available for leasing.
+ * <p>
+ * Note: when a buffer is invalidated its id is NOT removed from the queue immediately.
+ */
+ private final Queue<ShardBufferId> buffersToLease = new ConcurrentLinkedQueue<>();
+
+ MemoryBoundRecordBuffer(final ComponentLog logger, final long maxMemoryBytes, final Duration checkpointInterval) {
+ this.logger = logger;
+ this.memoryTracker = new BlockingMemoryTracker(logger, maxMemoryBytes);
+ this.checkpointIntervalMillis = checkpointInterval.toMillis();
+ }
+
+ @Override
+ public ShardBufferId createBuffer(final String shardId) {
+ final ShardBufferId id = new ShardBufferId(shardId, bufferIdCounter.getAndIncrement());
+
+ logger.info("Creating new buffer for shard {} with id {}", shardId, id);
+
+ shardBuffers.put(id, new ShardBuffer(id, logger, checkpointIntervalMillis));
+ buffersToLease.add(id);
+ return id;
+ }
+
+ @Override
+ public void addRecords(final ShardBufferId bufferId, final List<KinesisClientRecord> records, final RecordProcessorCheckpointer checkpointer) {
+ if (records.isEmpty()) {
+ return;
+ }
+
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot add records with sequence and subsequence numbers: {}.{} - {}.{}",
+ bufferId,
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber());
+ return;
+ }
+
+ final RecordBatch recordBatch = new RecordBatch(records, checkpointer, calculateMemoryUsage(records));
+ memoryTracker.reserveMemory(recordBatch);
+ final boolean addedRecords = buffer.offer(recordBatch);
+
+ if (addedRecords) {
+ logger.debug("Successfully added records with sequence and subsequence numbers: {}.{} - {}.{} to buffer with id {}",
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber(),
+ bufferId);
+ } else {
+ logger.debug("Buffer with id {} was invalidated. Cannot add records with sequence and subsequence numbers: {}.{} - {}.{}",
+ bufferId,
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber());
+ // If the buffer was invalidated, we should free memory reserved for these records.
+ memoryTracker.freeMemory(List.of(recordBatch));
+ }
+ }
+
+ @Override
+ public void checkpointEndedShard(final ShardBufferId bufferId, final RecordProcessorCheckpointer checkpointer) {
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot checkpoint the ended shard", bufferId);
+ return;
+ }
+
+ logger.info("Finishing consumption for buffer {}. Checkpointing the ended shard", bufferId);
Review Comment:
```suggestion
logger.debug("Finishing consumption for buffer {}. Checkpointing the ended shard", bufferId);
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ConsumeKinesis.java:
##########
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.annotation.behavior.InputRequirement;
+import org.apache.nifi.annotation.behavior.SystemResource;
+import org.apache.nifi.annotation.behavior.SystemResourceConsideration;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.configuration.DefaultSettings;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.DescribedValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.DataUnit;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processors.aws.credentials.provider.service.AWSCredentialsProviderService;
+import org.apache.nifi.processors.aws.kinesis.ReaderRecordProcessor.ProcessingResult;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import org.apache.nifi.processors.aws.region.RegionUtilV2;
+import org.apache.nifi.proxy.ProxyConfiguration;
+import org.apache.nifi.proxy.ProxyConfigurationService;
+import org.apache.nifi.proxy.ProxySpec;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
+import software.amazon.awssdk.http.Protocol;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.Http2Configuration;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
+import software.amazon.awssdk.services.kinesis.KinesisAsyncClientBuilder;
+import software.amazon.kinesis.common.ConfigsBuilder;
+import software.amazon.kinesis.common.InitialPositionInStream;
+import software.amazon.kinesis.common.InitialPositionInStreamExtended;
+import software.amazon.kinesis.coordinator.Scheduler;
+import software.amazon.kinesis.lifecycle.events.InitializationInput;
+import software.amazon.kinesis.lifecycle.events.LeaseLostInput;
+import software.amazon.kinesis.lifecycle.events.ProcessRecordsInput;
+import software.amazon.kinesis.lifecycle.events.ShardEndedInput;
+import software.amazon.kinesis.lifecycle.events.ShutdownRequestedInput;
+import software.amazon.kinesis.metrics.LogMetricsFactory;
+import software.amazon.kinesis.metrics.MetricsFactory;
+import software.amazon.kinesis.metrics.NullMetricsFactory;
+import software.amazon.kinesis.processor.ShardRecordProcessor;
+import software.amazon.kinesis.processor.ShardRecordProcessorFactory;
+import software.amazon.kinesis.processor.SingleStreamTracker;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.net.URI;
+import java.nio.channels.Channels;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Date;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.APPROXIMATE_ARRIVAL_TIMESTAMP;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.LAST_SUB_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.PARTITION_KEY;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SEQUENCE_NUMBER;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.SHARD_ID;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.STREAM_NAME;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.FIRST_SUB_SEQUENCE_NUMBER;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@Tags({"amazon", "aws", "kinesis", "consume", "stream", "record"})
+@CapabilityDescription("""
+ Consumes data from the specified AWS Kinesis stream and outputs a FlowFile for every processed Record (raw) \
+ or a FlowFile for a batch of processed records if a Record Reader and Record Writer are configured.
+ AWS Kinesis Client Library can take a few minutes on the first start and several seconds on subsequent start \
+ to initialise before starting to fetch data.
+ Uses DynamoDB for check pointing and coordination, and CloudWatch (optional) for metrics.
+ Ensure that the credentials provided have access to DynamoDB and CloudWatch (optional) along with Kinesis.""")
+@WritesAttributes({
+ @WritesAttribute(attribute = STREAM_NAME,
+ description = "The name of the Kinesis Stream from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = SHARD_ID,
+ description = "Shard ID from which all Kinesis Records in the Flow File were read"),
+ @WritesAttribute(attribute = PARTITION_KEY,
+ description = "Partition key of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the first Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = FIRST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the first Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = LAST_SEQUENCE_NUMBER,
+ description = "A Sequence Number of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = LAST_SUB_SEQUENCE_NUMBER,
+ description = "A SubSequence Number of the last Kinesis Record in the Flow File. Generated by KPL when aggregating records into a single Kinesis Record"),
+ @WritesAttribute(attribute = APPROXIMATE_ARRIVAL_TIMESTAMP,
+ description = "Approximate arrival timestamp of the last Kinesis Record in the Flow File"),
+ @WritesAttribute(attribute = MIME_TYPE,
+ description = "Sets the mime.type attribute to the MIME Type specified by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_COUNT,
+ description = "Number of records written to the FlowFiles by the Record Writer (if configured)"),
+ @WritesAttribute(attribute = RECORD_ERROR_MESSAGE,
+ description = "This attribute provides on failure the error message encountered by the Record Reader or Record Writer (if configured)")
+})
+@DefaultSettings(yieldDuration = "100 millis")
+@SystemResourceConsideration(resource = SystemResource.CPU, description = """
+ Kinesis Client Library is used to create a Worker thread for consumption of Kinesis Records.
+ The Worker is initialised and started when this Processor has been scheduled. It runs continually, spawning Kinesis Record Processors as required \
+ to fetch Kinesis Records. The Worker Thread (and any child Record Processor threads) are not controlled by the normal NiFi scheduler as part of the \
+ Concurrent Thread pool and are not released until this processor is stopped.""")
+@SystemResourceConsideration(resource = SystemResource.NETWORK, description = """
+ Kinesis Client Library will continually poll for new Records, \
+ requesting up to a maximum number of Records/bytes per call. This can result in sustained network usage.""")
+@SystemResourceConsideration(resource = SystemResource.MEMORY, description = """
+ ConsumeKinesis buffers Kinesis Records in memory until they can be processed.
+ The maximum size of the buffer is controlled by the 'Max Bytes to Buffer' property.
+ In addition, Kinesis Client Library may cache some amount of data for each shard when the processor's buffer is full.""")
+public class ConsumeKinesis extends AbstractProcessor {
+
+ private static final Duration HTTP_CLIENTS_CONNECTION_TIMEOUT = Duration.ofSeconds(30);
+ private static final Duration HTTP_CLIENTS_READ_TIMEOUT = Duration.ofMinutes(3);
+
+ /**
+ * Best balance between throughput and CPU usage by KCL.
+ */
+ private static final int KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK = 16;
+ private static final int KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES = 512 * 1024; // 512 KiB
+ private static final Duration KINESIS_HTTP_HEALTH_CHECK_PERIOD = Duration.ofMinutes(1);
+
+ static final PropertyDescriptor KINESIS_STREAM_NAME = new PropertyDescriptor.Builder()
+ .name("Amazon Kinesis Stream Name")
+ .description("The name of the Kinesis stream to consume from.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor APPLICATION_NAME = new PropertyDescriptor.Builder()
+ .name("Application Name")
+ .description("The name of the Kinesis application. This is used for DynamoDB table naming and worker coordination.")
+ .required(true)
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .build();
+
+ static final PropertyDescriptor AWS_CREDENTIALS_PROVIDER_SERVICE = new PropertyDescriptor.Builder()
+ .name("AWS Credentials Provider Service")
+ .description("The Controller Service that is used to obtain AWS credentials provider.")
+ .required(true)
+ .identifiesControllerService(AWSCredentialsProviderService.class)
+ .build();
+
+ static final PropertyDescriptor REGION = new PropertyDescriptor.Builder()
+ .name("Region")
+ .description("AWS Region in which the Kinesis stream is located.")
+ .required(true)
+ .allowableValues(RegionUtilV2.getAvailableRegions())
+ .defaultValue(RegionUtilV2.createAllowableValue(Region.US_WEST_2).getValue())
+ .build();
+
+ static final PropertyDescriptor RECORD_READER = new PropertyDescriptor.Builder()
+ .name("Record Reader")
+ .description("""
+ The Record Reader to use for parsing the data received from Kinesis.
+ If not set, the records are written one per FlowFile without parsing.
+
+ The Record Reader is responsible for providing schemas for the records. If the schemas change frequently,
+ it might hinder performance of the processor. (See processor's additional details for more information.)""")
+ .required(false)
+ .identifiesControllerService(RecordReaderFactory.class)
+ .build();
+
+ static final PropertyDescriptor RECORD_WRITER = new PropertyDescriptor.Builder()
+ .name("Record Writer")
+ .description("The Record Writer to use for serializing records.")
+ .required(true)
+ .dependsOn(RECORD_READER)
+ .identifiesControllerService(RecordSetWriterFactory.class)
+ .build();
+
+ static final PropertyDescriptor INITIAL_STREAM_POSITION = new PropertyDescriptor.Builder()
+ .name("Initial Stream Position")
+ .description("The position in the stream where the processor should start reading.")
+ .required(true)
+ .allowableValues(InitialPosition.class)
+ .defaultValue(InitialPosition.TRIM_HORIZON)
+ .build();
+
+ static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new PropertyDescriptor.Builder()
+ .name("Stream Position Timestamp")
+ .description("Timestamp position in stream from which to start reading Kinesis Records. The timestamp must be in ISO 8601 format.")
+ .required(true)
+ .addValidator(StandardValidators.ISO8601_INSTANT_VALIDATOR)
+ .dependsOn(INITIAL_STREAM_POSITION, InitialPosition.AT_TIMESTAMP)
+ .build();
+
+ static final PropertyDescriptor MAX_BYTES_TO_BUFFER = new PropertyDescriptor.Builder()
+ .name("Max Bytes to Buffer")
+ .description("""
+ The maximum size of Kinesis Records that can be buffered in memory before being processed by NiFi.
+ If the buffer size exceeds the limit, the KCL will stop consuming new records until free space is available.
+
+ Using a larger value may improve throughput, but will do so at the expense of using additional heap.
+ Using a smaller value may back off the Kinesis Client Library (KCL) from consuming records if the buffer is full, which may result in lower throughput.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
+ .defaultValue("100 MB")
+ .build();
+
+ static final PropertyDescriptor CHECKPOINT_INTERVAL = new PropertyDescriptor.Builder()
+ .name("Checkpoint Interval")
+ .description("""
+ Interval between checkpointing consumed Kinesis records. To checkpoint records on each NiFi session commit, set this value to 0 seconds.
+
+ Checkpointing too frequently may result in performance degradation and higher DynamoDB costs.
+ Checkpointing too rarely may result in duplicated records whenever a Shard lease is lost or NiFi server restarts.
+ """)
+ .required(true)
+ .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+ .defaultValue("5 sec")
+ .build();
+
+ static final PropertyDescriptor METRICS_DESTINATION = new PropertyDescriptor.Builder()
+ .name("Metrics Destination")
+ .description("Specifies where Kinesis usage metrics are published to.")
+ .required(true)
+ .allowableValues(MetricsDestination.class)
+ .defaultValue(MetricsDestination.NONE)
+ .build();
+
+ static final PropertyDescriptor PROXY_CONFIGURATION_SERVICE = ProxyConfiguration.createProxyConfigPropertyDescriptor(ProxySpec.HTTP, ProxySpec.HTTP_AUTH);
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS = List.of(
+ KINESIS_STREAM_NAME,
+ APPLICATION_NAME,
+ AWS_CREDENTIALS_PROVIDER_SERVICE,
+ REGION,
+ RECORD_READER,
+ RECORD_WRITER,
+ INITIAL_STREAM_POSITION,
+ STREAM_POSITION_TIMESTAMP,
+ MAX_BYTES_TO_BUFFER,
+ CHECKPOINT_INTERVAL,
+ PROXY_CONFIGURATION_SERVICE,
+ METRICS_DESTINATION
+ );
+
+ static final Relationship REL_SUCCESS = new Relationship.Builder()
+ .name("success")
+ .description("FlowFiles that are created when records are successfully read from Kinesis and parsed.")
+ .build();
+
+ static final Relationship REL_PARSE_FAILURE = new Relationship.Builder()
+ .name("parse.failure")
+ .description("FlowFiles that failed to parse using the configured Record Reader.")
+ .build();
+
+ private static final Set<Relationship> RAW_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS);
+ private static final Set<Relationship> RECORD_FILE_RELATIONSHIPS = Set.of(REL_SUCCESS, REL_PARSE_FAILURE);
+
+ private volatile DynamoDbAsyncClient dynamoDbClient;
+ private volatile CloudWatchAsyncClient cloudWatchClient;
+ private volatile KinesisAsyncClient kinesisClient;
+ private volatile Scheduler kinesisScheduler;
+
+ private volatile String streamName;
+ private volatile RecordBuffer.ForProcessor recordBuffer;
+
+ private volatile boolean useReader = false;
+ private volatile Optional<ReaderRecordProcessor> readerRecordProcessor = Optional.empty();
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return useReader ? RECORD_FILE_RELATIONSHIPS : RAW_FILE_RELATIONSHIPS;
+ }
+
+ @Override
+ public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
+ if (descriptor.equals(RECORD_READER)) {
+ useReader = newValue != null;
+ }
+ }
+
+ @OnScheduled
+ public void setup(final ProcessContext context) {
+ final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);
+ if (recordReaderFactory != null) {
+ final RecordSetWriterFactory recordWriterFactory = context.getProperty(RECORD_WRITER).asControllerService(RecordSetWriterFactory.class);
+ readerRecordProcessor = Optional.of(new ReaderRecordProcessor(recordReaderFactory, recordWriterFactory, getLogger()));
+ }
+
+ final Region region = Region.of(context.getProperty(REGION).getValue());
+ final AwsCredentialsProvider credentialsProvider = context.getProperty(AWS_CREDENTIALS_PROVIDER_SERVICE)
+ .asControllerService(AWSCredentialsProviderService.class).getAwsCredentialsProvider();
+
+ kinesisClient = KinesisAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getKinesisEndpointOverride())
+ .httpClient(createKinesisHttpClient(context))
+ .build();
+
+ dynamoDbClient = DynamoDbAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getDynamoDbEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ cloudWatchClient = CloudWatchAsyncClient.builder()
+ .region(region)
+ .credentialsProvider(credentialsProvider)
+ .endpointOverride(getCloudwatchEndpointOverride())
+ .httpClient(createHttpClientBuilder(context).build())
+ .build();
+
+ streamName = context.getProperty(KINESIS_STREAM_NAME).getValue();
+ final InitialPositionInStreamExtended initialPositionExtended = getInitialPosition(context);
+ final SingleStreamTracker streamTracker = new SingleStreamTracker(streamName, initialPositionExtended);
+
+ final long maxBytesToBuffer = context.getProperty(MAX_BYTES_TO_BUFFER).asDataSize(DataUnit.B).longValue();
+ final Duration checkpointInterval = context.getProperty(CHECKPOINT_INTERVAL).asDuration();
+ final MemoryBoundRecordBuffer memoryBoundRecordBuffer = new MemoryBoundRecordBuffer(getLogger(), maxBytesToBuffer, checkpointInterval);
+ recordBuffer = memoryBoundRecordBuffer;
+ final ShardRecordProcessorFactory recordProcessorFactory = () -> new ConsumeKinesisRecordProcessor(memoryBoundRecordBuffer);
+
+ final String applicationName = context.getProperty(APPLICATION_NAME).getValue();
+ final String workerId = getIdentifier();
+ final ConfigsBuilder configsBuilder = new ConfigsBuilder(streamTracker, applicationName, kinesisClient, dynamoDbClient, cloudWatchClient, workerId, recordProcessorFactory);
+
+ final MetricsFactory metricsFactory = configureMetricsFactory(context);
+
+ kinesisScheduler = new Scheduler(
+ configsBuilder.checkpointConfig(),
+ configsBuilder.coordinatorConfig(),
+ configsBuilder.leaseManagementConfig(),
+ configsBuilder.lifecycleConfig(),
+ configsBuilder.metricsConfig().metricsFactory(metricsFactory),
+ configsBuilder.processorConfig(),
+ configsBuilder.retrievalConfig()
+ );
+
+ final Thread schedulerThread = new Thread(kinesisScheduler);
+ schedulerThread.setDaemon(true);
+ schedulerThread.start();
+ }
+
+ /**
+ * Creating Kinesis HTTP client, as per
+ * {@link software.amazon.kinesis.common.KinesisClientUtil#adjustKinesisClientBuilder(KinesisAsyncClientBuilder)}.
+ */
+ private static SdkAsyncHttpClient createKinesisHttpClient(final ProcessContext context) {
+ final int maxConcurrency = KINESIS_HTTP_CLIENT_CONCURRENCY_PER_TASK * context.getMaxConcurrentTasks();
+
+ return createHttpClientBuilder(context)
+ .protocol(Protocol.HTTP2)
+ .maxConcurrency(maxConcurrency)
+ .http2Configuration(Http2Configuration.builder()
+ .initialWindowSize(KINESIS_HTTP_CLIENT_WINDOW_SIZE_BYTES)
+ .healthCheckPingPeriod(KINESIS_HTTP_HEALTH_CHECK_PERIOD)
+ .build())
+ .build();
+ }
+
+ private static NettyNioAsyncHttpClient.Builder createHttpClientBuilder(final ProcessContext context) {
+ final NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder()
+ .connectionTimeout(HTTP_CLIENTS_CONNECTION_TIMEOUT)
+ .readTimeout(HTTP_CLIENTS_READ_TIMEOUT);
+
+ final ProxyConfigurationService proxyConfigService = context.getProperty(PROXY_CONFIGURATION_SERVICE).asControllerService(ProxyConfigurationService.class);
+ if (proxyConfigService != null) {
+ final ProxyConfiguration proxyConfig = proxyConfigService.getConfiguration();
+
+ final software.amazon.awssdk.http.nio.netty.ProxyConfiguration.Builder proxyConfigBuilder = software.amazon.awssdk.http.nio.netty.ProxyConfiguration.builder()
+ .host(proxyConfig.getProxyServerHost())
+ .port(proxyConfig.getProxyServerPort());
+
+ if (proxyConfig.hasCredential()) {
+ proxyConfigBuilder.username(proxyConfig.getProxyUserName());
+ proxyConfigBuilder.password(proxyConfig.getProxyUserPassword());
+ }
+
+ builder.proxyConfiguration(proxyConfigBuilder.build());
+ }
+
+ return builder;
+ }
+
+ private static InitialPositionInStreamExtended getInitialPosition(final ProcessContext context) {
+ final InitialPosition initialPosition = context.getProperty(INITIAL_STREAM_POSITION).asAllowableValue(InitialPosition.class);
+ return switch (initialPosition) {
+ case TRIM_HORIZON ->
+ InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.TRIM_HORIZON);
+ case LATEST -> InitialPositionInStreamExtended.newInitialPosition(InitialPositionInStream.LATEST);
+ case AT_TIMESTAMP -> {
+ final String timestampValue = context.getProperty(STREAM_POSITION_TIMESTAMP).getValue();
+ final Instant timestamp = Instant.parse(timestampValue);
+ yield InitialPositionInStreamExtended.newInitialPositionAtTimestamp(Date.from(timestamp));
+ }
+ };
+ }
+
+ private static @Nullable MetricsFactory configureMetricsFactory(final ProcessContext context) {
+ final MetricsDestination destination = context.getProperty(METRICS_DESTINATION).asAllowableValue(MetricsDestination.class);
+ return switch (destination) {
+ case NONE -> new NullMetricsFactory();
+ case LOGS -> new LogMetricsFactory();
+ case CLOUDWATCH -> null; // If no metrics factory was provided, CloudWatch metrics factory is used by default.
+ };
+ }
+
+ @OnStopped
+ public void onStopped() {
+ if (kinesisScheduler != null) {
+ kinesisScheduler.shutdown();
+ }
+ if (kinesisClient != null) {
+ kinesisClient.close();
+ }
+ if (dynamoDbClient != null) {
+ dynamoDbClient.close();
+ }
+ if (cloudWatchClient != null) {
+ cloudWatchClient.close();
+ }
+
+ recordBuffer = null;
+ readerRecordProcessor = Optional.empty();
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+ final Optional<ShardBufferLease> maybeLease = recordBuffer.acquireBufferLease();
+
+ maybeLease.ifPresentOrElse(
+ lease -> processRecordsFromBuffer(session, lease),
+ context::yield
+ );
+ }
+
+ private void processRecordsFromBuffer(final ProcessSession session, final ShardBufferLease lease) {
+ try {
+ final List<KinesisClientRecord> records = recordBuffer.consumeRecords(lease);
+
+ if (records.isEmpty()) {
+ recordBuffer.returnBufferLease(lease);
+ return;
+ }
+
+ final String shardId = lease.shardId();
+ readerRecordProcessor.ifPresentOrElse(
+ p -> processRecordsWithReader(p, session, shardId, records),
+ () -> processRecordsAsRaw(session, shardId, records)
+ );
+
+ session.adjustCounter("Records Processed", records.size(), false);
+
+ session.commitAsync(
+ () -> commitRecords(lease),
+ __ -> rollbackRecords(lease)
+ );
+ } catch (final RuntimeException e) {
+ getLogger().error("Failed to process records from Kinesis stream: {}", e.getMessage());
+ rollbackRecords(lease);
+ throw e;
+ }
+ }
+
+ private void commitRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.commitConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void rollbackRecords(final ShardBufferLease lease) {
+ try {
+ recordBuffer.rollbackConsumedRecords(lease);
+ } finally {
+ recordBuffer.returnBufferLease(lease);
+ }
+ }
+
+ private void processRecordsAsRaw(final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ for (final KinesisClientRecord record : records) {
+ FlowFile flowFile = session.create();
+ flowFile = session.putAllAttributes(flowFile, ConsumeKinesisAttributes.fromKinesisRecords(streamName, shardId, record, record));
+
+ flowFile = session.write(flowFile, out -> Channels.newChannel(out).write(record.data()));
+
+ session.transfer(flowFile, REL_SUCCESS);
+ }
+ }
+
+ private void processRecordsWithReader(final ReaderRecordProcessor recordProcessor, final ProcessSession session, final String shardId, final List<KinesisClientRecord> records) {
+ final ProcessingResult result = recordProcessor.processRecords(session, streamName, shardId, records);
+
+ session.transfer(result.successFlowFiles(), REL_SUCCESS);
+ session.transfer(result.parseFailureFlowFiles(), REL_PARSE_FAILURE);
+ }
+
+ /**
+ * An adapter between Kinesis Consumer Library and {@link RecordBuffer}.
+ */
+ private static class ConsumeKinesisRecordProcessor implements ShardRecordProcessor {
+
+ private final RecordBuffer.ForKinesisClientLibrary recordBuffer;
+ private volatile @Nullable ShardBufferId bufferId;
+
+ ConsumeKinesisRecordProcessor(final MemoryBoundRecordBuffer recordBuffer) {
+ this.recordBuffer = recordBuffer;
+ }
+
+ @Override
+ public void initialize(final InitializationInput initializationInput) {
+ bufferId = recordBuffer.createBuffer(initializationInput.shardId());
+ }
+
+ @Override
+ public void processRecords(final ProcessRecordsInput processRecordsInput) {
+ if (bufferId == null) {
+ throw new IllegalStateException("Tried to process records before initialize.");
+ }
+ recordBuffer.addRecords(bufferId, processRecordsInput.records(), processRecordsInput.checkpointer());
+ }
+
+ @Override
+ public void leaseLost(final LeaseLostInput leaseLostInput) {
+ if (bufferId != null) {
+ recordBuffer.consumerLeaseLost(bufferId);
+ }
+ }
+
+ @Override
+ public void shardEnded(final ShardEndedInput shardEndedInput) {
+ if (bufferId != null) {
+ recordBuffer.checkpointEndedShard(bufferId, shardEndedInput.checkpointer());
+ }
+ }
+
+ @Override
+ public void shutdownRequested(final ShutdownRequestedInput shutdownRequestedInput) {
+ if (bufferId != null) {
+ recordBuffer.shutdownShardConsumption(bufferId, shutdownRequestedInput.checkpointer());
+ }
+ }
+ }
+
+ public enum InitialPosition implements DescribedValue {
Review Comment:
These values don't need to be public.
```suggestion
enum InitialPosition implements DescribedValue {
```
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/ReaderRecordProcessor.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.schema.access.SchemaNotFoundException;
+import org.apache.nifi.serialization.MalformedRecordException;
+import org.apache.nifi.serialization.RecordReader;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriter;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import org.apache.nifi.serialization.WriteResult;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.serialization.record.RecordSchema;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.channels.Channels;
+import java.util.ArrayList;
+import java.util.List;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.MIME_TYPE;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_COUNT;
+import static org.apache.nifi.processors.aws.kinesis.ConsumeKinesisAttributes.RECORD_ERROR_MESSAGE;
+
+final class ReaderRecordProcessor {
+
+ private final RecordReaderFactory recordReaderFactory;
+ private final RecordSetWriterFactory recordWriterFactory;
+ private final ComponentLog logger;
+
+ ReaderRecordProcessor(
+ final RecordReaderFactory recordReaderFactory,
+ final RecordSetWriterFactory recordWriterFactory,
+ final ComponentLog logger) {
+ this.recordReaderFactory = recordReaderFactory;
+ this.recordWriterFactory = recordWriterFactory;
+ this.logger = logger;
+ }
+
+ ProcessingResult processRecords(
+ final ProcessSession session,
+ final String streamName,
+ final String shardId,
+ final List<KinesisClientRecord> records) {
+ final List<FlowFile> successFlowFiles = new ArrayList<>();
+ final List<FlowFile> failureFlowFiles = new ArrayList<>();
+
+ ActiveFlowFile activeFlowFile = null;
+
+ for (final KinesisClientRecord kinesisRecord : records) {
+ final int dataSize = kinesisRecord.data().remaining();
+ final byte[] data = new byte[dataSize];
+ kinesisRecord.data().get(data);
+
+ try (final InputStream in = new ByteArrayInputStream(data);
+ final RecordReader reader = recordReaderFactory.createRecordReader(emptyMap(), in, data.length, logger)) {
+
+ Record record;
+ while ((record = reader.nextRecord()) != null) {
+ final RecordSchema writeSchema = recordWriterFactory.getSchema(emptyMap(), record.getSchema());
+
+ if (activeFlowFile == null) {
+ activeFlowFile = ActiveFlowFile.startNewFile(logger, session, recordWriterFactory, writeSchema, streamName, shardId);
+ } else if (!writeSchema.equals(activeFlowFile.schema())) {
+ // If the write schema has changed, we need to complete the current FlowFile and start a new one.
+ final FlowFile completedFlowFile = activeFlowFile.complete();
+ successFlowFiles.add(completedFlowFile);
+
+ activeFlowFile = ActiveFlowFile.startNewFile(logger, session, recordWriterFactory, writeSchema, streamName, shardId);
+ }
+
+ activeFlowFile.writeRecord(record, kinesisRecord);
+ }
+ } catch (final IOException | MalformedRecordException | SchemaNotFoundException e) {
+ logger.error("Reader or Writer failed to process Kinesis Record with Stream Name [{}] Shard Id [{}] Sequence Number [{}] SubSequence Number [{}]",
+ streamName, shardId, kinesisRecord.sequenceNumber(), kinesisRecord.subSequenceNumber(), e);
+ final FlowFile failureFlowFile = createParseFailureFlowFile(session, streamName, shardId, kinesisRecord, e);
+ failureFlowFiles.add(failureFlowFile);
+ }
+ }
+
+ if (activeFlowFile != null) {
+ final FlowFile completedFlowFile = activeFlowFile.complete();
+ successFlowFiles.add(completedFlowFile);
+ }
+
+ return new ProcessingResult(successFlowFiles, failureFlowFiles);
+ }
+
+ private static FlowFile createParseFailureFlowFile(
+ final ProcessSession session,
+ final String streamName,
+ final String shardId,
+ final KinesisClientRecord record,
+ final Exception e) {
+ FlowFile flowFile = session.create();
+
+ record.data().rewind();
+ flowFile = session.write(flowFile, out -> Channels.newChannel(out).write(record.data()));
+
+ flowFile = session.putAllAttributes(flowFile, ConsumeKinesisAttributes.fromKinesisRecords(streamName, shardId, record, record));
+
+ final Throwable cause = e.getCause() != null ? e.getCause() : e;
+ final String errorMessage = cause.getLocalizedMessage() != null ? cause.getLocalizedMessage() : "NiFi Reader or Writer failed to process Kinesis Record";
+ flowFile = session.putAttribute(flowFile, RECORD_ERROR_MESSAGE, errorMessage);
+
+ return flowFile;
+ }
+
+ record ProcessingResult(List<FlowFile> successFlowFiles, List<FlowFile> parseFailureFlowFiles) {
+ }
+
+ /**
+ * A class that manages a single {@link FlowFile} with a static schema that is currently being written to.
+ * On a schema change the current {@link ActiveFlowFile} should be completed a new instance of this class
+ * with a new schema should be created.
+ *
+ * An {@link ActiveFlowFile} must have at least one record written to it before it can be completed.
+ */
+ private static final class ActiveFlowFile {
+
+ private final ComponentLog logger;
+
+ private final ProcessSession session;
+ private final FlowFile flowFile;
+ private final RecordSetWriter writer;
+ private final RecordSchema schema;
+
+ private final String streamName;
+ private final String shardId;
+
+ private KinesisClientRecord firstRecord;
+ private KinesisClientRecord lastRecord;
+
+ private ActiveFlowFile(
+ final ComponentLog logger,
+ final ProcessSession session,
+ final FlowFile flowFile,
+ final RecordSetWriter writer,
+ final RecordSchema schema,
+ final String streamName,
+ final String shardId) {
+ this.logger = logger;
+ this.session = session;
+ this.flowFile = flowFile;
+ this.writer = writer;
+ this.schema = schema;
+ this.streamName = streamName;
+ this.shardId = shardId;
+ }
+
+ static ActiveFlowFile startNewFile(
+ final ComponentLog logger,
+ final ProcessSession session,
+ final RecordSetWriterFactory recordWriterFactory,
+ final RecordSchema writeSchema,
+ final String streamName,
+ final String shardId) throws SchemaNotFoundException {
+ final FlowFile flowFile = session.create();
+ final OutputStream outputStream = session.write(flowFile);
+
+ try {
+ final RecordSetWriter writer = recordWriterFactory.createWriter(logger, writeSchema, outputStream, flowFile);
+ writer.beginRecordSet();
+
+ return new ActiveFlowFile(logger, session, flowFile, writer, writeSchema, streamName, shardId);
+
+ } catch (final SchemaNotFoundException e) {
+ logger.debug("Failed to find writeSchema for Kinesis stream record: {}", e.getMessage());
+ try {
+ outputStream.close();
+ } catch (final IOException ioe) {
+ logger.warn("Failed to close FlowFile output stream: {}", ioe.getMessage());
+ e.addSuppressed(ioe);
+ }
+ throw e;
+
+ } catch (final IOException e) {
+ final ProcessException processException = new ProcessException("Failed to create a writer for a FlowFile", e);
+
+ logger.debug("Stopping Kinesis records processing. Failed to create a writer for a FlowFile: {}", e.getMessage());
+ try {
+ outputStream.close();
+ } catch (final IOException ioe) {
+ logger.warn("Failed to close FlowFile output stream: {}", ioe.getMessage());
+ processException.addSuppressed(ioe);
+ }
+ throw processException;
+ }
+ }
+
+ RecordSchema schema() {
+ return schema;
+ }
+
+ void writeRecord(final Record record, final KinesisClientRecord kinesisRecord) {
+ try {
+ writer.write(record);
+ } catch (final IOException e) {
+ logger.debug("Stopping Kinesis records processing. Failed to write to a FlowFile: {}", e.getMessage());
+ throw new ProcessException("Failed to write a record into a FlowFile", e);
+ }
+
+ if (firstRecord == null) {
+ firstRecord = kinesisRecord;
+ }
+ lastRecord = kinesisRecord;
+ }
+
+ FlowFile complete() {
+ if (firstRecord == null || lastRecord == null) {
+ throw new IllegalStateException("Cannot complete an ActiveFlowFile that has no records");
+ }
+
+ try {
+ final WriteResult finalResult = writer.finishRecordSet();
+ writer.close();
+
+ FlowFile completedFlowFile = session.putAllAttributes(this.flowFile, ConsumeKinesisAttributes.fromKinesisRecords(streamName, shardId, firstRecord, lastRecord));
+ completedFlowFile = session.putAllAttributes(completedFlowFile, finalResult.getAttributes());
+ completedFlowFile = session.putAttribute(completedFlowFile, RECORD_COUNT, String.valueOf(finalResult.getRecordCount()));
+ completedFlowFile = session.putAttribute(completedFlowFile, MIME_TYPE, writer.getMimeType());
+
+ return completedFlowFile;
+
+ } catch (final IOException e) {
+ final ProcessException processException = new ProcessException("Failed to complete a FlowFile", e);
+
+ logger.debug("Stopping Kinesis records processing. Failed to complete a FlowFile: {}", e.getMessage());
+ try {
+ writer.close();
+ } catch (final IOException ioe) {
+ logger.warn("Failed to close writer: {}", ioe.getMessage());
+ processException.addSuppressed(ioe);
Review Comment:
The suppressed exception should be included in the thrown exception, so is this log needed?
##########
nifi-extension-bundles/nifi-aws-bundle/nifi-aws-kinesis/src/main/java/org/apache/nifi/processors/aws/kinesis/MemoryBoundRecordBuffer.java:
##########
@@ -0,0 +1,674 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.processors.aws.kinesis;
+
+import jakarta.annotation.Nullable;
+import org.apache.nifi.logging.ComponentLog;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferId;
+import org.apache.nifi.processors.aws.kinesis.RecordBuffer.ShardBufferLease;
+import software.amazon.kinesis.exceptions.InvalidStateException;
+import software.amazon.kinesis.exceptions.KinesisClientLibDependencyException;
+import software.amazon.kinesis.exceptions.ShutdownException;
+import software.amazon.kinesis.exceptions.ThrottlingException;
+import software.amazon.kinesis.processor.RecordProcessorCheckpointer;
+import software.amazon.kinesis.retrieval.KinesisClientRecord;
+
+import java.nio.ByteBuffer;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static java.util.Collections.emptyList;
+
+/**
+ * A record buffer which limits the maximum memory usage across all shard buffers.
+ * If the memory limit is reached, adding new records will block until enough memory is freed.
+ */
+final class MemoryBoundRecordBuffer implements RecordBuffer.ForKinesisClientLibrary, RecordBuffer.ForProcessor {
+
+ private final ComponentLog logger;
+
+ private final long checkpointIntervalMillis;
+ private final BlockingMemoryTracker memoryTracker;
+
+ private final AtomicLong bufferIdCounter = new AtomicLong(0);
+ private final ConcurrentMap<ShardBufferId, ShardBuffer> shardBuffers = new ConcurrentHashMap<>();
+
+ /**
+ * A queue with ids shard buffers available for leasing.
+ * <p>
+ * Note: when a buffer is invalidated its id is NOT removed from the queue immediately.
+ */
+ private final Queue<ShardBufferId> buffersToLease = new ConcurrentLinkedQueue<>();
+
+ MemoryBoundRecordBuffer(final ComponentLog logger, final long maxMemoryBytes, final Duration checkpointInterval) {
+ this.logger = logger;
+ this.memoryTracker = new BlockingMemoryTracker(logger, maxMemoryBytes);
+ this.checkpointIntervalMillis = checkpointInterval.toMillis();
+ }
+
+ @Override
+ public ShardBufferId createBuffer(final String shardId) {
+ final ShardBufferId id = new ShardBufferId(shardId, bufferIdCounter.getAndIncrement());
+
+ logger.info("Creating new buffer for shard {} with id {}", shardId, id);
+
+ shardBuffers.put(id, new ShardBuffer(id, logger, checkpointIntervalMillis));
+ buffersToLease.add(id);
+ return id;
+ }
+
+ @Override
+ public void addRecords(final ShardBufferId bufferId, final List<KinesisClientRecord> records, final RecordProcessorCheckpointer checkpointer) {
+ if (records.isEmpty()) {
+ return;
+ }
+
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot add records with sequence and subsequence numbers: {}.{} - {}.{}",
+ bufferId,
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber());
+ return;
+ }
+
+ final RecordBatch recordBatch = new RecordBatch(records, checkpointer, calculateMemoryUsage(records));
+ memoryTracker.reserveMemory(recordBatch);
+ final boolean addedRecords = buffer.offer(recordBatch);
+
+ if (addedRecords) {
+ logger.debug("Successfully added records with sequence and subsequence numbers: {}.{} - {}.{} to buffer with id {}",
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber(),
+ bufferId);
+ } else {
+ logger.debug("Buffer with id {} was invalidated. Cannot add records with sequence and subsequence numbers: {}.{} - {}.{}",
+ bufferId,
+ records.getFirst().sequenceNumber(),
+ records.getFirst().subSequenceNumber(),
+ records.getLast().sequenceNumber(),
+ records.getLast().subSequenceNumber());
+ // If the buffer was invalidated, we should free memory reserved for these records.
+ memoryTracker.freeMemory(List.of(recordBatch));
+ }
+ }
+
+ @Override
+ public void checkpointEndedShard(final ShardBufferId bufferId, final RecordProcessorCheckpointer checkpointer) {
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot checkpoint the ended shard", bufferId);
+ return;
+ }
+
+ logger.info("Finishing consumption for buffer {}. Checkpointing the ended shard", bufferId);
+ buffer.checkpointEndedShard(checkpointer);
+
+ logger.debug("Removing buffer with id {} after successful ended shard checkpoint", bufferId);
+ shardBuffers.remove(bufferId);
+ }
+
+ @Override
+ public void shutdownShardConsumption(final ShardBufferId bufferId, final RecordProcessorCheckpointer checkpointer) {
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot shutdown shard consumption", bufferId);
+ return;
+ }
+
+ logger.info("Shutting down the buffer {}. Checkpointing last consumed record", bufferId);
+ buffer.shutdownBuffer(checkpointer);
+
+ logger.debug("Removing buffer with id {} after successful last consumed record checkpoint", bufferId);
+ shardBuffers.remove(bufferId);
+ }
+
+ @Override
+ public void consumerLeaseLost(final ShardBufferId bufferId) {
+ final ShardBuffer buffer = shardBuffers.remove(bufferId);
+
+ logger.info("Lease lost for buffer {}. Invalidating it", bufferId);
+
+ if (buffer != null) {
+ final Collection<RecordBatch> invalidatedBatches = buffer.invalidate();
+ memoryTracker.freeMemory(invalidatedBatches);
+ }
+ }
+
+ @Override
+ public Optional<ShardBufferLease> acquireBufferLease() {
+ final Set<ShardBufferId> seenBuffers = new HashSet<>();
+
+ while (true) {
+ final ShardBufferId bufferId = buffersToLease.poll();
+ if (bufferId == null) {
+ // The queue is empty or all buffers were seen already. Nothing to consume.
+ return Optional.empty();
+ }
+
+ if (seenBuffers.contains(bufferId)) {
+ // If the same buffer is seen again, there is a high chance we iterated through most of the buffers and didn't find any that isn't empty.
+ // To avoid burning CPU we return empty here, even if some buffer received records in the meantime. It will be picked up in the next iteration.
+ buffersToLease.add(bufferId);
+ return Optional.empty();
+ }
+
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+
+ if (buffer == null) {
+ // By the time the bufferId is polled, it might have been invalidated. No need to return it to the queue.
+ logger.debug("Buffer with id {} was removed while polling for lease. Continuing to poll.", bufferId);
+ } else if (buffer.isEmpty()) {
+ seenBuffers.add(bufferId);
+ buffersToLease.add(bufferId);
+ logger.debug("Buffer with id {} is empty. Continuing to poll.", bufferId);
+ } else {
+ logger.debug("Acquired lease for buffer {}", bufferId);
+ return Optional.of(new StandardShardBufferLease(bufferId));
+ }
+ }
+ }
+
+ @Override
+ public List<KinesisClientRecord> consumeRecords(final ShardBufferLease lease) {
+ if (!(lease instanceof StandardShardBufferLease standardLease)) {
+ throw new IllegalArgumentException("Unexpected lease type: " + lease.getClass().getName());
+ }
+
+ if (standardLease.returnedToPool.get()) {
+ logger.warn("Attempting to consume records from a buffer that was already returned to the pool. Ignoring.");
+ return emptyList();
+ }
+
+ final ShardBufferId bufferId = standardLease.bufferId;
+
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot consume records", bufferId);
+ return emptyList();
+ }
+
+ return buffer.consumeRecords();
+ }
+
+ @Override
+ public void commitConsumedRecords(final ShardBufferLease lease) {
+ if (!(lease instanceof StandardShardBufferLease standardLease)) {
+ throw new IllegalArgumentException("Unexpected lease type: " + lease.getClass().getName());
+ }
+
+ if (standardLease.returnedToPool.get()) {
+ logger.warn("Attempting to commit records from a buffer that was already returned to the pool. Ignoring.");
+ return;
+ }
+
+ final ShardBufferId bufferId = standardLease.bufferId;
+
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+ if (buffer == null) {
+ logger.debug("Buffer with id {} not found. Cannot commit consumed records", bufferId);
+ return;
+ }
+
+ final List<RecordBatch> consumedBatches = buffer.commitConsumedRecords();
+ memoryTracker.freeMemory(consumedBatches);
+ }
+
+ @Override
+ public void rollbackConsumedRecords(final ShardBufferLease lease) {
+ if (!(lease instanceof StandardShardBufferLease standardLease)) {
+ throw new IllegalArgumentException("Unexpected lease type: " + lease.getClass().getName());
+ }
+
+ if (standardLease.returnedToPool.get()) {
+ logger.warn("Attempting to rollback records from a buffer that was already returned to the pool. Ignoring.");
+ return;
+ }
+
+ final ShardBufferId bufferId = standardLease.bufferId;
+ final ShardBuffer buffer = shardBuffers.get(bufferId);
+
+ if (buffer != null) {
+ buffer.rollbackConsumedRecords();
+ }
+ }
+
+ @Override
+ public void returnBufferLease(final ShardBufferLease lease) {
+ if (!(lease instanceof StandardShardBufferLease standardLease)) {
+ throw new IllegalArgumentException("Unexpected lease type: " + lease.getClass().getName());
+ }
+
+ if (standardLease.returnedToPool.getAndSet(true)) {
+ logger.warn("Attempting to return a buffer that was already returned to the pool. Ignoring.");
+ return;
+ }
+
+ final ShardBufferId bufferId = standardLease.bufferId;
+ buffersToLease.add(bufferId);
+
+ logger.debug("The buffer {} is available for lease again", bufferId);
+ }
+
+ private static class StandardShardBufferLease implements ShardBufferLease {
+
+ private final ShardBufferId bufferId;
+ private final AtomicBoolean returnedToPool = new AtomicBoolean(false);
+
+ StandardShardBufferLease(final ShardBufferId bufferId) {
+ this.bufferId = bufferId;
+ }
+
+ @Override
+ public String shardId() {
+ return bufferId.shardId();
+ }
+ }
+
+ /**
+ * A memory tracker which blocks a thread when the memory usage exceeds the allowed maximum.
+ * <p>
+ * In order to make progress, the memory consumption may exceed the limit, but any new records will not be accepted.
+ * This is done to support the case when a single record batch is larger than the allowed memory limit.
+ */
+ private static class BlockingMemoryTracker {
+
+ private static final long AWAIT_MILLIS = 100;
+
+ private final ComponentLog logger;
+
+ private final long maxMemoryBytes;
+
+ private final AtomicLong consumedMemoryBytes = new AtomicLong(0);
+ /**
+ * Whenever memory is freed a latch opens. Then replaced with a new one.
+ */
+ private final AtomicReference<CountDownLatch> memoryAvailableLatch = new AtomicReference<>(new CountDownLatch(1));
+
+ BlockingMemoryTracker(final ComponentLog logger, final long maxMemoryBytes) {
+ this.logger = logger;
+ this.maxMemoryBytes = maxMemoryBytes;
+ }
+
+ void reserveMemory(final RecordBatch recordBatch) {
+ final long consumedBytes = recordBatch.batchSizeBytes();
+
+ if (consumedBytes == 0) {
+ return;
+ }
+
+ while (true) {
+ final long currentlyConsumedBytes = consumedMemoryBytes.get();
+
+ if (currentlyConsumedBytes >= maxMemoryBytes) {
+ // Not enough memory available, need to wait.
+ try {
+ memoryAvailableLatch.get().await(AWAIT_MILLIS, TimeUnit.MILLISECONDS);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Thread interrupted while waiting for available memory in RecordBuffer", e);
+ }
+ } else {
+ final long newConsumedBytes = currentlyConsumedBytes + consumedBytes;
+ if (consumedMemoryBytes.compareAndSet(currentlyConsumedBytes, newConsumedBytes)) {
+ logger.debug("Reserved {} bytes for {} records. Total consumed memory: {} bytes",
+ consumedBytes, recordBatch.size(), newConsumedBytes);
+ break;
+ }
+ // If we're here, the compare and set operation failed, as another thread has modified the gauge in meantime.
+ // Retrying the operation.
+ }
+ }
+ }
+
+ void freeMemory(final Collection<RecordBatch> consumedBatches) {
+ if (consumedBatches.isEmpty()) {
+ return;
+ }
+
+ long freedBytes = 0;
+ for (final RecordBatch batch : consumedBatches) {
+ freedBytes += batch.batchSizeBytes();
+ }
+
+ while (true) {
+ final long currentlyConsumedBytes = consumedMemoryBytes.get();
+ if (currentlyConsumedBytes < freedBytes) {
+ throw new IllegalStateException("Attempting to free more memory than currently used");
+ }
+
+ final long newTotal = currentlyConsumedBytes - freedBytes;
+ if (consumedMemoryBytes.compareAndSet(currentlyConsumedBytes, newTotal)) {
+ logger.debug("Freed {} bytes for {} batches. Total consumed memory: {} bytes",
+ freedBytes, consumedBatches.size(), newTotal);
+
+ final CountDownLatch oldLatch = memoryAvailableLatch.getAndSet(new CountDownLatch(1));
+ oldLatch.countDown(); // Release any waiting threads for free memory.
+ break;
+ }
+ // If we're here, the compare and set operation failed, as another thread has modified the gauge in meantime.
+ // Retrying the operation.
+ }
+ }
+ }
+
+ private record RecordBatch(List<KinesisClientRecord> records,
+ @Nullable RecordProcessorCheckpointer checkpointer,
+ long batchSizeBytes) {
+ int size() {
+ return records.size();
+ }
+ }
+
+ private long calculateMemoryUsage(final Collection<KinesisClientRecord> records) {
+ long totalBytes = 0;
+ for (final KinesisClientRecord record : records) {
+ final ByteBuffer data = record.data();
+ if (data != null) {
+ totalBytes += data.capacity();
+ }
+ }
+ return totalBytes;
+ }
+
+ /**
+ * ShardBuffer stores all record batches for a single shard in two queues:
+ * - IN_PROGRESS: record batches that have been consumed but not yet checkpointed.
+ * - PENDING: record batches that have been added but not yet consumed.
+ * <p>
+ * When consuming records all PENDING batches are moved to IN_PROGRESS.
+ * After a successful checkpoint all IN_PROGRESS batches are cleared.
+ * After a rollback all IN_PROGRESS batches are kept, allowing to retry consumption.
+ * <p>
+ * Each batch preserves the original grouping of records as provided by Kinesis
+ * along with their associated checkpointer, ensuring atomicity.
+ */
+ private static class ShardBuffer {
+
+ private static final long AWAIT_MILLIS = 100;
+
+ // Retry configuration.
+ private static final int MAX_RETRY_ATTEMPTS = 5;
+ private static final long BASE_RETRY_DELAY_MILLIS = 100;
+ private static final long MAX_RETRY_DELAY_MILLIS = 10_000;
+ private static final Random RANDOM = new Random();
+
+ private final ShardBufferId bufferId;
+ private final ComponentLog logger;
+
+ private final long checkpointIntervalMillis;
+ private volatile long nextCheckpointTimeMillis;
+ /**
+ * A last records checkpointer that was ignored due to the checkpoint interval.
+ * If null, the last checkpoint was successful or no checkpoint was attempted yet.
+ */
+ private volatile @Nullable RecordProcessorCheckpointer lastIgnoredCheckpointer = null;
+
+ /**
+ * Queues for managing record batches with their checkpointers in different states.
+ */
+ private final Queue<RecordBatch> inProgressBatches = new ConcurrentLinkedQueue<>();
+ private final Queue<RecordBatch> pendingBatches = new ConcurrentLinkedQueue<>();
+ /**
+ * Counter for tracking the number of batches in the buffer. Can be larger than the number of batches in the queues.
+ */
+ private final AtomicInteger batchesCount = new AtomicInteger(0);
+
+ /**
+ * A countdown latch that is used to signal when the buffer becomes empty. Used when ShardBuffer should be closed.
+ */
+ private volatile @Nullable CountDownLatch emptyBufferLatch = null;
+ private final AtomicBoolean invalidated = new AtomicBoolean(false);
+
+ ShardBuffer(final ShardBufferId bufferId, final ComponentLog logger, final long checkpointIntervalMillis) {
+ this.bufferId = bufferId;
+ this.logger = logger;
+ this.checkpointIntervalMillis = checkpointIntervalMillis;
+ this.nextCheckpointTimeMillis = System.currentTimeMillis() + checkpointIntervalMillis;
+ }
+
+ /**
+ * @param recordBatch record batch with records to add.
+ * @return true if the records were added successfully, false if a buffer was invalidated.
+ */
+ boolean offer(final RecordBatch recordBatch) {
+ if (invalidated.get()) {
+ return false;
+ }
+
+ // Batches count must be always equal to or larger than the number of batches in the queues.
+ // Thus, the ordering of the operations.
+ batchesCount.incrementAndGet();
+ pendingBatches.offer(recordBatch);
+
+ return true;
+ }
+
+ List<KinesisClientRecord> consumeRecords() {
+ if (invalidated.get()) {
+ return emptyList();
+ }
+
+ RecordBatch pendingBatch;
+ while ((pendingBatch = pendingBatches.poll()) != null) {
+ inProgressBatches.offer(pendingBatch);
+ }
+
+ final List<KinesisClientRecord> recordsToConsume = new ArrayList<>();
+ for (final RecordBatch batch : inProgressBatches) {
+ recordsToConsume.addAll(batch.records());
+ }
+
+ return recordsToConsume;
+ }
+
+ List<RecordBatch> commitConsumedRecords() {
+ if (invalidated.get()) {
+ return emptyList();
+ }
+
+ final List<RecordBatch> checkpointedBatches = new ArrayList<>();
+ RecordBatch batch;
+ while ((batch = inProgressBatches.poll()) != null) {
+ checkpointedBatches.add(batch);
+ }
+
+ if (checkpointedBatches.isEmpty()) {
+ // The buffer could be invalidated in the meantime, or no records were consumed.
+ return emptyList();
+ }
+
+ // Batches count must always be equal to or larger than the number of batches in the queues.
+ // To achieve so, the count is decreased only after the queue has been emptied.
+ batchesCount.addAndGet(-checkpointedBatches.size());
+
+ final RecordProcessorCheckpointer lastBatchCheckpointer = checkpointedBatches.getLast().checkpointer();
+ if (System.currentTimeMillis() >= nextCheckpointTimeMillis) {
+ checkpointSafely(lastBatchCheckpointer);
+ nextCheckpointTimeMillis = System.currentTimeMillis() + checkpointIntervalMillis;
+ lastIgnoredCheckpointer = null;
+ } else {
+ // Saving the checkpointer for later, in case shutdown happens before the next checkpoint.
+ lastIgnoredCheckpointer = lastBatchCheckpointer;
+ }
+
+ final CountDownLatch localEmptyBufferLatch = this.emptyBufferLatch;
+ if (localEmptyBufferLatch != null && isEmpty()) {
+ // If the latch is not null, it means we are waiting for the buffer to become empty.
+ localEmptyBufferLatch.countDown();
+ }
+
+ return checkpointedBatches;
+ }
+
+ void rollbackConsumedRecords() {
+ if (invalidated.get()) {
+ return;
+ }
+
+ for (final RecordBatch recordBatch : inProgressBatches) {
+ for (final KinesisClientRecord record : recordBatch.records()) {
+ record.data().rewind();
+ }
+ }
+ }
+
+ void checkpointEndedShard(final RecordProcessorCheckpointer checkpointer) {
+ while (true) {
+ if (invalidated.get()) {
+ return;
+ }
+
+ if (batchesCount.get() == 0) {
+ // Buffer is empty, perform final checkpoint.
+ checkpointSafely(checkpointer);
+ return;
+ }
+
+ // Wait for the records to be consumed first.
+ try {
+ final CountDownLatch localEmptyBufferLatch = new CountDownLatch(1);
+ this.emptyBufferLatch = localEmptyBufferLatch;
+ localEmptyBufferLatch.await(AWAIT_MILLIS, TimeUnit.MILLISECONDS);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Thread interrupted while waiting for records to be consumed", e);
+ }
+ }
+ }
+
+ void shutdownBuffer(final RecordProcessorCheckpointer checkpointer) {
+ if (invalidated.get()) {
+ return;
+ }
+
+ if (batchesCount.get() == 0) {
+ checkpointSafely(checkpointer);
+ } else {
+ // If there are still records in the buffer, checkpointing with the latest provided checkpointer is not safe.
+ // But, if the records were committed without checkpointing in the past, we can checkpoint them now.
+ final RecordProcessorCheckpointer lastCheckpointer = this.lastIgnoredCheckpointer;
+ if (lastCheckpointer != null) {
+ checkpointSafely(lastCheckpointer);
+ }
+ }
+ }
+
+ Collection<RecordBatch> invalidate() {
+ if (invalidated.getAndSet(true)) {
+ return emptyList();
+ }
+
+ final List<RecordBatch> batches = new ArrayList<>();
+ RecordBatch batch;
+ // If both consumeRecords and invalidate are called concurrently, invalidation must always consume all batches.
+ // Since consumeRecords moves batches from pending to in_progress, during invalidation pending batches should be drained first.
+ while ((batch = pendingBatches.poll()) != null) {
+ batches.add(batch);
+ }
+ while ((batch = inProgressBatches.poll()) != null) {
+ batches.add(batch);
+ }
+
+ // No need to adjust batchesCount after invalidation.
+
+ return batches;
+ }
+
+ /**
+ * Checks if the buffer has any records. <b>Can produce false negatives.</b>
+ *
+ * @return whether there are any records in the buffer.
+ */
+ boolean isEmpty() {
+ return invalidated.get() || batchesCount.get() == 0;
+ }
+
+ /**
+ * Performs checkpointing using exponential backoff and jitter, if needed.
+ *
+ * @param checkpointer the checkpointer to use.
+ */
+ private void checkpointSafely(final @Nullable RecordProcessorCheckpointer checkpointer) {
+ if (checkpointer == null) {
+ logger.warn("Attempting to checkpoint records with a null checkpointer. Ignoring checkpoint");
+ return;
+ }
+
+ logger.debug("Performing checkpoint for buffer with id {}", bufferId);
+
+ for (int attempt = 1; attempt <= MAX_RETRY_ATTEMPTS; attempt++) {
+ try {
+ checkpointer.checkpoint();
+ if (attempt > 1) {
+ logger.debug("Checkpoint succeeded on attempt {}", attempt);
+ }
+ return; // Success, exit retry loop.
+ } catch (final ThrottlingException | InvalidStateException | KinesisClientLibDependencyException e) {
+ if (attempt == MAX_RETRY_ATTEMPTS) {
+ logger.error("Failed to checkpoint after {} attempts, giving up. Last error: {}",
+ MAX_RETRY_ATTEMPTS, e.getMessage(), e);
+ return; // Max attempts reached, give up.
+ }
+
+ final long delayMillis = calculateRetryDelay(attempt);
+
+ logger.debug("Checkpoint failed on attempt {} with {}, retrying in {} ms",
+ attempt, e.getMessage(), delayMillis);
+
+ try {
+ Thread.sleep(delayMillis);
+ } catch (final InterruptedException ie) {
+ Thread.currentThread().interrupt();
+ logger.warn("Thread interrupted while waiting to retry checkpoint. Exiting retry loop", ie);
+ return;
+ }
+ } catch (final ShutdownException e) {
+ logger.warn("Failed to checkpoint records due to shutdown: {}. Ignoring checkpoint", e.getMessage(), e);
Review Comment:
The message is in the stack trace, so it does not need to be repeated.
```suggestion
logger.warn("Failed to checkpoint records due to shutdown: Ignoring checkpoint", e);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org