fgerlits commented on code in PR #2287:
URL: https://github.com/apache/nifi-minifi-cpp/pull/2287#discussion_r4697698511
##########
extensions/opc/src/FetchOPCFile.cpp:
##########
@@ -0,0 +1,222 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+#include "FetchOPCFile.h"
+
+#include <algorithm>
+#include <limits>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "core/Resource.h"
+#include "minifi-cpp/core/ProcessContext.h"
+#include "utils/ProcessorConfigUtils.h"
+#include "utils/expected.h"
+
+namespace org::apache::nifi::minifi::processors {
+
+namespace {
+// Used when neither the file node nor the server specifies a
MaxByteStringLength
+constexpr UA_UInt32 DEFAULT_CHUNK_SIZE = 32 * 1024;
+
+constexpr const char* NODE_ID_STATE_KEY = "node_id";
+constexpr const char* SIZE_STATE_KEY = "size";
+constexpr const char* LAST_MODIFIED_TIME_STATE_KEY = "last_modified_time";
+} // namespace
+
+void FetchOPCFile::initialize() {
+ setSupportedProperties(Properties);
+ setSupportedRelationships(Relationships);
+}
+
+void FetchOPCFile::onSchedule(core::ProcessContext& context,
core::ProcessSessionFactory& factory) {
+ logger_->log_trace("FetchOPCFile::onSchedule");
+
+ BaseOPCProcessor::onSchedule(context, factory);
+
+ node_id_ = utils::parseProperty(context, NodeID);
+ id_type_ = utils::parseEnumProperty<opc::OPCNodeIDType>(context, NodeIDType);
+ namespace_idx_ = gsl::narrow<UA_UInt16>(utils::parseU64Property(context,
NameSpaceIndex));
+ parseNode(context, PathReferenceTypes);
+ lazy_mode_ = utils::parseEnumProperty<FetchOPCFileLazyModeOptions>(context,
Lazy);
+ cached_file_.reset();
+}
+
+bool FetchOPCFile::reconnect() {
+ const bool was_connected = connection_ && connection_->isConnected();
+ if (!BaseOPCProcessor::reconnect()) {
+ return false;
+ }
+ if (!was_connected) {
+ cached_file_.reset();
+ }
+ return true;
+}
+
+void FetchOPCFile::invalidateFile() {
+ cached_file_.reset();
+ resolved_path_node_ids_.reset();
+}
+
+bool FetchOPCFile::resolveFile(const opc::NodeId& resolved_node) {
+ if (cached_file_) {
+ return true;
+ }
+ auto remote_file = opc::RemoteFile::create(*connection_,
opc::NodeId::copyOf(resolved_node));
+ if (!remote_file) {
+ logger_->log_error("Failed to fetch file node '{}' or find its file
methods: {}", node_id_, UA_StatusCode_name(remote_file.error()));
+ invalidateFile();
+ return false;
+ }
+ const auto chunk_size =
gsl::narrow<UA_Int32>(std::min<UA_UInt32>(remote_file->maxByteStringLength().value_or(DEFAULT_CHUNK_SIZE),
+ static_cast<UA_UInt32>(std::numeric_limits<UA_Int32>::max())));
+ std::optional<opc::NodeId> size_node_id;
+ std::optional<opc::NodeId> last_modified_time_node_id;
+ if (lazy_mode_ == FetchOPCFileLazyModeOptions::On) {
+ // Size is a mandatory, LastModifiedTime is an optional property of
FileType nodes (OPC UA Part 20, 4.2.1)
+ size_node_id = connection_->findChild(resolved_node, "Size", 0,
UA_NS0ID_HASPROPERTY) | utils::toOptional();
+ last_modified_time_node_id = connection_->findChild(resolved_node,
"LastModifiedTime", 0, UA_NS0ID_HASPROPERTY) | utils::toOptional();
+ if (!last_modified_time_node_id && size_node_id) {
+ logger_->log_warn("File node '{}' has no LastModifiedTime property, lazy
mode can only detect the changes of its Size", node_id_);
+ } else if (!last_modified_time_node_id) {
+ logger_->log_warn("File node '{}' has neither LastModifiedTime nor Size
property, lazy mode cannot detect its changes, it is fetched on every trigger",
node_id_);
+ }
+ }
+ auto browse_name = connection_->readBrowseName(resolved_node) |
utils::toOptional();
+ if (!browse_name) {
+ logger_->log_warn("Failed to read browse name of file node '{}'",
node_id_);
+ }
+ cached_file_.emplace(CachedFile{
+ .remote_file = std::move(*remote_file),
+ .chunk_size = chunk_size,
+ .browse_name = std::move(browse_name),
+ .size_node_id = std::move(size_node_id),
+ .last_modified_time_node_id = std::move(last_modified_time_node_id)});
+ return true;
+}
+
+std::optional<core::StateManager::State> FetchOPCFile::readFileState() {
+ core::StateManager::State state;
+ if (cached_file_->size_node_id) {
+ if (auto size = connection_->readUInt64Value(*cached_file_->size_node_id))
{
+ state[SIZE_STATE_KEY] = std::to_string(*size);
+ }
+ }
+ if (cached_file_->last_modified_time_node_id) {
+ if (auto last_modified_time =
connection_->readDateTimeValue(*cached_file_->last_modified_time_node_id)) {
+ state[LAST_MODIFIED_TIME_STATE_KEY] =
std::to_string(*last_modified_time);
+ }
+ }
+ if (state.empty()) {
+ return std::nullopt;
+ }
+ state[NODE_ID_STATE_KEY] = fmt::format("{};{};{}",
magic_enum::enum_name(id_type_), namespace_idx_, node_id_);
+ return state;
+}
+
+bool FetchOPCFile::writeOPCFileToFlowFile(opc::RemoteFile& remote_file,
opc::RemoteFileHandle file_handle, UA_Int32 chunk_size, core::ProcessSession&
session,
+ const std::shared_ptr<core::FlowFile>& flow_file) {
+ UA_StatusCode read_status = UA_STATUSCODE_GOOD;
+ session.write(flow_file, [&](const std::shared_ptr<io::OutputStream>&
output_stream) -> io::IoResult {
+ size_t total_size = 0;
+ while (true) {
+ auto chunk = remote_file.read(file_handle, chunk_size);
+ if (!chunk) {
+ read_status = chunk.error();
+ return io::IoResult::cancelled();
+ }
+ const auto data = chunk->data();
+ if (data.empty()) {
+ return io::IoResult::from(total_size);
+ }
+ const auto written = output_stream->write(data);
+ if (io::isError(written)) {
+ return io::IoResult::error();
+ }
+ total_size += data.size();
+ }
+ });
+
+ if (read_status != UA_STATUSCODE_GOOD) {
+ logger_->log_error("Failed to read file node '{}': {}", node_id_,
UA_StatusCode_name(read_status));
+ session.remove(flow_file);
+ return false;
+ }
+
+ if (auto sc = file_handle.close(); !sc) {
+ logger_->log_warn("Failed to close file node '{}' after reading it: {}",
node_id_, UA_StatusCode_name(sc.error()));
+ }
+ return true;
+}
+
+void FetchOPCFile::onTrigger(core::ProcessContext& context,
core::ProcessSession& session) {
+ logger_->log_trace("FetchOPCFile::onTrigger");
+
+ if (!reconnect()) {
+ logger_->log_warn("Could not connect to OPC server, yielding");
+ context.yield();
+ return;
+ }
+
+ auto* resolved_node = resolveNodeId();
+ if (!resolved_node) {
+ context.yield();
+ return;
+ }
+
+ if (!resolveFile(*resolved_node)) {
+ context.yield();
+ return;
+ }
+
+ auto* state_manager = context.getStateManager();
+ std::optional<core::StateManager::State> file_state;
+ if (lazy_mode_ == FetchOPCFileLazyModeOptions::On) {
+ if (state_manager == nullptr) {
+ logger_->log_error("Failed to get StateManager, lazy mode cannot be
used");
+ context.yield();
+ return;
Review Comment:
I think it would be better to do this check at schedule time and fail to
schedule the processor if Lazy mode is On and the state manager is not
available, as this problem is unlikely to fix itself.
If we have already scheduled the processor in Lazy mode and the state is not
available here in `onTrigger`, I would log a warning and proceed in non-Lazy
mode.
##########
extensions/opc/src/OPCCommon.cpp:
##########
@@ -227,6 +227,38 @@ UA_StatusCode Client::connect(const std::string& url,
const std::string& usernam
}
}
+std::map<std::string, std::string> nodeIdAttributes(const UA_NodeId& node_id) {
+ std::map<std::string, std::string> attributes;
+ if (node_id.identifierType == UA_NODEIDTYPE_STRING) {
+ std::string nodeidstr(reinterpret_cast<const
char*>(node_id.identifier.string.data), //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ node_id.identifier.string.length); //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ attributes["node.id"] = nodeidstr;
+ attributes["node.id.type"] = "string";
+ } else if (node_id.identifierType == UA_NODEIDTYPE_BYTESTRING) {
+ std::string nodeidstr(reinterpret_cast<const
char*>(node_id.identifier.byteString.data), //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ node_id.identifier.byteString.length); //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ attributes["node.id"] = nodeidstr;
+ attributes["node.id.type"] = "bytestring";
+ } else if (node_id.identifierType == UA_NODEIDTYPE_NUMERIC) {
+ attributes["node.id"] = std::to_string(node_id.identifier.numeric); //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ attributes["node.id.type"] = "numeric";
+ } else if (node_id.identifierType == UA_NODEIDTYPE_GUID) {
+ const auto& guid = node_id.identifier.guid; //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ std::array<char, 37> guid_str_array{};
+ auto res = snprintf(guid_str_array.data(), guid_str_array.size(),
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+ guid.data1, guid.data2, guid.data3, guid.data4[0],
guid.data4[1], guid.data4[2],
+ guid.data4[3], guid.data4[4], guid.data4[5],
guid.data4[6], guid.data4[7]);
Review Comment:
can we use `printToString(UA_Guid_print, ...)` here, too?
##########
extensions/opc/include/OPCCommon.h:
##########
@@ -103,6 +104,36 @@ class NodeId {
UA_NodeId id_ = UA_NODEID_NULL;
};
+class MethodOutput {
Review Comment:
`MethodOutput` doesn't really describe what this class is. I understand it
is the output type of `callMethod`, but I think a name like `ArrayOfUAValues`
or something similar would be better.
##########
extensions/opc/tests/features/resources/opcua-file-server/Dockerfile:
##########
@@ -0,0 +1,11 @@
+# SPDX-License-Identifier: Apache-2.0
+# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under
one or more contributor license agreements
+
+FROM lordgamez/open62541:1.5.2
+RUN apk add --no-cache build-base
+COPY file_server.cpp /opt/file_server/
+RUN g++ -std=c++23 -Wall -Wextra -O2 -isystem /usr/local/include/open62541 \
+ -o /opt/file_server/file_server /opt/file_server/file_server.cpp
-lopen62541 && \
+ mkdir -p /data
+CMD ["/opt/file_server/file_server", "/data"]
Review Comment:
Could we use some existing OPC server from dockerhub instead of rolling our
own?
##########
PROCESSORS.md:
##########
@@ -1129,6 +1130,47 @@ In the list below, the names of required properties
appear in bold. Any other pr
| success | Successfully retrieved OPC-UA events |
+## FetchOPCFile
+
+### Description
+
+Fetches the content of an OPC UA FileType node using its Open, Read and Close
methods.
+
+### Properties
+
+In the list below, the names of required properties appear in bold. Any other
properties (not in bold) are considered optional. The table also indicates any
default values, and whether a property supports the NiFi Expression Language.
+
+| Name | Default Value | Allowable Values
| Description
|
+|---------------------------------|---------------|----------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| **OPC server endpoint** | |
| Specifies the address, port and relative path of an OPC endpoint
|
+| Application URI | |
| Application URI of the client in the format
'urn:unconfigured:application'. Mandatory, if using Secure Channel and must
match the URI included in the certificate's Subject Alternative Names.
|
+| Username | |
| Username to log in with.
|
+| Password | |
| Password to log in with.<br/>**Sensitive Property: true**
|
+| Certificate path | |
| Path to the DER-encoded cert file
|
+| Key path | |
| Path to the DER-encoded key file
|
+| Trusted server certificate path | |
| Comma separated list of paths to the DER-encoded trusted server
certificates
|
+| Path reference types | |
| Specify the reference types between nodes in the path if Path Node ID
type is used. If not provided, all reference types are assumed to be Organizes.
The format is 'referenceType1/referenceType2/.../referenceTypeN' and the
supported reference types are Organizes, HasComponent, HasProperty, and
HasSubtype. |
Review Comment:
Machine-assisted nitpick: the description is missing the last sentence
("Subtypes of the specified reference types are also matched.")
It would be best to re-generate the PROCESSORS.md file from the current
state of the processor.
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]