You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@plc4x.apache.org by "QuanticPony (via GitHub)" <gi...@apache.org> on 2023/02/16 14:53:45 UTC

[PR] Feature/nifi integration sink record processor and minor fixes (plc4x)

QuanticPony opened a new pull request, #809:
URL: https://github.com/apache/plc4x/pull/809

   At the moment the NiFi integration has attribute based sink and source and a record based source. This PR attempts to bring a record based sink processor and some minor fixes to the nifi integration.
   
   ## Changes:
   * Added Plc4xSinkRecordProcessor and unit tests.
   * Added PlcWriteResponse check on both sink processors.
   * Added unit tests for Plc4xSinkProcessor.
   * Updated all processor tags.
   * Fixed some issues on source processors unit tests.
   
   Waiting for feedback


-- 
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: dev-unsubscribe@plc4x.apache.org

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


Re: [PR] Feature/nifi integration sink record processor and minor fixes (plc4x)

Posted by "QuanticPony (via GitHub)" <gi...@apache.org>.
QuanticPony commented on code in PR #809:
URL: https://github.com/apache/plc4x/pull/809#discussion_r1113982008


##########
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/Plc4xSinkRecordProcessor.java:
##########
@@ -0,0 +1,229 @@
+/*
+ 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.plc4x.nifi;
+
+import java.io.InputStream;
+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.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.nifi.annotation.behavior.InputRequirement;
+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.Tags;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.logging.ComponentLog;
+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.util.StandardValidators;
+import org.apache.nifi.serialization.RecordReader;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.util.StopWatch;
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.java.api.messages.PlcWriteRequest;
+import org.apache.plc4x.java.api.messages.PlcWriteResponse;
+import org.apache.plc4x.java.api.model.PlcTag;
+import org.apache.plc4x.java.api.types.PlcResponseCode;
+
+@TriggerSerially
+@Tags({"plc4x", "put", "sink", "record"})
+@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
+@CapabilityDescription("Processor able to write data to industrial PLCs using Apache PLC4X")
+@WritesAttributes({ @WritesAttribute(attribute = "value", description = "some value") })
+public class Plc4xSinkRecordProcessor extends BasePlc4xProcessor {
+
+	public static final String RESULT_ROW_COUNT = "plc4x.write.row.count";
+	public static final String RESULT_QUERY_DURATION = "plc4x.write.query.duration";
+	public static final String RESULT_QUERY_EXECUTION_TIME = "plc4x.write.query.executiontime";
+	public static final String RESULT_QUERY_FETCH_TIME = "plc4x.write.query.fetchtime";
+	public static final String INPUT_FLOWFILE_UUID = "input.flowfile.uuid";
+	public static final String RESULT_ERROR_MESSAGE = "plc4x.write.error.message";
+	
+	public static final PropertyDescriptor PLC_RECORD_READER_FACTORY = new PropertyDescriptor.Builder()
+			.name("record-reader").displayName("Record Reader")
+			.description(
+					"Specifies the Controller Service to use for reading record from a FlowFile. The Record Reader may use Inherit Schema to emulate the inferred schema behavior, i.e. "
+							+ "an explicit schema need not be defined in the reader, and will be supplied by the same logic used to infer the schema from the column types.")
+			.identifiesControllerService(RecordReaderFactory.class)
+			.required(true)
+			.build();
+
+	public static final PropertyDescriptor PLC_WRITE_FUTURE_TIMEOUT_MILISECONDS = new PropertyDescriptor.Builder().name("plc4x-record-write-timeout").displayName("Write timeout (miliseconds)")
+			.description("Write timeout in miliseconds")
+			.defaultValue("10000")
+			.required(true)
+			.addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR)
+			.build();
+	
+
+	public Plc4xSinkRecordProcessor() {
+	}
+
+	@Override
+	protected void init(final ProcessorInitializationContext context) {
+		super.init(context);
+		final Set<Relationship> r = new HashSet<>();
+		r.addAll(super.getRelationships());
+		this.relationships = Collections.unmodifiableSet(r);
+
+		final List<PropertyDescriptor> pds = new ArrayList<>();
+		pds.addAll(super.getSupportedPropertyDescriptors());
+		pds.add(PLC_RECORD_READER_FACTORY);
+		pds.add(PLC_WRITE_FUTURE_TIMEOUT_MILISECONDS);
+		this.properties = Collections.unmodifiableList(pds);
+	}
+
+	@Override
+	public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+		FlowFile fileToProcess = session.get();
+
+        // Abort if there's nothing to do.
+        if (fileToProcess == null) {
+            return;
+        }
+			
+		final ComponentLog logger = getLogger();
+		// Get an instance of a component able to read from a PLC.
+		final AtomicLong nrOfRows = new AtomicLong(0L);
+		final StopWatch executeTime = new StopWatch(true);
+
+		final FlowFile originalFlowFile = fileToProcess;
+
+		InputStream in = session.read(originalFlowFile);
+
+		Record record = null;
+		
+		try (RecordReader recordReader = context.getProperty(PLC_RECORD_READER_FACTORY)
+			.asControllerService(RecordReaderFactory.class)
+			.createRecordReader(originalFlowFile, in, logger)){
+
+			while ((record = recordReader.nextRecord()) != null) {
+				long nrOfRowsHere = 0L;
+				PlcWriteResponse plcWriteResponse;
+				PlcWriteRequest writeRequest;
+
+				Map<String,String> addressMap = getPlcAddressMap(context, fileToProcess);
+				final Map<String, PlcTag> tags = getSchemaCache().retrieveTags(addressMap);
+
+				try (PlcConnection connection = getConnectionManager().getConnection(getConnectionString())) {
+					PlcWriteRequest.Builder builder = connection.writeRequestBuilder();
+					
+					
+					if (tags != null){
+						for (Map.Entry<String,PlcTag> tag : tags.entrySet()){
+							if (record.toMap().containsKey(tag.getKey())) {
+								builder.addTag(tag.getKey(), tag.getValue(), record.getValue(tag.getKey()));
+								nrOfRowsHere++;
+							} else {
+								if (debugEnabled)
+                    				logger.debug("PlcTag " + tag + " is declared as address but was not found on input record.");
+							}
+						}
+					} else {
+						if (debugEnabled)
+                   			logger.debug("Plc-Avro schema and PlcTypes resolution not found in cache and will be added with key: " + addressMap.toString());
+						for (Map.Entry<String,String> entry: addressMap.entrySet()){
+							if (record.toMap().containsKey(entry.getKey())) {
+								builder.addTagAddress(entry.getKey(), entry.getValue(), record.getValue(entry.getKey()));
+								nrOfRowsHere++;
+							} else {
+								if (debugEnabled)
+                    				logger.debug("PlcTag " + entry.getKey() + " with address " + entry.getValue() + " was not found on input record.");
+							}
+						}
+					}
+					writeRequest = builder.build();
+
+					plcWriteResponse = writeRequest.execute().get(
+						context.getProperty(PLC_WRITE_FUTURE_TIMEOUT_MILISECONDS.getName()).asInteger(), TimeUnit.MILLISECONDS
+						);
+				} catch (Exception e) {
+					System.out.println(e.getMessage());
+					in.close();
+					logger.error("Exception writing the data to PLC", e);
+					session.transfer(originalFlowFile, REL_FAILURE);
+					session.commitAsync();
+					throw (e instanceof ProcessException) ? (ProcessException) e : new ProcessException(e);
+				}
+

Review Comment:
   I agree, I have moved them in both sinks to cache only if it works



-- 
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: dev-unsubscribe@plc4x.apache.org

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


Re: [PR] Feature/nifi integration sink record processor and minor fixes (plc4x)

Posted by "ottobackwards (via GitHub)" <gi...@apache.org>.
ottobackwards commented on code in PR #809:
URL: https://github.com/apache/plc4x/pull/809#discussion_r1113341175


##########
plc4j/integrations/apache-nifi/README.md:
##########
@@ -48,19 +49,66 @@ This applies to all Plc4x processors:
     ```
     If this JSON is in an attribute `plc4x.addresses` it can be accessed with *Address Text*=`${plc4x.addresses}`. 
 
+

Review Comment:
   The response isn't converted into Avro, an Avro _schema_ is produced for the PLC Data types



##########
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/Plc4xSinkRecordProcessor.java:
##########
@@ -0,0 +1,229 @@
+/*
+ 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.plc4x.nifi;
+
+import java.io.InputStream;
+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.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.nifi.annotation.behavior.InputRequirement;
+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.Tags;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.logging.ComponentLog;
+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.util.StandardValidators;
+import org.apache.nifi.serialization.RecordReader;
+import org.apache.nifi.serialization.RecordReaderFactory;
+import org.apache.nifi.serialization.record.Record;
+import org.apache.nifi.util.StopWatch;
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.java.api.messages.PlcWriteRequest;
+import org.apache.plc4x.java.api.messages.PlcWriteResponse;
+import org.apache.plc4x.java.api.model.PlcTag;
+import org.apache.plc4x.java.api.types.PlcResponseCode;
+
+@TriggerSerially
+@Tags({"plc4x", "put", "sink", "record"})
+@InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED)
+@CapabilityDescription("Processor able to write data to industrial PLCs using Apache PLC4X")
+@WritesAttributes({ @WritesAttribute(attribute = "value", description = "some value") })
+public class Plc4xSinkRecordProcessor extends BasePlc4xProcessor {
+
+	public static final String RESULT_ROW_COUNT = "plc4x.write.row.count";
+	public static final String RESULT_QUERY_DURATION = "plc4x.write.query.duration";
+	public static final String RESULT_QUERY_EXECUTION_TIME = "plc4x.write.query.executiontime";
+	public static final String RESULT_QUERY_FETCH_TIME = "plc4x.write.query.fetchtime";
+	public static final String INPUT_FLOWFILE_UUID = "input.flowfile.uuid";
+	public static final String RESULT_ERROR_MESSAGE = "plc4x.write.error.message";
+	
+	public static final PropertyDescriptor PLC_RECORD_READER_FACTORY = new PropertyDescriptor.Builder()
+			.name("record-reader").displayName("Record Reader")
+			.description(
+					"Specifies the Controller Service to use for reading record from a FlowFile. The Record Reader may use Inherit Schema to emulate the inferred schema behavior, i.e. "
+							+ "an explicit schema need not be defined in the reader, and will be supplied by the same logic used to infer the schema from the column types.")
+			.identifiesControllerService(RecordReaderFactory.class)
+			.required(true)
+			.build();
+
+	public static final PropertyDescriptor PLC_WRITE_FUTURE_TIMEOUT_MILISECONDS = new PropertyDescriptor.Builder().name("plc4x-record-write-timeout").displayName("Write timeout (miliseconds)")
+			.description("Write timeout in miliseconds")
+			.defaultValue("10000")
+			.required(true)
+			.addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR)
+			.build();
+	
+
+	public Plc4xSinkRecordProcessor() {
+	}
+
+	@Override
+	protected void init(final ProcessorInitializationContext context) {
+		super.init(context);
+		final Set<Relationship> r = new HashSet<>();
+		r.addAll(super.getRelationships());
+		this.relationships = Collections.unmodifiableSet(r);
+
+		final List<PropertyDescriptor> pds = new ArrayList<>();
+		pds.addAll(super.getSupportedPropertyDescriptors());
+		pds.add(PLC_RECORD_READER_FACTORY);
+		pds.add(PLC_WRITE_FUTURE_TIMEOUT_MILISECONDS);
+		this.properties = Collections.unmodifiableList(pds);
+	}
+
+	@Override
+	public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
+		FlowFile fileToProcess = session.get();
+
+        // Abort if there's nothing to do.
+        if (fileToProcess == null) {
+            return;
+        }
+			
+		final ComponentLog logger = getLogger();
+		// Get an instance of a component able to read from a PLC.
+		final AtomicLong nrOfRows = new AtomicLong(0L);
+		final StopWatch executeTime = new StopWatch(true);
+
+		final FlowFile originalFlowFile = fileToProcess;
+
+		InputStream in = session.read(originalFlowFile);
+
+		Record record = null;
+		
+		try (RecordReader recordReader = context.getProperty(PLC_RECORD_READER_FACTORY)
+			.asControllerService(RecordReaderFactory.class)
+			.createRecordReader(originalFlowFile, in, logger)){
+
+			while ((record = recordReader.nextRecord()) != null) {
+				long nrOfRowsHere = 0L;
+				PlcWriteResponse plcWriteResponse;
+				PlcWriteRequest writeRequest;
+
+				Map<String,String> addressMap = getPlcAddressMap(context, fileToProcess);
+				final Map<String, PlcTag> tags = getSchemaCache().retrieveTags(addressMap);
+
+				try (PlcConnection connection = getConnectionManager().getConnection(getConnectionString())) {
+					PlcWriteRequest.Builder builder = connection.writeRequestBuilder();
+					
+					
+					if (tags != null){
+						for (Map.Entry<String,PlcTag> tag : tags.entrySet()){
+							if (record.toMap().containsKey(tag.getKey())) {
+								builder.addTag(tag.getKey(), tag.getValue(), record.getValue(tag.getKey()));
+								nrOfRowsHere++;
+							} else {
+								if (debugEnabled)
+                    				logger.debug("PlcTag " + tag + " is declared as address but was not found on input record.");
+							}
+						}
+					} else {
+						if (debugEnabled)
+                   			logger.debug("Plc-Avro schema and PlcTypes resolution not found in cache and will be added with key: " + addressMap.toString());
+						for (Map.Entry<String,String> entry: addressMap.entrySet()){
+							if (record.toMap().containsKey(entry.getKey())) {
+								builder.addTagAddress(entry.getKey(), entry.getValue(), record.getValue(entry.getKey()));
+								nrOfRowsHere++;
+							} else {
+								if (debugEnabled)
+                    				logger.debug("PlcTag " + entry.getKey() + " with address " + entry.getValue() + " was not found on input record.");
+							}
+						}
+					}
+					writeRequest = builder.build();
+
+					plcWriteResponse = writeRequest.execute().get(
+						context.getProperty(PLC_WRITE_FUTURE_TIMEOUT_MILISECONDS.getName()).asInteger(), TimeUnit.MILLISECONDS
+						);
+				} catch (Exception e) {
+					System.out.println(e.getMessage());
+					in.close();
+					logger.error("Exception writing the data to PLC", e);
+					session.transfer(originalFlowFile, REL_FAILURE);
+					session.commitAsync();
+					throw (e instanceof ProcessException) ? (ProcessException) e : new ProcessException(e);
+				}
+

Review Comment:
   should we only cache if it works? 



##########
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/Plc4xSinkProcessor.java:
##########
@@ -64,12 +67,13 @@ public void onTrigger(final ProcessContext context, final ProcessSession session
 
             if (tags != null){
                 for (Map.Entry<String,PlcTag> tag : tags.entrySet()){
-                    builder.addTag(tag.getKey(), tag.getValue());
+                    builder.addTag(tag.getKey(), tag.getValue(), flowFile.getAttribute(tag.getKey()));

Review Comment:
   What attribute is this???  Isn't this a breaking change?



##########
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/Plc4xSinkProcessor.java:
##########
@@ -64,12 +67,13 @@ public void onTrigger(final ProcessContext context, final ProcessSession session
 
             if (tags != null){
                 for (Map.Entry<String,PlcTag> tag : tags.entrySet()){
-                    builder.addTag(tag.getKey(), tag.getValue());
+                    builder.addTag(tag.getKey(), tag.getValue(), flowFile.getAttribute(tag.getKey()));

Review Comment:
   Also, what if it is not present?



##########
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/Plc4xSinkProcessor.java:
##########
@@ -64,12 +67,13 @@ public void onTrigger(final ProcessContext context, final ProcessSession session
 
             if (tags != null){
                 for (Map.Entry<String,PlcTag> tag : tags.entrySet()){
-                    builder.addTag(tag.getKey(), tag.getValue());
+                    builder.addTag(tag.getKey(), tag.getValue(), flowFile.getAttribute(tag.getKey()));

Review Comment:
   There is no @ReadsAttribute entry for anything new
   



-- 
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: dev-unsubscribe@plc4x.apache.org

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


Re: [PR] Feature/nifi integration sink record processor and minor fixes (plc4x)

Posted by "sruehl (via GitHub)" <gi...@apache.org>.
sruehl commented on PR #809:
URL: https://github.com/apache/plc4x/pull/809#issuecomment-1441449363

   Thanks for the PR @QuanticPony 


-- 
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: dev-unsubscribe@plc4x.apache.org

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


Re: [PR] Feature/nifi integration sink record processor and minor fixes (plc4x)

Posted by "ottobackwards (via GitHub)" <gi...@apache.org>.
ottobackwards commented on PR #809:
URL: https://github.com/apache/plc4x/pull/809#issuecomment-1440505855

   Thanks for the update.  I have no more requests, if you are set can you make this Ready for review and move out of draft status?


-- 
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: dev-unsubscribe@plc4x.apache.org

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


Re: [PR] Feature/nifi integration sink record processor and minor fixes (plc4x)

Posted by "QuanticPony (via GitHub)" <gi...@apache.org>.
QuanticPony commented on code in PR #809:
URL: https://github.com/apache/plc4x/pull/809#discussion_r1113977993


##########
plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/Plc4xSinkProcessor.java:
##########
@@ -64,12 +67,13 @@ public void onTrigger(final ProcessContext context, final ProcessSession session
 
             if (tags != null){
                 for (Map.Entry<String,PlcTag> tag : tags.entrySet()){
-                    builder.addTag(tag.getKey(), tag.getValue());
+                    builder.addTag(tag.getKey(), tag.getValue(), flowFile.getAttribute(tag.getKey()));

Review Comment:
   This flowfile's attribute is the value we need to write into the Plc. I forgot including this on the previous PR.
   I have added a check to see if it is present. Similar to Plc4xSinkRecordProcessor and record fields.



-- 
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: dev-unsubscribe@plc4x.apache.org

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


Re: [PR] Feature/nifi integration sink record processor and minor fixes (plc4x)

Posted by "sruehl (via GitHub)" <gi...@apache.org>.
sruehl merged PR #809:
URL: https://github.com/apache/plc4x/pull/809


-- 
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: dev-unsubscribe@plc4x.apache.org

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