turcsanyip commented on a change in pull request #4822:
URL: https://github.com/apache/nifi/pull/4822#discussion_r629948591



##########
File path: 
nifi-nar-bundles/nifi-aws-bundle/nifi-aws-processors/src/main/java/org/apache/nifi/processors/aws/kinesis/stream/ConsumeKinesisStream.java
##########
@@ -0,0 +1,704 @@
+/*
+ * 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.stream;
+
+import 
com.amazonaws.services.kinesis.clientlibrary.interfaces.v2.IRecordProcessorFactory;
+import 
com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream;
+import 
com.amazonaws.services.kinesis.clientlibrary.lib.worker.KinesisClientLibConfiguration;
+import com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker;
+import com.amazonaws.services.kinesis.metrics.impl.NullMetricsFactory;
+import org.apache.commons.beanutils.BeanUtilsBean;
+import org.apache.commons.beanutils.ConvertUtilsBean2;
+import org.apache.commons.beanutils.FluentPropertyBeanIntrospector;
+import org.apache.commons.beanutils.PropertyUtilsBean;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.nifi.annotation.behavior.DynamicProperties;
+import org.apache.nifi.annotation.behavior.DynamicProperty;
+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.TriggerSerially;
+import org.apache.nifi.annotation.behavior.WritesAttribute;
+import org.apache.nifi.annotation.behavior.WritesAttributes;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.annotation.documentation.SeeAlso;
+import org.apache.nifi.annotation.documentation.Tags;
+import org.apache.nifi.annotation.lifecycle.OnStopped;
+import org.apache.nifi.components.AllowableValue;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.components.ValidationContext;
+import org.apache.nifi.components.ValidationResult;
+import org.apache.nifi.context.PropertyContext;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.ProcessSessionFactory;
+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.AbstractAWSCredentialsProviderProcessor;
+import 
org.apache.nifi.processors.aws.kinesis.stream.record.AbstractKinesisRecordProcessor;
+import 
org.apache.nifi.processors.aws.kinesis.stream.record.KinesisRecordProcessorRaw;
+import 
org.apache.nifi.processors.aws.kinesis.stream.record.KinesisRecordProcessorRecord;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.RecordSetWriterFactory;
+import org.apache.nifi.serialization.record.RecordFieldType;
+
+import java.lang.reflect.InvocationTargetException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.stream.Collectors;
+
+@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
+@TriggerSerially
+@Tags({"amazon", "aws", "kinesis", "consume", "stream"})
+@CapabilityDescription("Reads 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. " +
+        "At-least-once delivery of all Kinesis Records within the Stream while 
the processor is running. " +
+        "AWS Kinesis Client Library can take several seconds to initialise 
before starting to fetch data. " +
+        "Uses DynamoDB for check pointing and CloudWatch (optional) for 
metrics. " +
+        "Ensure that the credentials provided have access to DynamoDB and 
CloudWatch (optional) along with Kinesis.")
+@WritesAttributes({
+        @WritesAttribute(attribute = 
AbstractKinesisRecordProcessor.AWS_KINESIS_PARTITION_KEY,
+                description = "Partition key of the (last) Kinesis Record read 
from the Shard"),
+        @WritesAttribute(attribute = 
AbstractKinesisRecordProcessor.AWS_KINESIS_SHARD_ID,
+                description = "Shard ID from which the Kinesis Record was 
read"),
+        @WritesAttribute(attribute = 
AbstractKinesisRecordProcessor.AWS_KINESIS_SEQUENCE_NUMBER,
+                description = "The unique identifier of the (last) Kinesis 
Record within its Shard"),
+        @WritesAttribute(attribute = 
AbstractKinesisRecordProcessor.AWS_KINESIS_APPROXIMATE_ARRIVAL_TIMESTAMP,
+                description = "Approximate arrival timestamp of the (last) 
Kinesis Record read from the stream"),
+        @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)")
+})
+@DynamicProperties({
+        @DynamicProperty(name="Kinesis Client Library (KCL) Configuration 
property name",
+                description="Override default KCL Configuration properties 
with required values. Supports setting of values via the \"with\" " +
+                        "methods on the KCL Configuration class. Specify the 
property to be set without the leading prefix, e.g. 
\"maxInitialisationAttempts\" " +
+                        "will call \"withMaxInitialisationAttempts\" and set 
the provided value. Only supports setting of simple property values, e.g. 
String, " +
+                        "int, long and boolean. Does not allow override of KCL 
Configuration settings handled by non-dynamic processor properties.",
+                expressionLanguageScope = ExpressionLanguageScope.NONE, 
value="Value to set in the KCL Configuration property")
+})
+@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 
triggered. 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.")
+@SeeAlso(PutKinesisStream.class)
+@SuppressWarnings({"java:S110", "java:S2160", "java:S3077"})
+public class ConsumeKinesisStream extends AbstractKinesisStreamProcessor {
+    static final AllowableValue TRIM_HORIZON = new AllowableValue(
+            InitialPositionInStream.TRIM_HORIZON.toString(),
+            InitialPositionInStream.TRIM_HORIZON.toString(),
+            "Start reading at the last untrimmed record in the shard in the 
system, which is the oldest data record in the shard."
+    );
+    static final AllowableValue LATEST = new AllowableValue(
+            InitialPositionInStream.LATEST.toString(),
+            InitialPositionInStream.LATEST.toString(),
+            "Start reading just after the most recent record in the shard, so 
that you always read the most recent data in the shard."
+    );
+    static final AllowableValue AT_TIMESTAMP = new AllowableValue(
+            InitialPositionInStream.AT_TIMESTAMP.toString(),
+            InitialPositionInStream.AT_TIMESTAMP.toString(), "Start reading 
from the position denoted by a specific time stamp, provided in the value 
Timestamp."
+    );
+
+    public static final PropertyDescriptor APPLICATION_NAME = new 
PropertyDescriptor.Builder()
+            .displayName("Application Name")
+            .name("amazon-kinesis-stream-application-name")
+            .description("The Kinesis stream reader application name.")
+            .addValidator(StandardValidators.NON_BLANK_VALIDATOR)
+            .required(true).build();
+
+    public static final PropertyDescriptor INITIAL_STREAM_POSITION = new 
PropertyDescriptor.Builder()
+            .displayName("Initial Stream Position")
+            .name("amazon-kinesis-stream-initial-position")
+            .description("Initial position to read Kinesis streams.")
+            .allowableValues(LATEST, TRIM_HORIZON, AT_TIMESTAMP)
+            .defaultValue(LATEST.getValue())
+            .required(true).build();
+
+    public static final PropertyDescriptor STREAM_POSITION_TIMESTAMP = new 
PropertyDescriptor.Builder()
+            .displayName("Stream Position Timestamp")
+            .name("amazon-kinesis-stream-position-timestamp")
+            .description("Timestamp position in stream from which to start 
reading Kinesis Records. " +
+                    "Required if " + INITIAL_STREAM_POSITION.getDescription() 
+ " is " + AT_TIMESTAMP.getDisplayName() + ". " +
+                    "Uses the Timestamp Format to parse value into a Date.")
+            .addValidator(StandardValidators.NON_BLANK_VALIDATOR) // 
customValidate checks the value against TIMESTAMP_FORMAT
+            .dependsOn(INITIAL_STREAM_POSITION, AT_TIMESTAMP)
+            .required(false).build();
+
+    public static final PropertyDescriptor TIMESTAMP_FORMAT = new 
PropertyDescriptor.Builder()
+            .displayName("Timestamp Format")
+            .name("amazon-kinesis-stream-timestamp-format")
+            .description("Format to use for parsing the " + 
STREAM_POSITION_TIMESTAMP.getDisplayName() + " into a Date " +
+                    "and converting the Kinesis Record's Approximate Arrival 
Timestamp into a FlowFile attribute.")
+            .addValidator((subject, input, context) -> {
+                if (StringUtils.isNotBlank(input)) {
+                    try {
+                        DateTimeFormatter.ofPattern(input);
+                    } catch (Exception e) {
+                        return new 
ValidationResult.Builder().valid(false).subject(subject).input(input)
+                                .explanation("Must be a valid 
java.time.DateTimeFormatter pattern, e.g. " + 
RecordFieldType.TIMESTAMP.getDefaultFormat())
+                                .build();
+                    }
+                }
+                return new 
ValidationResult.Builder().valid(true).subject(subject).build();
+            })
+            .defaultValue(RecordFieldType.TIMESTAMP.getDefaultFormat())
+            
.expressionLanguageSupported(ExpressionLanguageScope.VARIABLE_REGISTRY)
+            .required(true).build();
+
+    public static final PropertyDescriptor FAILOVER_TIMEOUT = new 
PropertyDescriptor.Builder()
+            .displayName("Failover Timeout")
+            .name("amazon-kinesis-stream-failover-timeout")
+            .description("Kinesis Client Library failover timeout")
+            .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+            .defaultValue("30 secs")
+            .required(true).build();
+
+    public static final PropertyDescriptor GRACEFUL_SHUTDOWN_TIMEOUT = new 
PropertyDescriptor.Builder()
+            .displayName("Graceful Shutdown Timeout")
+            .name("amazon-kinesis-stream-graceful-shutdown-timeout")
+            .description("Kinesis Client Library graceful shutdown timeout")
+            .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+            .defaultValue("20 secs")
+            .required(true).build();
+
+    public static final PropertyDescriptor CHECKPOINT_INTERVAL = new 
PropertyDescriptor.Builder()
+            .displayName("Checkpoint Interval")
+            .name("amazon-kinesis-stream-checkpoint-interval")
+            .description("Interval between Kinesis checkpoints")
+            .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
+            .defaultValue("3 secs")

Review comment:
       @ChrisSamo632 I did some kind of performance tests with 1 Mio messages 
in 12 shards and running NiFi on my local machine (no cluster). It took 64-74 
seconds with default settings (no additional dynamic properties).
   
   The interesting thing that I could not see any difference when I set 
Checkpoint Interval to 0 sec (that is checkpointing "synchronously" after each 
bunch of messages received in `IRecordProcessor.processRecords()` callback). It 
seems there is no significant overhead of checkpointing more frequently (and it 
has the advantage of having fewer duplicated messages in case of restart).
   
   It can be investigated further in a follow-up ticket with more sophisticated 
performance tests (nifi cluster, non-local machine, tuning KCL properties, etc) 
and the default can be adjusted if that is reasonable.
   
   




-- 
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.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to