You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by bb...@apache.org on 2016/03/11 15:23:20 UTC
[2/2] nifi git commit: NIFI-899 Rewrite of ListenUDP to use new
listener framework,
includes the following changes: - Adding Network Interface property to
AbstractListenEventProcessor and ListenSyslog - Adding sending host and
sending port to DatagramCha
NIFI-899 Rewrite of ListenUDP to use new listener framework, includes the following changes:
- Adding Network Interface property to AbstractListenEventProcessor and ListenSyslog
- Adding sending host and sending port to DatagramChannelDispatcher
- Creation of common base class AbstractListenEventBatchingProcessor
- Refactor of ListenUDP, ListenTCP, and ListenRELP to all extend from AbstractListenEventBatchingProcessor
- Changing DatagramChannelDispatcher, socket handlers, and RELP handler to use offer() when queueing instead of put(), and log an error if the offer failed
This closes #266
Project: http://git-wip-us.apache.org/repos/asf/nifi/repo
Commit: http://git-wip-us.apache.org/repos/asf/nifi/commit/1373bf67
Tree: http://git-wip-us.apache.org/repos/asf/nifi/tree/1373bf67
Diff: http://git-wip-us.apache.org/repos/asf/nifi/diff/1373bf67
Branch: refs/heads/master
Commit: 1373bf672586ba5ddcfa697c45c832ccc79425cb
Parents: 8f01165
Author: Bryan Bende <bb...@apache.org>
Authored: Thu Mar 10 09:19:54 2016 -0500
Committer: Bryan Bende <bb...@apache.org>
Committed: Fri Mar 11 09:07:05 2016 -0500
----------------------------------------------------------------------
.../AbstractListenEventBatchingProcessor.java | 269 +++++++++
.../listen/AbstractListenEventProcessor.java | 160 ++---
.../util/listen/ListenerProperties.java | 87 +++
.../listen/dispatcher/ChannelDispatcher.java | 8 +-
.../dispatcher/DatagramChannelDispatcher.java | 36 +-
.../dispatcher/SocketChannelDispatcher.java | 7 +-
.../processor/util/listen/event/EventQueue.java | 67 +++
.../util/listen/event/StandardEventFactory.java | 37 ++
.../util/listen/handler/ChannelHandler.java | 5 +-
.../handler/socket/SSLSocketChannelHandler.java | 4 +-
.../socket/StandardSocketChannelHandler.java | 4 +-
.../nifi/processors/standard/ListenRELP.java | 122 ++--
.../nifi/processors/standard/ListenSyslog.java | 15 +-
.../nifi/processors/standard/ListenTCP.java | 110 +---
.../nifi/processors/standard/ListenUDP.java | 587 +++----------------
.../standard/relp/handler/RELPFrameHandler.java | 14 +-
.../handler/RELPSSLSocketChannelHandler.java | 2 +-
.../relp/handler/RELPSocketChannelHandler.java | 2 +-
.../processors/standard/TestListenRELP.java | 63 +-
.../processors/standard/TestListenSyslog.java | 2 +-
.../nifi/processors/standard/TestListenUDP.java | 408 ++++++++-----
.../relp/handler/TestRELPFrameHandler.java | 5 +-
.../handler/TestRELPSocketChannelHandler.java | 2 +-
23 files changed, 1044 insertions(+), 972 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventBatchingProcessor.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventBatchingProcessor.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventBatchingProcessor.java
new file mode 100644
index 0000000..9a97671
--- /dev/null
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventBatchingProcessor.java
@@ -0,0 +1,269 @@
+/*
+ * 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.processor.util.listen;
+
+import static org.apache.nifi.processor.util.listen.ListenerProperties.NETWORK_INTF_NAME;
+
+import org.apache.nifi.annotation.lifecycle.OnScheduled;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.ProcessorInitializationContext;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.io.OutputStreamCallback;
+import org.apache.nifi.processor.util.StandardValidators;
+import org.apache.nifi.processor.util.listen.event.Event;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * An abstract processor that extends from AbstractListenEventProcessor and adds common functionality for
+ * batching events into a single FlowFile.
+ *
+ * @param <E> the type of Event
+ */
+public abstract class AbstractListenEventBatchingProcessor<E extends Event> extends AbstractListenEventProcessor<E> {
+
+ public static final PropertyDescriptor MAX_BATCH_SIZE = new PropertyDescriptor.Builder()
+ .name("Max Batch Size")
+ .description(
+ "The maximum number of messages to add to a single FlowFile. If multiple messages are available, they will be concatenated along with "
+ + "the <Message Delimiter> up to this configured maximum number of messages")
+ .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR)
+ .expressionLanguageSupported(false)
+ .defaultValue("1")
+ .required(true)
+ .build();
+ public static final PropertyDescriptor MESSAGE_DELIMITER = new PropertyDescriptor.Builder()
+ .name("Message Delimiter")
+ .displayName("Batching Message Delimiter")
+ .description("Specifies the delimiter to place between messages when multiple messages are bundled together (see <Max Batch Size> property).")
+ .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
+ .defaultValue("\\n")
+ .required(true)
+ .build();
+
+ // it is only the array reference that is volatile - not the contents.
+ protected volatile byte[] messageDemarcatorBytes;
+
+ @Override
+ protected void init(final ProcessorInitializationContext context) {
+ final List<PropertyDescriptor> descriptors = new ArrayList<>();
+ descriptors.add(NETWORK_INTF_NAME);
+ descriptors.add(PORT);
+ descriptors.add(RECV_BUFFER_SIZE);
+ descriptors.add(MAX_MESSAGE_QUEUE_SIZE);
+ descriptors.add(MAX_SOCKET_BUFFER_SIZE);
+ descriptors.add(CHARSET);
+ descriptors.add(MAX_BATCH_SIZE);
+ descriptors.add(MESSAGE_DELIMITER);
+ descriptors.addAll(getAdditionalProperties());
+ this.descriptors = Collections.unmodifiableList(descriptors);
+
+ final Set<Relationship> relationships = new HashSet<>();
+ relationships.add(REL_SUCCESS);
+ relationships.addAll(getAdditionalRelationships());
+ this.relationships = Collections.unmodifiableSet(relationships);
+ }
+
+ @Override
+ @OnScheduled
+ public void onScheduled(ProcessContext context) throws IOException {
+ super.onScheduled(context);
+ final String msgDemarcator = context.getProperty(MESSAGE_DELIMITER).getValue().replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t");
+ messageDemarcatorBytes = msgDemarcator.getBytes(charset);
+ }
+
+ @Override
+ public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
+ final int maxBatchSize = context.getProperty(MAX_BATCH_SIZE).asInteger();
+ final Map<String,FlowFileEventBatch> batches = getBatches(session, maxBatchSize, messageDemarcatorBytes);
+
+ // if the size is 0 then there was nothing to process so return
+ // we don't need to yield here because we have a long poll in side of getBatches
+ if (batches.size() == 0) {
+ return;
+ }
+
+ final List<E> allEvents = new ArrayList<>();
+
+ for (Map.Entry<String,FlowFileEventBatch> entry : batches.entrySet()) {
+ FlowFile flowFile = entry.getValue().getFlowFile();
+ final List<E> events = entry.getValue().getEvents();
+
+ if (flowFile.getSize() == 0L || events.size() == 0) {
+ session.remove(flowFile);
+ getLogger().debug("No data written to FlowFile from batch {}; removing FlowFile", new Object[] {entry.getKey()});
+ continue;
+ }
+
+ final Map<String,String> attributes = getAttributes(entry.getValue());
+ flowFile = session.putAllAttributes(flowFile, attributes);
+
+ getLogger().debug("Transferring {} to success", new Object[] {flowFile});
+ session.transfer(flowFile, REL_SUCCESS);
+ session.adjustCounter("FlowFiles Transferred to Success", 1L, false);
+
+ // the sender and command will be the same for all events based on the batch key
+ final String transitUri = getTransitUri(entry.getValue());
+ session.getProvenanceReporter().receive(flowFile, transitUri);
+
+ allEvents.addAll(events);
+ }
+
+ // let sub-classes take any additional actions
+ postProcess(context, session, allEvents);
+ }
+
+ /**
+ * Creates the attributes for the FlowFile of the given batch.
+ *
+ * @param batch the current batch
+ * @return the Map of FlowFile attributes
+ */
+ protected abstract Map<String,String> getAttributes(final FlowFileEventBatch batch);
+
+ /**
+ * Creates the transit uri to be used when reporting a provenance receive event for the given batch.
+ *
+ * @param batch the current batch
+ * @return the transit uri string
+ */
+ protected abstract String getTransitUri(final FlowFileEventBatch batch);
+
+ /**
+ * Called at the end of onTrigger to allow sub-classes to take post processing action on the events
+ *
+ * @param context the current context
+ * @param session the current session
+ * @param events the list of all events processed by the current execution of onTrigger
+ */
+ protected void postProcess(ProcessContext context, ProcessSession session, final List<E> events) {
+ // empty implementation so sub-classes only have to override if necessary
+ }
+
+ /**
+ * Batches together up to the batchSize events. Events are grouped together based on a batch key which
+ * by default is the sender of the event, but can be override by sub-classes.
+ *
+ * This method will return when batchSize has been reached, or when no more events are available on the queue.
+ *
+ * @param session the current session
+ * @param totalBatchSize the total number of events to process
+ * @param messageDemarcatorBytes the demarcator to put between messages when writing to a FlowFile
+ *
+ * @return a Map from the batch key to the FlowFile and events for that batch, the size of events in all
+ * the batches will be <= batchSize
+ */
+ protected Map<String,FlowFileEventBatch> getBatches(final ProcessSession session, final int totalBatchSize,
+ final byte[] messageDemarcatorBytes) {
+
+ final Map<String,FlowFileEventBatch> batches = new HashMap<>();
+ for (int i=0; i < totalBatchSize; i++) {
+ final E event = getMessage(true, true, session);
+ if (event == null) {
+ break;
+ }
+
+ final String batchKey = getBatchKey(event);
+ FlowFileEventBatch batch = batches.get(batchKey);
+
+ // if we don't have a batch for this key then create a new one
+ if (batch == null) {
+ batch = new FlowFileEventBatch(session.create(), new ArrayList<E>());
+ batches.put(batchKey, batch);
+ }
+
+ // add the current event to the batch
+ batch.getEvents().add(event);
+
+ // append the event's data to the FlowFile, write the demarcator first if not on the first event
+ final boolean writeDemarcator = (i > 0);
+ try {
+ final byte[] rawMessage = event.getData();
+ FlowFile appendedFlowFile = session.append(batch.getFlowFile(), new OutputStreamCallback() {
+ @Override
+ public void process(final OutputStream out) throws IOException {
+ if (writeDemarcator) {
+ out.write(messageDemarcatorBytes);
+ }
+
+ out.write(rawMessage);
+ }
+ });
+
+ // update the FlowFile reference in the batch object
+ batch.setFlowFile(appendedFlowFile);
+
+ } catch (final Exception e) {
+ getLogger().error("Failed to write contents of the message to FlowFile due to {}; will re-queue message and try again",
+ new Object[] {e.getMessage()}, e);
+ errorEvents.offer(event);
+ break;
+ }
+ }
+
+ return batches;
+ }
+
+ /**
+ * @param event an event that was pulled off the queue
+ *
+ * @return a key to use for batching events together, by default this uses the sender of the
+ * event, but sub-classes should override this to batch by something else
+ */
+ protected String getBatchKey(final E event) {
+ return event.getSender();
+ }
+
+ /**
+ * Wrapper to hold a FlowFile and the events that have been appended to it.
+ */
+ protected final class FlowFileEventBatch {
+
+ private FlowFile flowFile;
+ private List<E> events;
+
+ public FlowFileEventBatch(final FlowFile flowFile, final List<E> events) {
+ this.flowFile = flowFile;
+ this.events = events;
+ }
+
+ public FlowFile getFlowFile() {
+ return flowFile;
+ }
+
+ public List<E> getEvents() {
+ return events;
+ }
+
+ public void setFlowFile(FlowFile flowFile) {
+ this.flowFile = flowFile;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventProcessor.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventProcessor.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventProcessor.java
index 84fa5dc..43d01b8 100644
--- a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventProcessor.java
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/AbstractListenEventProcessor.java
@@ -16,30 +16,31 @@
*/
package org.apache.nifi.processor.util.listen;
+import static org.apache.nifi.processor.util.listen.ListenerProperties.NETWORK_INTF_NAME;
+
+import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.lifecycle.OnUnscheduled;
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.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
-import org.apache.nifi.processor.io.OutputStreamCallback;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.processor.util.listen.dispatcher.ChannelDispatcher;
import org.apache.nifi.processor.util.listen.event.Event;
import java.io.IOException;
-import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@@ -55,6 +56,8 @@ import java.util.concurrent.TimeUnit;
*/
public abstract class AbstractListenEventProcessor<E extends Event> extends AbstractProcessor {
+
+
public static final PropertyDescriptor PORT = new PropertyDescriptor
.Builder().name("Port")
.description("The port to listen on for communication.")
@@ -105,23 +108,7 @@ public abstract class AbstractListenEventProcessor<E extends Event> extends Abst
.defaultValue("2")
.required(true)
.build();
- public static final PropertyDescriptor MAX_BATCH_SIZE = new PropertyDescriptor.Builder()
- .name("Max Batch Size")
- .description(
- "The maximum number of messages to add to a single FlowFile. If multiple messages are available, they will be concatenated along with "
- + "the <Message Delimiter> up to this configured maximum number of messages")
- .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR)
- .expressionLanguageSupported(false)
- .defaultValue("1")
- .required(true)
- .build();
- public static final PropertyDescriptor MESSAGE_DELIMITER = new PropertyDescriptor.Builder()
- .name("Message Delimiter")
- .description("Specifies the delimiter to place between messages when multiple messages are bundled together (see <Max Batch Size> property).")
- .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
- .defaultValue("\\n")
- .required(true)
- .build();
+
public static final Relationship REL_SUCCESS = new Relationship.Builder()
.name("success")
@@ -130,8 +117,8 @@ public abstract class AbstractListenEventProcessor<E extends Event> extends Abst
public static final int POLL_TIMEOUT_MS = 20;
- private Set<Relationship> relationships;
- private List<PropertyDescriptor> descriptors;
+ protected Set<Relationship> relationships;
+ protected List<PropertyDescriptor> descriptors;
protected volatile int port;
protected volatile Charset charset;
@@ -142,6 +129,7 @@ public abstract class AbstractListenEventProcessor<E extends Event> extends Abst
@Override
protected void init(final ProcessorInitializationContext context) {
final List<PropertyDescriptor> descriptors = new ArrayList<>();
+ descriptors.add(NETWORK_INTF_NAME);
descriptors.add(PORT);
descriptors.add(RECV_BUFFER_SIZE);
descriptors.add(MAX_MESSAGE_QUEUE_SIZE);
@@ -190,11 +178,18 @@ public abstract class AbstractListenEventProcessor<E extends Event> extends Abst
port = context.getProperty(PORT).asInteger();
events = new LinkedBlockingQueue<>(context.getProperty(MAX_MESSAGE_QUEUE_SIZE).asInteger());
+ final String nicIPAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions().getValue();
final int maxChannelBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
+ InetAddress nicIPAddress = null;
+ if (!StringUtils.isEmpty(nicIPAddressStr)) {
+ NetworkInterface netIF = NetworkInterface.getByName(nicIPAddressStr);
+ nicIPAddress = netIF.getInetAddresses().nextElement();
+ }
+
// create the dispatcher and call open() to bind to the given port
dispatcher = createDispatcher(context, events);
- dispatcher.open(port, maxChannelBufferSize);
+ dispatcher.open(nicIPAddress, port, maxChannelBufferSize);
// start a thread to run the dispatcher
final Thread readerThread = new Thread(dispatcher);
@@ -232,6 +227,21 @@ public abstract class AbstractListenEventProcessor<E extends Event> extends Abst
}
/**
+ * Creates a pool of ByteBuffers with the given size.
+ *
+ * @param poolSize the number of buffers to initialize the pool with
+ * @param bufferSize the size of each buffer
+ * @return a blocking queue with size equal to poolSize and each buffer equal to bufferSize
+ */
+ protected BlockingQueue<ByteBuffer> createBufferPool(final int poolSize, final int bufferSize) {
+ final LinkedBlockingQueue<ByteBuffer> bufferPool = new LinkedBlockingQueue<>(poolSize);
+ for (int i = 0; i < poolSize; i++) {
+ bufferPool.offer(ByteBuffer.allocate(bufferSize));
+ }
+ return bufferPool;
+ }
+
+ /**
* If pollErrorQueue is true, the error queue will be checked first and event will be
* returned from the error queue if available.
*
@@ -271,104 +281,4 @@ public abstract class AbstractListenEventProcessor<E extends Event> extends Abst
return event;
}
- /**
- * Batches together up to the batchSize events. Events are grouped together based on a batch key which
- * by default is the sender of the event, but can be override by sub-classes.
- *
- * This method will return when batchSize has been reached, or when no more events are available on the queue.
- *
- * @param session the current session
- * @param totalBatchSize the total number of events to process
- * @param messageDemarcatorBytes the demarcator to put between messages when writing to a FlowFile
- *
- * @return a Map from the batch key to the FlowFile and events for that batch, the size of events in all
- * the batches will be <= batchSize
- */
- protected Map<String,FlowFileEventBatch> getBatches(final ProcessSession session, final int totalBatchSize,
- final byte[] messageDemarcatorBytes) {
-
- final Map<String,FlowFileEventBatch> batches = new HashMap<>();
- for (int i=0; i < totalBatchSize; i++) {
- final E event = getMessage(true, true, session);
- if (event == null) {
- break;
- }
-
- final String batchKey = getBatchKey(event);
- FlowFileEventBatch batch = batches.get(batchKey);
-
- // if we don't have a batch for this key then create a new one
- if (batch == null) {
- batch = new FlowFileEventBatch(session.create(), new ArrayList<E>());
- batches.put(batchKey, batch);
- }
-
- // add the current event to the batch
- batch.getEvents().add(event);
-
- // append the event's data to the FlowFile, write the demarcator first if not on the first event
- final boolean writeDemarcator = (i > 0);
- try {
- final byte[] rawMessage = event.getData();
- FlowFile appendedFlowFile = session.append(batch.getFlowFile(), new OutputStreamCallback() {
- @Override
- public void process(final OutputStream out) throws IOException {
- if (writeDemarcator) {
- out.write(messageDemarcatorBytes);
- }
-
- out.write(rawMessage);
- }
- });
-
- // update the FlowFile reference in the batch object
- batch.setFlowFile(appendedFlowFile);
-
- } catch (final Exception e) {
- getLogger().error("Failed to write contents of the message to FlowFile due to {}; will re-queue message and try again",
- new Object[] {e.getMessage()}, e);
- errorEvents.offer(event);
- break;
- }
- }
-
- return batches;
- }
-
- /**
- * @param event an event that was pulled off the queue
- *
- * @return a key to use for batching events together, by default this uses the sender of the
- * event, but sub-classes should override this to batch by something else
- */
- protected String getBatchKey(final E event) {
- return event.getSender();
- }
-
- /**
- * Wrapper to hold a FlowFile and the events that have been appended to it.
- */
- protected final class FlowFileEventBatch {
-
- private FlowFile flowFile;
- private List<E> events;
-
- public FlowFileEventBatch(final FlowFile flowFile, final List<E> events) {
- this.flowFile = flowFile;
- this.events = events;
- }
-
- public FlowFile getFlowFile() {
- return flowFile;
- }
-
- public List<E> getEvents() {
- return events;
- }
-
- public void setFlowFile(FlowFile flowFile) {
- this.flowFile = flowFile;
- }
- }
-
}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/ListenerProperties.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/ListenerProperties.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/ListenerProperties.java
new file mode 100644
index 0000000..5e4c639
--- /dev/null
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/ListenerProperties.java
@@ -0,0 +1,87 @@
+/*
+ * 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.processor.util.listen;
+
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.components.ValidationContext;
+import org.apache.nifi.components.ValidationResult;
+import org.apache.nifi.components.Validator;
+import org.apache.nifi.expression.AttributeExpression;
+
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Shared properties.
+ */
+public class ListenerProperties {
+
+ private static final Set<String> interfaceSet = new HashSet<>();
+
+ static {
+ try {
+ final Enumeration<NetworkInterface> interfaceEnum = NetworkInterface.getNetworkInterfaces();
+ while (interfaceEnum.hasMoreElements()) {
+ final NetworkInterface ifc = interfaceEnum.nextElement();
+ interfaceSet.add(ifc.getName());
+ }
+ } catch (SocketException e) {
+ }
+ }
+
+ public static final PropertyDescriptor NETWORK_INTF_NAME = new PropertyDescriptor.Builder()
+ .name("Local Network Interface")
+ .description("The name of a local network interface to be used to restrict listening to a specific LAN.")
+ .addValidator(new Validator() {
+ @Override
+ public ValidationResult validate(String subject, String input, ValidationContext context) {
+ ValidationResult result = new ValidationResult.Builder()
+ .subject("Local Network Interface").valid(true).input(input).build();
+ if (interfaceSet.contains(input.toLowerCase())) {
+ return result;
+ }
+
+ String message;
+ String realValue = input;
+ try {
+ if (context.isExpressionLanguagePresent(input)) {
+ AttributeExpression ae = context.newExpressionLanguageCompiler().compile(input);
+ realValue = ae.evaluate();
+ }
+
+ if (interfaceSet.contains(realValue.toLowerCase())) {
+ return result;
+ }
+
+ message = realValue + " is not a valid network name. Valid names are " + interfaceSet.toString();
+
+ } catch (IllegalArgumentException e) {
+ message = "Not a valid AttributeExpression: " + e.getMessage();
+ }
+ result = new ValidationResult.Builder().subject("Local Network Interface")
+ .valid(false).input(input).explanation(message).build();
+
+ return result;
+ }
+ })
+ .expressionLanguageSupported(true)
+ .build();
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/ChannelDispatcher.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/ChannelDispatcher.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/ChannelDispatcher.java
index cff230e..444aeb1 100644
--- a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/ChannelDispatcher.java
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/ChannelDispatcher.java
@@ -17,6 +17,7 @@
package org.apache.nifi.processor.util.listen.dispatcher;
import java.io.IOException;
+import java.net.InetAddress;
/**
* Dispatches handlers for a given channel.
@@ -27,11 +28,16 @@ public interface ChannelDispatcher extends Runnable {
* Opens the dispatcher listening on the given port and attempts to set the
* OS socket buffer to maxBufferSize.
*
+ * @param nicAddress the local network interface to listen on, if null will listen on the wildcard address
+ * which means listening on all local network interfaces
+ *
* @param port the port to listen on
+ *
* @param maxBufferSize the size to set the OS socket buffer to
+ *
* @throws IOException if an error occurred listening on the given port
*/
- void open(int port, int maxBufferSize) throws IOException;
+ void open(InetAddress nicAddress, int port, int maxBufferSize) throws IOException;
/**
* @return the port being listened to
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/DatagramChannelDispatcher.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/DatagramChannelDispatcher.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/DatagramChannelDispatcher.java
index e362e15..3fb9ba9 100644
--- a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/DatagramChannelDispatcher.java
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/DatagramChannelDispatcher.java
@@ -21,8 +21,10 @@ import org.apache.nifi.logging.ProcessorLog;
import org.apache.nifi.processor.util.listen.event.Event;
import org.apache.nifi.processor.util.listen.event.EventFactory;
import org.apache.nifi.processor.util.listen.event.EventFactoryUtil;
+import org.apache.nifi.processor.util.listen.event.EventQueue;
import java.io.IOException;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.StandardSocketOptions;
@@ -42,8 +44,10 @@ public class DatagramChannelDispatcher<E extends Event<DatagramChannel>> impleme
private final EventFactory<E> eventFactory;
private final BlockingQueue<ByteBuffer> bufferPool;
- private final BlockingQueue<E> events;
+ private final EventQueue<E> events;
private final ProcessorLog logger;
+ private final String sendingHost;
+ private final Integer sendingPort;
private Selector selector;
private DatagramChannel datagramChannel;
@@ -53,10 +57,21 @@ public class DatagramChannelDispatcher<E extends Event<DatagramChannel>> impleme
final BlockingQueue<ByteBuffer> bufferPool,
final BlockingQueue<E> events,
final ProcessorLog logger) {
+ this(eventFactory, bufferPool, events, logger, null, null);
+ }
+
+ public DatagramChannelDispatcher(final EventFactory<E> eventFactory,
+ final BlockingQueue<ByteBuffer> bufferPool,
+ final BlockingQueue<E> events,
+ final ProcessorLog logger,
+ final String sendingHost,
+ final Integer sendingPort) {
this.eventFactory = eventFactory;
this.bufferPool = bufferPool;
- this.events = events;
this.logger = logger;
+ this.sendingHost = sendingHost;
+ this.sendingPort = sendingPort;
+ this.events = new EventQueue<>(events, logger);
if (bufferPool == null || bufferPool.size() == 0) {
throw new IllegalArgumentException("A pool of available ByteBuffers is required");
@@ -64,7 +79,7 @@ public class DatagramChannelDispatcher<E extends Event<DatagramChannel>> impleme
}
@Override
- public void open(final int port, int maxBufferSize) throws IOException {
+ public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
stopped = false;
datagramChannel = DatagramChannel.open();
datagramChannel.configureBlocking(false);
@@ -78,7 +93,17 @@ public class DatagramChannelDispatcher<E extends Event<DatagramChannel>> impleme
+ "maximum receive buffer");
}
}
- datagramChannel.socket().bind(new InetSocketAddress(port));
+
+ // we don't have to worry about nicAddress being null here because InetSocketAddress already handles it
+ datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
+ datagramChannel.socket().bind(new InetSocketAddress(nicAddress, port));
+
+ // if a sending host and port were provided then connect to that specific address to only receive
+ // datagrams from that host/port, otherwise we can receive datagrams from any host/port
+ if (sendingHost != null && sendingPort != null) {
+ datagramChannel.connect(new InetSocketAddress(sendingHost, sendingPort));
+ }
+
selector = Selector.open();
datagramChannel.register(selector, SelectionKey.OP_READ);
}
@@ -115,9 +140,8 @@ public class DatagramChannelDispatcher<E extends Event<DatagramChannel>> impleme
final Map<String,String> metadata = EventFactoryUtil.createMapWithSender(sender);
final E event = eventFactory.create(bytes, metadata, null);
+ events.offer(event);
- // queue the raw message with the sender, block until space is available
- events.put(event);
buffer.clear();
}
}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/SocketChannelDispatcher.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/SocketChannelDispatcher.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/SocketChannelDispatcher.java
index 670dba4..70b2bae 100644
--- a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/SocketChannelDispatcher.java
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/dispatcher/SocketChannelDispatcher.java
@@ -27,6 +27,7 @@ import org.apache.nifi.security.util.SslContextFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.IOException;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
@@ -104,7 +105,7 @@ public class SocketChannelDispatcher<E extends Event<SocketChannel>> implements
}
@Override
- public void open(final int port, int maxBufferSize) throws IOException {
+ public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
stopped = false;
executor = Executors.newFixedThreadPool(maxConnections);
@@ -119,7 +120,9 @@ public class SocketChannelDispatcher<E extends Event<SocketChannel>> implements
+ "maximum receive buffer");
}
}
- serverSocketChannel.socket().bind(new InetSocketAddress(port));
+
+ serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port));
+
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/EventQueue.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/EventQueue.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/EventQueue.java
new file mode 100644
index 0000000..4afaf40
--- /dev/null
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/EventQueue.java
@@ -0,0 +1,67 @@
+/*
+ * 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.processor.util.listen.event;
+
+import org.apache.commons.lang3.Validate;
+import org.apache.nifi.logging.ProcessorLog;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Wraps a BlockingQueue to centralize logic for offering events across UDP, TCP, and SSL.
+ *
+ * @param <E> the type of event
+ */
+public class EventQueue<E extends Event> {
+
+ /**
+ * The default number of milliseconds to wait when offering new events to the queue.
+ */
+ public static final long DEFAULT_OFFER_WAIT_MS = 100;
+
+ private final long offerWaitMs;
+ private final BlockingQueue<E> events;
+ private final ProcessorLog logger;
+
+ public EventQueue(final BlockingQueue<E> events, final ProcessorLog logger) {
+ this(events, DEFAULT_OFFER_WAIT_MS, logger);
+ }
+
+ public EventQueue(final BlockingQueue<E> events, final long offerWaitMs, final ProcessorLog logger) {
+ this.events = events;
+ this.offerWaitMs = offerWaitMs;
+ this.logger = logger;
+ Validate.notNull(this.events);
+ Validate.notNull(this.logger);
+ }
+
+ /**
+ * Offers the given event to the events queue with a wait time, if the offer fails the event
+ * is dropped an error is logged.
+ *
+ * @param event the event to offer
+ * @throws InterruptedException if interrupted while waiting to offer
+ */
+ public void offer(final E event) throws InterruptedException {
+ boolean queued = events.offer(event, offerWaitMs, TimeUnit.MILLISECONDS);
+ if (!queued) {
+ logger.error("Internal queue at maximum capacity, could not queue event");
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/StandardEventFactory.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/StandardEventFactory.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/StandardEventFactory.java
new file mode 100644
index 0000000..9ae6161
--- /dev/null
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/event/StandardEventFactory.java
@@ -0,0 +1,37 @@
+/*
+ * 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.processor.util.listen.event;
+
+import org.apache.nifi.processor.util.listen.response.ChannelResponder;
+
+import java.util.Map;
+
+/**
+ * EventFactory to create StandardEvent instances.
+ */
+public class StandardEventFactory implements EventFactory<StandardEvent> {
+
+ @Override
+ public StandardEvent create(final byte[] data, final Map<String, String> metadata, final ChannelResponder responder) {
+ String sender = null;
+ if (metadata != null && metadata.containsKey(EventFactory.SENDER_KEY)) {
+ sender = metadata.get(EventFactory.SENDER_KEY);
+ }
+ return new StandardEvent(sender, data, responder);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/ChannelHandler.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/ChannelHandler.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/ChannelHandler.java
index ab4346f..6307c76 100644
--- a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/ChannelHandler.java
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/ChannelHandler.java
@@ -20,6 +20,7 @@ import org.apache.nifi.logging.ProcessorLog;
import org.apache.nifi.processor.util.listen.dispatcher.ChannelDispatcher;
import org.apache.nifi.processor.util.listen.event.Event;
import org.apache.nifi.processor.util.listen.event.EventFactory;
+import org.apache.nifi.processor.util.listen.event.EventQueue;
import java.nio.channels.SelectionKey;
import java.nio.charset.Charset;
@@ -34,7 +35,7 @@ public abstract class ChannelHandler<E extends Event, D extends ChannelDispatche
protected final D dispatcher;
protected final Charset charset;
protected final EventFactory<E> eventFactory;
- protected final BlockingQueue<E> events;
+ protected final EventQueue<E> events;
protected final ProcessorLog logger;
@@ -48,8 +49,8 @@ public abstract class ChannelHandler<E extends Event, D extends ChannelDispatche
this.dispatcher = dispatcher;
this.charset = charset;
this.eventFactory = eventFactory;
- this.events = events;
this.logger = logger;
+ this.events = new EventQueue<E>(events, logger);
}
}
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/SSLSocketChannelHandler.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/SSLSocketChannelHandler.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/SSLSocketChannelHandler.java
index 460ef08..d11cb02 100644
--- a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/SSLSocketChannelHandler.java
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/SSLSocketChannelHandler.java
@@ -135,10 +135,8 @@ public class SSLSocketChannelHandler<E extends Event<SocketChannel>> extends Soc
if (currBytes.size() > 0) {
final SSLSocketChannelResponder response = new SSLSocketChannelResponder(socketChannel, sslSocketChannel);
final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender.toString());
-
- // queue the raw event blocking until space is available, reset the temporary buffer
final E event = eventFactory.create(currBytes.toByteArray(), metadata, response);
- events.put(event);
+ events.offer(event);
currBytes.reset();
}
} else {
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/StandardSocketChannelHandler.java
----------------------------------------------------------------------
diff --git a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/StandardSocketChannelHandler.java b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/StandardSocketChannelHandler.java
index e2fd3a8..94e41eb 100644
--- a/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/StandardSocketChannelHandler.java
+++ b/nifi-commons/nifi-processor-utilities/src/main/java/org/apache/nifi/processor/util/listen/handler/socket/StandardSocketChannelHandler.java
@@ -137,10 +137,8 @@ public class StandardSocketChannelHandler<E extends Event<SocketChannel>> extend
if (currBytes.size() > 0) {
final SocketChannelResponder response = new SocketChannelResponder(socketChannel);
final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender.toString());
-
- // queue the raw event blocking until space is available, reset the buffer
final E event = eventFactory.create(currBytes.toByteArray(), metadata, response);
- events.put(event);
+ events.offer(event);
currBytes.reset();
// Mark this as the start of the next message
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenRELP.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenRELP.java b/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenRELP.java
index c386bdc..51173ec 100644
--- a/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenRELP.java
+++ b/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenRELP.java
@@ -24,14 +24,12 @@ import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.PropertyDescriptor;
-import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.flowfile.attributes.FlowFileAttributeKey;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
-import org.apache.nifi.processor.exception.ProcessException;
-import org.apache.nifi.processor.util.listen.AbstractListenEventProcessor;
+import org.apache.nifi.processor.util.listen.AbstractListenEventBatchingProcessor;
import org.apache.nifi.processor.util.listen.dispatcher.AsyncChannelDispatcher;
import org.apache.nifi.processor.util.listen.dispatcher.ChannelDispatcher;
import org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher;
@@ -56,7 +54,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
@Tags({"listen", "relp", "tcp", "logs"})
@@ -72,7 +69,7 @@ import java.util.concurrent.LinkedBlockingQueue;
@WritesAttribute(attribute="mime.type", description="The mime.type of the content which is text/plain")
})
@SeeAlso({ParseSyslog.class})
-public class ListenRELP extends AbstractListenEventProcessor<RELPEvent> {
+public class ListenRELP extends AbstractListenEventBatchingProcessor<RELPEvent> {
public static final PropertyDescriptor SSL_CONTEXT_SERVICE = new PropertyDescriptor.Builder()
.name("SSL Context Service")
@@ -83,11 +80,10 @@ public class ListenRELP extends AbstractListenEventProcessor<RELPEvent> {
.build();
private volatile RELPEncoder relpEncoder;
- private volatile byte[] messageDemarcatorBytes; //it is only the array reference that is volatile - not the contents.
@Override
protected List<PropertyDescriptor> getAdditionalProperties() {
- return Arrays.asList(MAX_CONNECTIONS, MAX_BATCH_SIZE, MESSAGE_DELIMITER, SSL_CONTEXT_SERVICE);
+ return Arrays.asList(MAX_CONNECTIONS, SSL_CONTEXT_SERVICE);
}
@Override
@@ -96,9 +92,6 @@ public class ListenRELP extends AbstractListenEventProcessor<RELPEvent> {
super.onScheduled(context);
// wanted to ensure charset was already populated here
relpEncoder = new RELPEncoder(charset);
-
- final String msgDemarcator = context.getProperty(MESSAGE_DELIMITER).getValue().replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t");
- messageDemarcatorBytes = msgDemarcator.getBytes(charset);
}
@Override
@@ -111,10 +104,7 @@ public class ListenRELP extends AbstractListenEventProcessor<RELPEvent> {
final Charset charSet = Charset.forName(context.getProperty(CHARSET).getValue());
// initialize the buffer pool based on max number of connections and the buffer size
- final LinkedBlockingQueue<ByteBuffer> bufferPool = new LinkedBlockingQueue<>(maxConnections);
- for (int i = 0; i < maxConnections; i++) {
- bufferPool.offer(ByteBuffer.allocate(bufferSize));
- }
+ final BlockingQueue<ByteBuffer> bufferPool = createBufferPool(maxConnections, bufferSize);
// if an SSLContextService was provided then create an SSLContext to pass down to the dispatcher
SSLContext sslContext = null;
@@ -129,69 +119,20 @@ public class ListenRELP extends AbstractListenEventProcessor<RELPEvent> {
}
@Override
- public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
- final int maxBatchSize = context.getProperty(MAX_BATCH_SIZE).asInteger();
- final Map<String,FlowFileEventBatch> batches = getBatches(session, maxBatchSize, messageDemarcatorBytes);
-
- // if the size is 0 then there was nothing to process so return
- // we don't need to yield here because inside getBatches() we are polling a queue with a wait
- // and yielding here could have a negative impact on performance
- if (batches.size() == 0) {
- return;
- }
-
- for (Map.Entry<String,FlowFileEventBatch> entry : batches.entrySet()) {
- FlowFile flowFile = entry.getValue().getFlowFile();
- final List<RELPEvent> events = entry.getValue().getEvents();
-
- if (flowFile.getSize() == 0L || events.size() == 0) {
- session.remove(flowFile);
- getLogger().debug("No data written to FlowFile from batch {}; removing FlowFile", new Object[] {entry.getKey()});
- continue;
- }
-
- // the sender and command will be the same for all events based on the batch key
- final String sender = events.get(0).getSender();
- final String command = events.get(0).getCommand();
-
- final int numAttributes = events.size() == 1 ? 5 : 4;
-
- final Map<String,String> attributes = new HashMap<>(numAttributes);
- attributes.put(RELPAttributes.COMMAND.key(), command);
- attributes.put(RELPAttributes.SENDER.key(), sender);
- attributes.put(RELPAttributes.PORT.key(), String.valueOf(port));
- attributes.put(CoreAttributes.MIME_TYPE.key(), "text/plain");
-
- // if there was only one event then we can pass on the transaction
- // NOTE: we could pass on all the transaction ids joined together
- if (events.size() == 1) {
- attributes.put(RELPAttributes.TXNR.key(), String.valueOf(events.get(0).getTxnr()));
- }
- flowFile = session.putAllAttributes(flowFile, attributes);
-
- getLogger().debug("Transferring {} to success", new Object[] {flowFile});
- session.transfer(flowFile, REL_SUCCESS);
- session.adjustCounter("FlowFiles Transferred to Success", 1L, false);
-
- // create a provenance receive event
- final String senderHost = sender.startsWith("/") && sender.length() > 1 ? sender.substring(1) : sender;
- final String transitUri = new StringBuilder().append("relp").append("://").append(senderHost).append(":")
- .append(port).toString();
- session.getProvenanceReporter().receive(flowFile, transitUri);
-
- // commit the session to guarantee the data has been delivered
- session.commit();
-
- // respond to each event to acknowledge successful receipt
- for (final RELPEvent event : events) {
- respond(event, RELPResponse.ok(event.getTxnr()));
- }
- }
+ protected String getBatchKey(RELPEvent event) {
+ return event.getSender() + "_" + event.getCommand();
}
@Override
- protected String getBatchKey(RELPEvent event) {
- return event.getSender() + "_" + event.getCommand();
+ protected void postProcess(final ProcessContext context, final ProcessSession session, final List<RELPEvent> events) {
+ // first commit the session so we guarantee we have all the events successfully
+ // written to FlowFiles and transferred to the success relationship
+ session.commit();
+
+ // respond to each event to acknowledge successful receipt
+ for (final RELPEvent event : events) {
+ respond(event, RELPResponse.ok(event.getTxnr()));
+ }
}
protected void respond(final RELPEvent event, final RELPResponse relpResponse) {
@@ -207,6 +148,39 @@ public class ListenRELP extends AbstractListenEventProcessor<RELPEvent> {
}
}
+ @Override
+ protected Map<String, String> getAttributes(FlowFileEventBatch batch) {
+ final List<RELPEvent> events = batch.getEvents();
+
+ // the sender and command will be the same for all events based on the batch key
+ final String sender = events.get(0).getSender();
+ final String command = events.get(0).getCommand();
+
+ final int numAttributes = events.size() == 1 ? 5 : 4;
+
+ final Map<String,String> attributes = new HashMap<>(numAttributes);
+ attributes.put(RELPAttributes.COMMAND.key(), command);
+ attributes.put(RELPAttributes.SENDER.key(), sender);
+ attributes.put(RELPAttributes.PORT.key(), String.valueOf(port));
+ attributes.put(CoreAttributes.MIME_TYPE.key(), "text/plain");
+
+ // if there was only one event then we can pass on the transaction
+ // NOTE: we could pass on all the transaction ids joined together
+ if (events.size() == 1) {
+ attributes.put(RELPAttributes.TXNR.key(), String.valueOf(events.get(0).getTxnr()));
+ }
+ return attributes;
+ }
+
+ @Override
+ protected String getTransitUri(FlowFileEventBatch batch) {
+ final String sender = batch.getEvents().get(0).getSender();
+ final String senderHost = sender.startsWith("/") && sender.length() > 1 ? sender.substring(1) : sender;
+ final String transitUri = new StringBuilder().append("relp").append("://").append(senderHost).append(":")
+ .append(port).toString();
+ return transitUri;
+ }
+
public enum RELPAttributes implements FlowFileAttributeKey {
TXNR("relp.txnr"),
COMMAND("relp.command"),
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenSyslog.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenSyslog.java b/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenSyslog.java
index 1ec406d..38668e5 100644
--- a/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenSyslog.java
+++ b/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenSyslog.java
@@ -16,6 +16,9 @@
*/
package org.apache.nifi.processors.standard;
+import static org.apache.nifi.processor.util.listen.ListenerProperties.NETWORK_INTF_NAME;
+
+import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.SupportsBatching;
import org.apache.nifi.annotation.behavior.WritesAttribute;
@@ -55,6 +58,8 @@ import org.apache.nifi.ssl.SSLContextService;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
@@ -189,6 +194,7 @@ public class ListenSyslog extends AbstractSyslogProcessor {
final List<PropertyDescriptor> descriptors = new ArrayList<>();
descriptors.add(PROTOCOL);
descriptors.add(PORT);
+ descriptors.add(NETWORK_INTF_NAME);
descriptors.add(SSL_CONTEXT_SERVICE);
descriptors.add(RECV_BUFFER_SIZE);
descriptors.add(MAX_MESSAGE_QUEUE_SIZE);
@@ -257,6 +263,7 @@ public class ListenSyslog extends AbstractSyslogProcessor {
final int maxChannelBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
final int maxMessageQueueSize = context.getProperty(MAX_MESSAGE_QUEUE_SIZE).asInteger();
final String protocol = context.getProperty(PROTOCOL).getValue();
+ final String nicIPAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions().getValue();
final String charSet = context.getProperty(CHARSET).getValue();
final String msgDemarcator = context.getProperty(MESSAGE_DELIMITER).getValue().replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t");
messageDemarcatorBytes = msgDemarcator.getBytes(Charset.forName(charSet));
@@ -276,10 +283,16 @@ public class ListenSyslog extends AbstractSyslogProcessor {
parser = new SyslogParser(Charset.forName(charSet));
syslogEvents = new LinkedBlockingQueue<>(maxMessageQueueSize);
+ InetAddress nicIPAddress = null;
+ if (!StringUtils.isEmpty(nicIPAddressStr)) {
+ NetworkInterface netIF = NetworkInterface.getByName(nicIPAddressStr);
+ nicIPAddress = netIF.getInetAddresses().nextElement();
+ }
+
// create either a UDP or TCP reader and call open() to bind to the given port
final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
channelDispatcher = createChannelReader(protocol, bufferPool, syslogEvents, maxConnections, sslContextService, Charset.forName(charSet));
- channelDispatcher.open(port, maxChannelBufferSize);
+ channelDispatcher.open(nicIPAddress, port, maxChannelBufferSize);
final Thread readerThread = new Thread(channelDispatcher);
readerThread.setName("ListenSyslog [" + getIdentifier() + "]");
http://git-wip-us.apache.org/repos/asf/nifi/blob/1373bf67/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenTCP.java
----------------------------------------------------------------------
diff --git a/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenTCP.java b/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenTCP.java
index c79d593..86554c8 100644
--- a/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenTCP.java
+++ b/nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ListenTCP.java
@@ -23,31 +23,26 @@ 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.Tags;
-import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
-import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.ProcessContext;
-import org.apache.nifi.processor.ProcessSession;
-import org.apache.nifi.processor.exception.ProcessException;
-import org.apache.nifi.processor.util.listen.AbstractListenEventProcessor;
+import org.apache.nifi.processor.util.listen.AbstractListenEventBatchingProcessor;
import org.apache.nifi.processor.util.listen.dispatcher.AsyncChannelDispatcher;
import org.apache.nifi.processor.util.listen.dispatcher.ChannelDispatcher;
import org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher;
import org.apache.nifi.processor.util.listen.event.EventFactory;
import org.apache.nifi.processor.util.listen.event.StandardEvent;
+import org.apache.nifi.processor.util.listen.event.StandardEventFactory;
import org.apache.nifi.processor.util.listen.handler.ChannelHandlerFactory;
import org.apache.nifi.processor.util.listen.handler.socket.SocketChannelHandlerFactory;
-import org.apache.nifi.processor.util.listen.response.ChannelResponder;
import org.apache.nifi.security.util.SslContextFactory;
import org.apache.nifi.ssl.SSLContextService;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.ByteBuffer;
-import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
@@ -57,7 +52,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
@SupportsBatching
@InputRequirement(InputRequirement.Requirement.INPUT_FORBIDDEN)
@@ -71,7 +65,7 @@ import java.util.concurrent.LinkedBlockingQueue;
@WritesAttribute(attribute="tcp.sender", description="The sending host of the messages."),
@WritesAttribute(attribute="tcp.port", description="The sending port the messages were received.")
})
-public class ListenTCP extends AbstractListenEventProcessor<ListenTCP.TCPEvent> {
+public class ListenTCP extends AbstractListenEventBatchingProcessor<StandardEvent> {
public static final PropertyDescriptor SSL_CONTEXT_SERVICE = new PropertyDescriptor.Builder()
.name("SSL Context Service")
@@ -89,15 +83,10 @@ public class ListenTCP extends AbstractListenEventProcessor<ListenTCP.TCPEvent>
.defaultValue(SSLContextService.ClientAuth.REQUIRED.name())
.build();
- // it is only the array reference that is volatile - not the contents.
- private volatile byte[] messageDemarcatorBytes;
-
@Override
protected List<PropertyDescriptor> getAdditionalProperties() {
return Arrays.asList(
MAX_CONNECTIONS,
- MAX_BATCH_SIZE,
- MESSAGE_DELIMITER,
SSL_CONTEXT_SERVICE,
CLIENT_AUTH
);
@@ -120,15 +109,7 @@ public class ListenTCP extends AbstractListenEventProcessor<ListenTCP.TCPEvent>
}
@Override
- @OnScheduled
- public void onScheduled(ProcessContext context) throws IOException {
- super.onScheduled(context);
- final String msgDemarcator = context.getProperty(MESSAGE_DELIMITER).getValue().replace("\\n", "\n").replace("\\r", "\r").replace("\\t", "\t");
- messageDemarcatorBytes = msgDemarcator.getBytes(charset);
- }
-
- @Override
- protected ChannelDispatcher createDispatcher(final ProcessContext context, final BlockingQueue<TCPEvent> events)
+ protected ChannelDispatcher createDispatcher(final ProcessContext context, final BlockingQueue<StandardEvent> events)
throws IOException {
final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
@@ -136,12 +117,7 @@ public class ListenTCP extends AbstractListenEventProcessor<ListenTCP.TCPEvent>
final Charset charSet = Charset.forName(context.getProperty(CHARSET).getValue());
// initialize the buffer pool based on max number of connections and the buffer size
- final LinkedBlockingQueue<ByteBuffer> bufferPool = new LinkedBlockingQueue<>(maxConnections);
- for (int i = 0; i < maxConnections; i++) {
- bufferPool.offer(ByteBuffer.allocate(bufferSize));
- }
-
- final EventFactory<TCPEvent> eventFactory = new TCPEventFactory();
+ final BlockingQueue<ByteBuffer> bufferPool = createBufferPool(maxConnections, bufferSize);
// if an SSLContextService was provided then create an SSLContext to pass down to the dispatcher
SSLContext sslContext = null;
@@ -154,73 +130,27 @@ public class ListenTCP extends AbstractListenEventProcessor<ListenTCP.TCPEvent>
clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
}
- final ChannelHandlerFactory<TCPEvent<SocketChannel>, AsyncChannelDispatcher> handlerFactory = new SocketChannelHandlerFactory<>();
+ final EventFactory<StandardEvent> eventFactory = new StandardEventFactory();
+ final ChannelHandlerFactory<StandardEvent<SocketChannel>, AsyncChannelDispatcher> handlerFactory = new SocketChannelHandlerFactory<>();
return new SocketChannelDispatcher(eventFactory, handlerFactory, bufferPool, events, getLogger(), maxConnections, sslContext, clientAuth, charSet);
}
@Override
- public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
- final int maxBatchSize = context.getProperty(MAX_BATCH_SIZE).asInteger();
- final Map<String,FlowFileEventBatch> batches = getBatches(session, maxBatchSize, messageDemarcatorBytes);
-
- // if the size is 0 then there was nothing to process so return
- // we don't need to yield here because we have a long poll in side of getBatches
- if (batches.size() == 0) {
- return;
- }
-
- for (Map.Entry<String,FlowFileEventBatch> entry : batches.entrySet()) {
- FlowFile flowFile = entry.getValue().getFlowFile();
- final List<TCPEvent> events = entry.getValue().getEvents();
-
- if (flowFile.getSize() == 0L || events.size() == 0) {
- session.remove(flowFile);
- getLogger().debug("No data written to FlowFile from batch {}; removing FlowFile", new Object[] {entry.getKey()});
- continue;
- }
-
- // the sender and command will be the same for all events based on the batch key
- final String sender = events.get(0).getSender();
-
- final Map<String,String> attributes = new HashMap<>(3);
- attributes.put("tcp.sender", sender);
- attributes.put("tcp.port", String.valueOf(port));
- flowFile = session.putAllAttributes(flowFile, attributes);
-
- getLogger().debug("Transferring {} to success", new Object[] {flowFile});
- session.transfer(flowFile, REL_SUCCESS);
- session.adjustCounter("FlowFiles Transferred to Success", 1L, false);
-
- // create a provenance receive event
- final String senderHost = sender.startsWith("/") && sender.length() > 1 ? sender.substring(1) : sender;
- final String transitUri = new StringBuilder().append("tcp").append("://").append(senderHost).append(":")
- .append(port).toString();
- session.getProvenanceReporter().receive(flowFile, transitUri);
- }
+ protected Map<String, String> getAttributes(final FlowFileEventBatch batch) {
+ final String sender = batch.getEvents().get(0).getSender();
+ final Map<String,String> attributes = new HashMap<>(3);
+ attributes.put("tcp.sender", sender);
+ attributes.put("tcp.port", String.valueOf(port));
+ return attributes;
}
- /**
- * Event implementation for TCP.
- */
- static class TCPEvent<C extends SelectableChannel> extends StandardEvent<C> {
-
- public TCPEvent(String sender, byte[] data, ChannelResponder<C> responder) {
- super(sender, data, responder);
- }
+ @Override
+ protected String getTransitUri(FlowFileEventBatch batch) {
+ final String sender = batch.getEvents().get(0).getSender();
+ final String senderHost = sender.startsWith("/") && sender.length() > 1 ? sender.substring(1) : sender;
+ final String transitUri = new StringBuilder().append("tcp").append("://").append(senderHost).append(":")
+ .append(port).toString();
+ return transitUri;
}
- /**
- * Factory implementation for TCPEvents.
- */
- static final class TCPEventFactory implements EventFactory<TCPEvent> {
-
- @Override
- public TCPEvent create(byte[] data, Map<String, String> metadata, ChannelResponder responder) {
- String sender = null;
- if (metadata != null && metadata.containsKey(EventFactory.SENDER_KEY)) {
- sender = metadata.get(EventFactory.SENDER_KEY);
- }
- return new TCPEvent(sender, data, responder);
- }
- }
}