This is an automated email from the ASF dual-hosted git repository.
szaszm pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi-minifi-cpp.git
The following commit(s) were added to refs/heads/main by this push:
new 1c87f39c1 MINIFICPP-2908 Add FetchOPCEvents processor (#2268)
1c87f39c1 is described below
commit 1c87f39c13e45c226bf11442af5f454f77fa6db9
Author: Gabor Gyimesi <[email protected]>
AuthorDate: Fri Nov 20 21:42:24 2026 +0100
MINIFICPP-2908 Add FetchOPCEvents processor (#2268)
* MINIFICPP-2908 Add FetchOPCEvents processor
* Review update
* Fix after rebase
* Review update
* Shorten license headers
* Catch exceptions in OPC UA callbacks
---
.github/references/docker_manifest.json | 187 +++++++++++
PROCESSORS.md | 39 +++
extensions/opc/include/FetchOPCEvents.h | 161 +++++++++
extensions/opc/include/FetchOPCHistory.h | 1 +
extensions/opc/include/OPCCommon.h | 62 +++-
extensions/opc/src/FetchOPCEvents.cpp | 208 ++++++++++++
extensions/opc/src/FetchOPCHistory.cpp | 46 ++-
extensions/opc/src/OPCCommon.cpp | 351 +++++++++++++++-----
extensions/opc/tests/FetchOPCEventsTests.cpp | 455 ++++++++++++++++++++++++++
extensions/opc/tests/OpcUaTestServer.h | 73 +++++
extensions/opc/tests/PutOPCProcessorTests.cpp | 4 +-
11 files changed, 1491 insertions(+), 96 deletions(-)
diff --git a/.github/references/docker_manifest.json
b/.github/references/docker_manifest.json
index d960ed9cd..fa6fe5861 100644
--- a/.github/references/docker_manifest.json
+++ b/.github/references/docker_manifest.json
@@ -6506,6 +6506,193 @@
"bundles": {
"componentManifest": {
"processors": [
+ {
+ "propertyDescriptors": {
+ "Application URI": {
+ "name": "Application URI",
+ "description": "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.",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Batch size": {
+ "name": "Batch size",
+ "description": "Maximum number of events to put in
a single flow file. If set to zero or empty all events retrieved in a single
trigger are put in a single flow file.",
+ "validator": "NON_NEGATIVE_INTEGER_VALIDATOR",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Certificate path": {
+ "name": "Certificate path",
+ "description": "Path to the DER-encoded cert file",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Event filter expression": {
+ "name": "Event filter expression",
+ "description": "Custom filter expression to apply
to the OPC-UA events. It is an open62541 library specific query language
syntax. This overrides the other filter properties (Event type node ID, Select
fields, Minimum severity). Example: SELECT /Message, /Severity WHERE /Severity
>= 100",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Event type node ID": {
+ "name": "Event type node ID",
+ "description": "Adds event type to the event
filter. Only events of this type or its subtypes are reported. i=2041
(BaseEventType) is inherited by every event type, so it applies no type
filtering.",
+ "validator": "VALID",
+ "required": "true",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE",
+ "defaultValue": "i=2041"
+ },
+ "Key path": {
+ "name": "Key path",
+ "description": "Path to the DER-encoded key file",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Max size of message queue": {
+ "name": "Max size of message queue",
+ "description": "Maximum number of events allowed
to be buffered before processing them when the processor is triggered. If the
buffer is full, the oldest events are dropped. If not set or set to zero the
buffer is unlimited.",
+ "validator": "NON_NEGATIVE_INTEGER_VALIDATOR",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE",
+ "defaultValue": "10000"
+ },
+ "Minimum severity": {
+ "name": "Minimum severity",
+ "description": "Specifies the minimum severity of
events to fetch. If not set or set to zero, no severity filter is applied.",
+ "validator": "NON_NEGATIVE_INTEGER_VALIDATOR",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Namespace index": {
+ "name": "Namespace index",
+ "description": "Specifies the index of the
namespace for the target OPC-UA node.",
+ "validator": "NON_NEGATIVE_INTEGER_VALIDATOR",
+ "required": "true",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE",
+ "defaultValue": "0"
+ },
+ "Node ID": {
+ "name": "Node ID",
+ "description": "Specifies the node ID of the
target OPC-UA node to subscribe to. In case of a Path Node ID Type, the path
should be provided in the format of 'path/to/node'.",
+ "validator": "VALID",
+ "required": "true",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Node ID type": {
+ "name": "Node ID type",
+ "description": "Specifies the type of the provided
node ID",
+ "validator": "VALID",
+ "required": "true",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE",
+ "allowableValues": [
+ {
+ "value": "Path",
+ "displayName": "Path"
+ },
+ {
+ "value": "Int",
+ "displayName": "Int"
+ },
+ {
+ "value": "String",
+ "displayName": "String"
+ },
+ {
+ "value": "Guid",
+ "displayName": "Guid"
+ }
+ ]
+ },
+ "OPC server endpoint": {
+ "name": "OPC server endpoint",
+ "description": "Specifies the address, port and
relative path of an OPC endpoint",
+ "validator": "VALID",
+ "required": "true",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Password": {
+ "name": "Password",
+ "description": "Password to log in with.",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "true",
+ "expressionLanguageScope": "NONE"
+ },
+ "Path reference types": {
+ "name": "Path reference types",
+ "description": "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. Subtypes of the
specified reference types are also matched.",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Record set writer": {
+ "typeProvidedByValue": {
+ "type":
"org.apache.nifi.minifi.core.RecordSetWriter",
+ "group": "org.apache.nifi.minifi",
+ "artifact": "minifi-system"
+ },
+ "name": "Record set writer",
+ "description": "Specifies the Controller Service
to use for writing results to a FlowFile.",
+ "validator": "VALID",
+ "required": "true",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Select fields": {
+ "name": "Select fields",
+ "description": "Comma separated browse paths of
the event fields to return, e.g. 'EventId,Time,Message,Severity,SourceName'.
Nested paths use '/', e.g. 'Tool/Diameter', and a browse name outside namespace
0 is prefixed with its namespace index, e.g. '1:Diameter'. A path can be
prefixed with the node ID of an event type to restrict the field to the
instances of that type, e.g. 'i=2052/ActionTimeStamp', but the server rejects
the whole subscription unless it kno [...]
+ "validator": "VALID",
+ "required": "true",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE",
+ "defaultValue":
"EventId,EventType,SourceName,Time,Message,Severity"
+ },
+ "Trusted server certificate path": {
+ "name": "Trusted server certificate path",
+ "description": "Comma separated list of paths to
the DER-encoded trusted server certificates",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ },
+ "Username": {
+ "name": "Username",
+ "description": "Username to log in with.",
+ "validator": "VALID",
+ "required": "false",
+ "sensitive": "false",
+ "expressionLanguageScope": "NONE"
+ }
+ },
+ "inputRequirement": "INPUT_FORBIDDEN",
+ "isSingleThreaded": "true",
+ "supportedRelationships": [
+ {
+ "name": "success",
+ "description": "Successfully retrieved OPC-UA
events"
+ }
+ ],
+ "typeDescription": "Subscribes to OPC-UA events from the
specified node. The processor will continuously listen for events and write
them to flow file records when the processor is triggered. The events can be
filtered using the filtering criteria specified in the processor properties.",
+ "supportsDynamicRelationships": "false",
+ "supportsDynamicProperties": "false",
+ "type": "org.apache.nifi.minifi.processors.FetchOPCEvents"
+ },
{
"propertyDescriptors": {
"Application URI": {
diff --git a/PROCESSORS.md b/PROCESSORS.md
index 3ec57ad80..23d84cd88 100644
--- a/PROCESSORS.md
+++ b/PROCESSORS.md
@@ -37,6 +37,7 @@
- [FetchFile](#FetchFile)
- [FetchGCSObject](#FetchGCSObject)
- [FetchModbusTcp](#FetchModbusTcp)
+- [FetchOPCEvents](#FetchOPCEvents)
- [FetchOPCHistory](#FetchOPCHistory)
- [FetchOPCProcessor](#FetchOPCProcessor)
- [FetchS3Object](#FetchS3Object)
@@ -1090,6 +1091,44 @@ In the list below, the names of required properties
appear in bold. Any other pr
| failure | An error occurred processing |
+## FetchOPCEvents
+
+### Description
+
+Subscribes to OPC-UA events from the specified node. The processor will
continuously listen for events and write them to flow file records when the
processor is triggered. The events can be filtered using the filtering criteria
specified in the processor properties.
+
+### 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.
[...]
+| **Node ID type** |
| Path<br/>Int<br/>String<br/>Guid | Specifies the type of the provided
node ID
[...]
+| **Node ID** |
| | Specifies the node ID of the
target OPC-UA node to subscribe to. In case of a Path Node ID Type, the path
should be provided in the format of 'path/to/node'.
[...]
+| **Namespace index** | 0
| | Specifies the index of the
namespace for the target OPC-UA node.
[...]
+| **Event type node ID** | i=2041
| | Adds event type to the event
filter. Only events of this type or its subtypes are reported. i=2041
(BaseEventType) is inherited by every event type, so it applies no type
filtering.
[...]
+| **Select fields** |
EventId,EventType,SourceName,Time,Message,Severity |
| Comma separated browse paths of the event fields to return, e.g.
'EventId,Time,Message,Severity,SourceName'. Nested paths use '/', e.g.
'Tool/Diameter', and a browse name outside namespace 0 is prefixed with its
namespace index, e.g. '1:Diameter'. A path can be prefixed with the node ID of
an event type to restrict the field to the instances of that type, e.g. 'i=20
[...]
+| Minimum severity |
| | Specifies the minimum severity of
events to fetch. If not set or set to zero, no severity filter is applied.
[...]
+| Event filter expression |
| | Custom filter expression to apply
to the OPC-UA events. It is an open62541 library specific query language
syntax. This overrides the other filter properties (Event type node ID, Select
fields, Minimum severity). Example: SELECT /Message, /Severity WHERE /Severity
>= 100
[...]
+| Max size of message queue | 10000
| | Maximum number of events allowed
to be buffered before processing them when the processor is triggered. If the
buffer is full, the oldest events are dropped. If not set or set to zero the
buffer is unlimited.
[...]
+| Batch size |
| | Maximum number of events to put in
a single flow file. If set to zero or empty all events retrieved in a single
trigger are put in a single flow file.
[...]
+| **Record set writer** |
| | Specifies the Controller Service
to use for writing results to a FlowFile.
[...]
+
+### Relationships
+
+| Name | Description |
+|---------|--------------------------------------|
+| success | Successfully retrieved OPC-UA events |
+
+
## FetchOPCHistory
### Description
diff --git a/extensions/opc/include/FetchOPCEvents.h
b/extensions/opc/include/FetchOPCEvents.h
new file mode 100644
index 000000000..c7b4cec02
--- /dev/null
+++ b/extensions/opc/include/FetchOPCEvents.h
@@ -0,0 +1,161 @@
+// 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
+
+#pragma once
+
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <vector>
+
+#include "BaseOPCProcessor.h"
+#include "OPCCommon.h"
+#include "core/ProcessSession.h"
+#include "core/PropertyDefinitionBuilder.h"
+#include "core/logging/LoggerFactory.h"
+#include "minifi-cpp/controllers/RecordSetWriter.h"
+#include "minifi-cpp/core/Property.h"
+#include "minifi-cpp/core/PropertyValidator.h"
+#include "minifi-cpp/core/RelationshipDefinition.h"
+#include "utils/ArrayUtils.h"
+#include "utils/StoppableThread.h"
+
+using namespace std::literals::chrono_literals;
+
+namespace org::apache::nifi::minifi::processors {
+
+class FetchOPCEvents final : public BaseOPCProcessor {
+ public:
+ using BaseOPCProcessor::BaseOPCProcessor;
+
+ EXTENSIONAPI static constexpr const char* Description =
+ "Subscribes to OPC-UA events from the specified node. "
+ "The processor will continuously listen for events and write them to
flow file records when the processor is triggered. "
+ "The events can be filtered using the filtering criteria specified in
the processor properties.";
+
+ EXTENSIONAPI static constexpr auto NodeIDType =
+
core::PropertyDefinitionBuilder<magic_enum::enum_count<opc::OPCNodeIDType>()>::createProperty("Node
ID type")
+ .withDescription("Specifies the type of the provided node ID")
+ .isRequired(true)
+ .withAllowedValues(magic_enum::enum_names<opc::OPCNodeIDType>())
+ .build();
+ EXTENSIONAPI static constexpr auto NodeID =
+ core::PropertyDefinitionBuilder<>::createProperty("Node ID")
+ .withDescription(
+ "Specifies the node ID of the target OPC-UA node to subscribe
to. In case of a Path Node ID Type, the path should be provided in the "
+ "format of 'path/to/node'.")
+ .isRequired(true)
+ .build();
+ EXTENSIONAPI static constexpr auto NameSpaceIndex =
+ core::PropertyDefinitionBuilder<>::createProperty("Namespace index")
+ .withDescription("Specifies the index of the namespace for the
target OPC-UA node.")
+
.withValidator(core::StandardPropertyValidators::UNSIGNED_INTEGER_VALIDATOR)
+ .withDefaultValue("0")
+ .isRequired(true)
+ .build();
+ EXTENSIONAPI static constexpr auto EventTypeNodeId =
+ core::PropertyDefinitionBuilder<>::createProperty("Event type node ID")
+ .withDescription(
+ "Adds event type to the event filter. Only events of this type
or its subtypes are reported. "
+ "i=2041 (BaseEventType) is inherited by every event type, so it
applies no type filtering.")
+ .withDefaultValue("i=2041")
+ .isRequired(true)
+ .build();
+ EXTENSIONAPI static constexpr auto SelectFields =
+ core::PropertyDefinitionBuilder<>::createProperty("Select fields")
+ .withDescription(
+ "Comma separated browse paths of the event fields to return,
e.g. 'EventId,Time,Message,Severity,SourceName'. "
+ "Nested paths use '/', e.g. 'Tool/Diameter', and a browse name
outside namespace 0 is prefixed with its namespace "
+ "index, e.g. '1:Diameter'. A path can be prefixed with the node
ID of an event type to restrict the field to the "
+ "instances of that type, e.g. 'i=2052/ActionTimeStamp', but the
server rejects the whole subscription unless it "
+ "knows that event type and the field belongs to it. Each field
is named after its path in the record.")
+
.withDefaultValue("EventId,EventType,SourceName,Time,Message,Severity")
+ .isRequired(true)
+ .build();
+ EXTENSIONAPI static constexpr auto MinimumSeverity =
+ core::PropertyDefinitionBuilder<>::createProperty("Minimum severity")
+ .withDescription("Specifies the minimum severity of events to fetch.
If not set or set to zero, no severity filter is applied.")
+
.withValidator(core::StandardPropertyValidators::UNSIGNED_INTEGER_VALIDATOR)
+ .build();
+ EXTENSIONAPI static constexpr auto EventFilterExpression =
+ core::PropertyDefinitionBuilder<>::createProperty("Event filter
expression")
+ .withDescription(
+ "Custom filter expression to apply to the OPC-UA events. It is
an open62541 library specific query language syntax. "
+ "This overrides the other filter properties (Event type node ID,
Select fields, Minimum severity). "
+ "Example: SELECT /Message, /Severity WHERE /Severity >= 100")
+ .build();
+ EXTENSIONAPI static constexpr auto MaxQueueSize =
+ core::PropertyDefinitionBuilder<>::createProperty("Max size of message
queue")
+ .withDescription(
+ "Maximum number of events allowed to be buffered before
processing them when the processor is triggered. "
+ "If the buffer is full, the oldest events are dropped. If not
set or set to zero the buffer is unlimited.")
+
.withValidator(core::StandardPropertyValidators::UNSIGNED_INTEGER_VALIDATOR)
+ .withDefaultValue("10000")
+ .build();
+ EXTENSIONAPI static constexpr auto BatchSize =
+ core::PropertyDefinitionBuilder<>::createProperty("Batch size")
+ .withDescription(
+ "Maximum number of events to put in a single flow file. If set
to zero or empty all events retrieved in a single trigger are put in a "
+ "single flow file.")
+
.withValidator(core::StandardPropertyValidators::UNSIGNED_INTEGER_VALIDATOR)
+ .build();
+ EXTENSIONAPI static constexpr auto RecordSetWriter =
+ core::PropertyDefinitionBuilder<>::createProperty("Record set writer")
+ .withDescription("Specifies the Controller Service to use for
writing results to a FlowFile.")
+ .withAllowedTypes<core::RecordSetWriter>()
+ .isRequired(true)
+ .build();
+ EXTENSIONAPI static constexpr auto PathReferenceTypes =
+ core::PropertyDefinitionBuilder<>::createProperty("Path reference types")
+ .withDescription("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. "
+ "Subtypes of the specified reference types are also
matched.")
+ .build();
+
+ EXTENSIONAPI static constexpr auto Properties =
utils::array_cat(BaseOPCProcessor::Properties,
+ std::to_array<core::PropertyReference>({NodeIDType,
+ NodeID,
+ NameSpaceIndex,
+ EventTypeNodeId,
+ SelectFields,
+ MinimumSeverity,
+ EventFilterExpression,
+ MaxQueueSize,
+ BatchSize,
+ RecordSetWriter,
+ PathReferenceTypes}));
+
+ EXTENSIONAPI static constexpr auto Success =
core::RelationshipDefinition{"success", "Successfully retrieved OPC-UA events"};
+ EXTENSIONAPI static constexpr auto Relationships = std::array{Success};
+
+ EXTENSIONAPI static constexpr bool SupportsDynamicProperties = false;
+ EXTENSIONAPI static constexpr bool SupportsDynamicRelationships = false;
+ EXTENSIONAPI static constexpr core::annotation::Input InputRequirement =
core::annotation::Input::INPUT_FORBIDDEN;
+ EXTENSIONAPI static constexpr bool IsSingleThreaded = true;
+
+ ADD_COMMON_VIRTUAL_FUNCTIONS_FOR_PROCESSORS
+
+ ~FetchOPCEvents() override;
+
+ void onSchedule(core::ProcessContext& context, core::ProcessSessionFactory&
factory) override;
+ void onTrigger(core::ProcessContext& context, core::ProcessSession& session)
override;
+ void initialize() override;
+
+ protected:
+ void notifyStop() override;
+
+ private:
+ void createFlowFiles(core::ProcessSession& session, const
std::vector<opc::Event>& events) const;
+ void runEventLoop();
+ void stopEventThread();
+
+ std::shared_ptr<core::RecordSetWriter> record_set_writer_;
+ std::optional<uint64_t> batch_size_;
+ opc::EventFilterPtr event_filter_;
+ std::mutex connection_mutex_;
+ std::unique_ptr<utils::StoppableThread> event_thread_;
+ std::chrono::milliseconds retry_interval_ = 1s;
+};
+
+} // namespace org::apache::nifi::minifi::processors
diff --git a/extensions/opc/include/FetchOPCHistory.h
b/extensions/opc/include/FetchOPCHistory.h
index 400ff77c2..792203dc3 100644
--- a/extensions/opc/include/FetchOPCHistory.h
+++ b/extensions/opc/include/FetchOPCHistory.h
@@ -42,6 +42,7 @@ struct FetchOPCHistoryContext {
const int32_t namespace_index;
const std::optional<FetchedState> fetched_state;
std::shared_ptr<core::logging::Logger> logger;
+ bool callback_failed = false;
};
class FetchOPCHistory final : public BaseOPCProcessor {
diff --git a/extensions/opc/include/OPCCommon.h
b/extensions/opc/include/OPCCommon.h
index 19ab9ad05..cb4fc53b1 100644
--- a/extensions/opc/include/OPCCommon.h
+++ b/extensions/opc/include/OPCCommon.h
@@ -6,9 +6,13 @@
#pragma once
#include <array>
+#include <chrono>
+#include <deque>
#include <string>
#include <functional>
#include <map>
+#include <unordered_map>
+#include <mutex>
#include <vector>
#include <memory>
#include <expected>
@@ -99,6 +103,26 @@ class NodeId {
UA_NodeId id_ = UA_NODEID_NULL;
};
+struct Event {
+ std::unordered_map<std::string, std::string> fields;
+};
+
+struct EventFilter {
+ std::vector<std::string> select_fields;
+ std::string event_type_node_id;
+ std::optional<uint64_t> minimum_severity;
+ std::string filter_expression;
+};
+
+std::string buildEventFilterExpression(const EventFilter& options);
+
+struct EventFilterDeleter {
+ void operator()(UA_EventFilter* filter) const noexcept {
UA_EventFilter_delete(filter); }
+};
+using EventFilterPtr = std::unique_ptr<UA_EventFilter, EventFilterDeleter>;
+
+std::expected<EventFilterPtr, std::string> parseEventFilter(const std::string&
expression);
+
struct NodeData;
class Client;
@@ -125,17 +149,49 @@ class Client {
UA_StatusCode readHistory(HistoryReadTypeOption history_type, const
UA_NodeId& node_id, const HistoryCallback callback, void* callback_context,
UA_DateTime start_time, UA_DateTime end_time);
+ UA_StatusCode subscribeToEvents(const UA_NodeId& node_id, const
UA_EventFilter& event_filter);
+ [[nodiscard]] bool hasEventSubscription() const noexcept { return
subscription_ && subscription_->alive; }
+ UA_StatusCode processSubscriptionNotifications(UA_UInt32
timeout_milliseconds);
+ std::vector<Event> drainEvents();
+ uint64_t getDroppedEventCountSinceLastCall();
+
static std::unique_ptr<Client> createClient(const
std::shared_ptr<core::logging::Logger>& logger, const std::string&
application_uri,
- const std::vector<char>&
cert_buffer, const std::vector<char>& key_buffer,
- const
std::vector<std::vector<char>>& trust_buffers);
+ const std::vector<char>& cert_buffer, const std::vector<char>&
key_buffer, const std::vector<std::vector<char>>& trust_buffers,
+ std::optional<size_t> max_event_queue_size = std::nullopt);
private:
Client(const std::shared_ptr<core::logging::Logger>& logger, const
std::string& application_uri,
const std::vector<char>& cert_buffer, const std::vector<char>&
key_buffer,
- const std::vector<std::vector<char>>& trust_buffers);
+ const std::vector<std::vector<char>>& trust_buffers,
std::optional<size_t> max_event_queue_size);
+
+ static void eventNotificationCallback(UA_Client *client, UA_UInt32 sub_id,
void *sub_context, UA_UInt32 mon_id, void *mon_context,
+ const UA_KeyValueMap event_fields);
+
+ static void subscriptionStatusChangeCallback(UA_Client *client, UA_UInt32
sub_id, void *sub_context, UA_StatusChangeNotification *notification);
+ static void subscriptionDeleteCallback(UA_Client *client, UA_UInt32 sub_id,
void *sub_context);
+ static void subscriptionInactivityCallback(UA_Client *client, UA_UInt32
sub_id, void *sub_context);
+ void markSubscriptionDead() noexcept {
+ if (subscription_) {
+ subscription_->alive = false;
+ }
+ }
+
+ void pushEvent(Event&& event);
+
+ struct EventSubscription {
+ UA_UInt32 id = 0;
+ bool alive = false;
+ };
UA_Client *client_{nullptr};
std::shared_ptr<core::logging::Logger> logger_;
+
+ std::optional<EventSubscription> subscription_;
+ std::mutex event_queue_mutex_;
+ std::deque<Event> event_queue_;
+ std::optional<size_t> max_event_queue_size_;
+ uint64_t dropped_event_count_{0};
+
UA_Logger minifi_ua_logger_{};
bool use_encryption_{false};
};
diff --git a/extensions/opc/src/FetchOPCEvents.cpp
b/extensions/opc/src/FetchOPCEvents.cpp
new file mode 100644
index 000000000..001cf8ab2
--- /dev/null
+++ b/extensions/opc/src/FetchOPCEvents.cpp
@@ -0,0 +1,208 @@
+// 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 "FetchOPCEvents.h"
+
+#include <chrono>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "OPCCommon.h"
+#include "core/ProcessSession.h"
+#include "core/Resource.h"
+#include "minifi-cpp/core/ProcessContext.h"
+#include "utils/Enum.h"
+#include "utils/ProcessorConfigUtils.h"
+#include "utils/StringUtils.h"
+
+namespace org::apache::nifi::minifi::processors {
+
+namespace {
+// How long one iteration of the event thread waits for notifications to
arrive from the server.
+constexpr UA_UInt32 NOTIFICATION_WAIT_TIME_MS = 200;
+} // namespace
+
+void FetchOPCEvents::initialize() {
+ setSupportedProperties(Properties);
+ setSupportedRelationships(Relationships);
+}
+
+void FetchOPCEvents::onSchedule(core::ProcessContext& context,
core::ProcessSessionFactory& factory) {
+ logger_->log_trace("FetchOPCEvents::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);
+
+ const auto record_set_writer_name = utils::parseProperty(context,
RecordSetWriter);
+ auto controller_service =
context.getControllerService(record_set_writer_name, getUUID());
+ if (!record_set_writer_name.empty() && !controller_service) {
+ throw Exception(PROCESS_SCHEDULE_EXCEPTION, fmt::format("Controller
service '{}' not found", record_set_writer_name));
+ }
+ record_set_writer_ =
std::dynamic_pointer_cast<core::RecordSetWriter>(controller_service);
+ if (!record_set_writer_) {
+ throw Exception(PROCESS_SCHEDULE_EXCEPTION, fmt::format("Failed to obtain
RecordSetWriter controller service '{}'", record_set_writer_name));
+ }
+
+ const auto max_queue_size = utils::parseOptionalU64Property(context,
MaxQueueSize);
+ const auto max_event_queue_size = max_queue_size && *max_queue_size > 0
+ ? std::optional<size_t>(gsl::narrow<size_t>(*max_queue_size))
+ : std::nullopt;
+
+ opc::EventFilter event_filter_options;
+ const auto minimum_severity = utils::parseOptionalU64Property(context,
MinimumSeverity);
+ event_filter_options.minimum_severity = minimum_severity &&
*minimum_severity > 0 ? minimum_severity : std::nullopt;
+
+ event_filter_options.event_type_node_id = utils::parseProperty(context,
EventTypeNodeId);
+ event_filter_options.filter_expression =
context.getProperty(EventFilterExpression).value_or("");
+
+ event_filter_options.select_fields =
utils::string::splitAndTrimRemovingEmpty(utils::parseProperty(context,
SelectFields), ",");
+ if (event_filter_options.select_fields.empty() &&
event_filter_options.filter_expression.empty()) {
+ throw Exception(PROCESS_SCHEDULE_EXCEPTION,
+ fmt::format("At least one field must be set in '{}', otherwise the
events would carry no data", SelectFields.name));
+ }
+
+ const auto event_filter_expression =
opc::buildEventFilterExpression(event_filter_options);
+ logger_->log_debug("Using the event filter '{}'", event_filter_expression);
+ auto event_filter = opc::parseEventFilter(event_filter_expression);
+ if (!event_filter) {
+ throw Exception(PROCESS_SCHEDULE_EXCEPTION, event_filter.error());
+ }
+ event_filter_ = std::move(*event_filter);
+
+ const auto batch_size = utils::parseOptionalU64Property(context, BatchSize);
+ batch_size_ = batch_size && *batch_size > 0 ? batch_size : std::nullopt;
+
+ connection_ = opc::Client::createClient(logger_, application_uri_,
cert_buffer_, key_buffer_, trust_buffers_, max_event_queue_size);
+ if (!connection_) {
+ throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Failed to create the OPC UA
client");
+ }
+
+ gsl_Expects(!event_thread_);
+ retry_interval_ = 1s;
+ event_thread_ = std::make_unique<utils::StoppableThread>([this]() {
runEventLoop(); });
+}
+
+void FetchOPCEvents::runEventLoop() {
+ auto retry = [&]() {
+ utils::StoppableThread::waitForStopRequest(retry_interval_);
+ if (retry_interval_ < 64s) {
+ retry_interval_ *= 2;
+ }
+ };
+
+ while (!utils::StoppableThread::waitForStopRequest(0ms)) {
+ try {
+ if (!reconnect()) {
+ retry();
+ continue;
+ }
+
+ const auto* node = resolveNodeId();
+ if (!node) {
+ retry();
+ continue;
+ }
+
+ if (!connection_->hasEventSubscription()) {
+ if (auto sc = connection_->subscribeToEvents(*node, *event_filter_);
sc != UA_STATUSCODE_GOOD) {
+ logger_->log_error("Failed to subscribe to the events of node '{}':
{}", node_id_, UA_StatusCode_name(sc));
+ retry();
+ continue;
+ }
+ logger_->log_debug("Subscribed to the events of node '{}'", node_id_);
+ }
+
+ // Receives the event notifications that arrived since the last call and
queues them for onTrigger to take.
+ if (auto sc =
connection_->processSubscriptionNotifications(NOTIFICATION_WAIT_TIME_MS); sc !=
UA_STATUSCODE_GOOD) {
+ logger_->log_error("Failed to process the OPC UA event notifications:
{}", UA_StatusCode_name(sc));
+ retry();
+ continue;
+ }
+ retry_interval_ = 1s;
+ } catch (const std::exception& ex) {
+ logger_->log_error("Exception while receiving OPC UA events: {}",
ex.what());
+ retry();
+ }
+ }
+}
+
+void FetchOPCEvents::stopEventThread() {
+ event_thread_.reset();
+ const std::lock_guard<std::mutex> lock(connection_mutex_);
+ connection_.reset();
+}
+
+void FetchOPCEvents::notifyStop() {
+ stopEventThread();
+}
+
+FetchOPCEvents::~FetchOPCEvents() {
+ stopEventThread();
+}
+
+void FetchOPCEvents::createFlowFiles(core::ProcessSession& session, const
std::vector<opc::Event>& events) const {
+ core::RecordSet record_set;
+ const auto writeToFlowFile = [&]() {
+ auto flow_file = session.create();
+ record_set_writer_->write(record_set, flow_file, session);
+
+ session.transfer(flow_file, Success);
+ record_set.clear();
+ };
+
+ for (const auto& event : events) {
+ core::Record record;
+ for (const auto& [name, value] : event.fields) {
+ record.emplace(name, core::RecordField(value));
+ }
+ record_set.push_back(std::move(record));
+
+ if (batch_size_ && *batch_size_ > 0 && record_set.size() >= *batch_size_) {
+ writeToFlowFile();
+ }
+ }
+
+ if (!record_set.empty()) {
+ writeToFlowFile();
+ }
+}
+
+void FetchOPCEvents::onTrigger(core::ProcessContext& context,
core::ProcessSession& session) {
+ logger_->log_trace("FetchOPCEvents::onTrigger");
+
+ std::vector<opc::Event> events;
+ uint64_t dropped_event_count = 0;
+ {
+ const std::lock_guard<std::mutex> lock(connection_mutex_);
+ if (!connection_) {
+ context.yield();
+ return;
+ }
+ dropped_event_count = connection_->getDroppedEventCountSinceLastCall();
+ events = connection_->drainEvents();
+ }
+
+ if (dropped_event_count > 0) {
+ logger_->log_warn("The event queue is full, {} OPC UA events were dropped.
Consider increasing '{}' or triggering the processor more often.",
+ dropped_event_count,
+ MaxQueueSize.name);
+ }
+
+ if (events.empty()) {
+ logger_->log_debug("No OPC UA events were received");
+ context.yield();
+ return;
+ }
+
+ createFlowFiles(session, events);
+ logger_->log_debug("Transferred {} OPC UA events", events.size());
+}
+
+REGISTER_RESOURCE(FetchOPCEvents, Processor);
+
+} // namespace org::apache::nifi::minifi::processors
diff --git a/extensions/opc/src/FetchOPCHistory.cpp
b/extensions/opc/src/FetchOPCHistory.cpp
index f14389e4c..43449bb09 100644
--- a/extensions/opc/src/FetchOPCHistory.cpp
+++ b/extensions/opc/src/FetchOPCHistory.cpp
@@ -210,27 +210,35 @@ UA_Boolean historyReadCallback(UA_Client* /*client*/,
const UA_NodeId* /*node_id
void* ctx) {
auto* opc_history_context = static_cast<FetchOPCHistoryContext*>(ctx);
- const auto binary_encoding = opc_history_context->record_set_writer ?
opc::BinaryEncoding::Base64 : opc::BinaryEncoding::Raw;
- auto batch = extractHistoryBatch(data, binary_encoding,
opc_history_context->logger);
- if (batch && !batch->entries.empty()) {
- const std::optional<size_t> remaining = opc_history_context->batch_size != 0
- ? std::optional<size_t>(opc_history_context->batch_size -
opc_history_context->entries_transferred)
- : std::nullopt;
- auto new_entries = selectNewEntries(std::move(batch->entries),
opc_history_context->fetched_state, batch->has_modification_info, remaining);
-
- if (!new_entries.empty()) {
- if (opc_history_context->record_set_writer) {
- writeAsRecordSet(*opc_history_context, new_entries);
- } else {
- writeAsFlowFiles(*opc_history_context, new_entries);
+ try {
+ const auto binary_encoding = opc_history_context->record_set_writer ?
opc::BinaryEncoding::Base64 : opc::BinaryEncoding::Raw;
+ auto batch = extractHistoryBatch(data, binary_encoding,
opc_history_context->logger);
+ if (batch && !batch->entries.empty()) {
+ const std::optional<size_t> remaining = opc_history_context->batch_size
!= 0
+ ? std::optional<size_t>(opc_history_context->batch_size -
opc_history_context->entries_transferred)
+ : std::nullopt;
+ auto new_entries = selectNewEntries(std::move(batch->entries),
opc_history_context->fetched_state, batch->has_modification_info, remaining);
+
+ if (!new_entries.empty()) {
+ if (opc_history_context->record_set_writer) {
+ writeAsRecordSet(*opc_history_context, new_entries);
+ } else {
+ writeAsFlowFiles(*opc_history_context, new_entries);
+ }
+ updateState(opc_history_context->state_map, new_entries,
batch->has_modification_info);
}
- updateState(opc_history_context->state_map, new_entries,
batch->has_modification_info);
}
- }
- const bool batch_limit_reached = opc_history_context->batch_size != 0 &&
- opc_history_context->entries_transferred >=
opc_history_context->batch_size;
- return more_data_available && !batch_limit_reached;
+ const bool batch_limit_reached = opc_history_context->batch_size != 0 &&
+ opc_history_context->entries_transferred >=
opc_history_context->batch_size;
+ return more_data_available && !batch_limit_reached;
+ } catch (const std::exception& ex) {
+ opc_history_context->logger->log_error("Failed to process the OPC UA
history read result: {}", ex.what());
+ } catch (...) {
+ opc_history_context->logger->log_error("Failed to process the OPC UA
history read result, exception type: {}", getCurrentExceptionTypeName());
+ }
+ opc_history_context->callback_failed = true;
+ return false;
}
UA_DateTime toUaDateTime(std::chrono::system_clock::time_point tp) {
@@ -363,6 +371,8 @@ void FetchOPCHistory::onTrigger(core::ProcessContext&
context, core::ProcessSess
if (retval != UA_STATUSCODE_GOOD) {
logger_->log_error("Failed to read OPC UA node history, status code: {}",
UA_StatusCode_name(retval));
context.yield();
+ } else if (history_context.callback_failed) {
+ context.yield();
}
}
diff --git a/extensions/opc/src/OPCCommon.cpp b/extensions/opc/src/OPCCommon.cpp
index 0b3257cf0..07f96605b 100644
--- a/extensions/opc/src/OPCCommon.cpp
+++ b/extensions/opc/src/OPCCommon.cpp
@@ -4,9 +4,14 @@
#include "OPCCommon.h"
+#include <algorithm>
+#include <chrono>
#include <cstdio>
#include <cstdlib>
+#include <iterator>
#include <memory>
+#include <mutex>
+#include <utility>
#include <vector>
#include <string>
#include <string_view>
@@ -21,6 +26,7 @@
#include "open62541/client_highlevel.h"
#include "open62541/client_config_default.h"
+#include "open62541/client_subscriptions.h"
extern "C" int mp_vsnprintf(char* s, size_t count, const char* format, va_list
arg);
@@ -112,8 +118,9 @@ core::logging::LOG_LEVEL MapOPCLogLevel(UA_LogLevel ualvl) {
Client::Client(const std::shared_ptr<core::logging::Logger>& logger, const
std::string& application_uri,
const std::vector<char>& cert_buffer, const std::vector<char>&
key_buffer,
- const std::vector<std::vector<char>>& trust_buffers)
- : use_encryption_(!cert_buffer.empty()) {
+ const std::vector<std::vector<char>>& trust_buffers,
std::optional<size_t> max_event_queue_size)
+ : max_event_queue_size_(max_event_queue_size),
+ use_encryption_(!cert_buffer.empty()) {
minifi_ua_logger_ = {logFunc, logger.get(), [](UA_Logger*){}};
// Build the config with our logger pre-installed so that open62541 doesn't
allocate a default stdout logger (as it would with UA_Client_new).
@@ -165,6 +172,7 @@ Client::Client(const
std::shared_ptr<core::logging::Logger>& logger, const std::
}
config.allowNonePolicyPassword = true;
+ config.subscriptionInactivityCallback =
&Client::subscriptionInactivityCallback;
if (!application_uri.empty()) {
UA_String_clear(&config.clientDescription.applicationUri);
@@ -207,6 +215,8 @@ bool Client::isConnected() {
}
UA_StatusCode Client::connect(const std::string& url, const std::string&
username, const std::string& password) {
+ markSubscriptionDead();
+
if (username.empty()) {
return UA_Client_connect(client_, url.c_str());
} else {
@@ -218,74 +228,92 @@ UA_StatusCode Client::connect(const std::string& url,
const std::string& usernam
}
NodeData Client::getNodeData(const UA_ReferenceDescription *ref, const
std::string& base_path) {
- if (ref->nodeClass == UA_NODECLASS_VARIABLE) {
- opc::NodeData nodedata;
- std::string browsename(reinterpret_cast<const
char*>(ref->browseName.name.data), ref->browseName.name.length);
-
- if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_STRING) {
- std::string nodeidstr(reinterpret_cast<const
char*>(ref->nodeId.nodeId.identifier.string.data), //
NOLINT(cppcoreguidelines-pro-type-union-access)
- ref->nodeId.nodeId.identifier.string.length); //
NOLINT(cppcoreguidelines-pro-type-union-access)
- nodedata.attributes["node.id"] = nodeidstr;
- nodedata.attributes["node.id.type"] = "string";
- } else if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_BYTESTRING) {
- std::string nodeidstr(reinterpret_cast<const
char*>(ref->nodeId.nodeId.identifier.byteString.data), //
NOLINT(cppcoreguidelines-pro-type-union-access)
- ref->nodeId.nodeId.identifier.byteString.length); //
NOLINT(cppcoreguidelines-pro-type-union-access)
- nodedata.attributes["node.id"] = nodeidstr;
- nodedata.attributes["node.id.type"] = "bytestring";
- } else if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_NUMERIC) {
- nodedata.attributes["node.id"] =
std::to_string(ref->nodeId.nodeId.identifier.numeric); //
NOLINT(cppcoreguidelines-pro-type-union-access)
- nodedata.attributes["node.id.type"] = "numeric";
- } else if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_GUID) {
- nodedata.attributes["node.id"] = printToString(UA_Guid_print,
ref->nodeId.nodeId.identifier.guid, "GUID"); //
NOLINT(cppcoreguidelines-pro-type-union-access)
- nodedata.attributes["node.id.type"] = "guid";
- }
- nodedata.attributes["namespace.index"] =
std::to_string(ref->nodeId.nodeId.namespaceIndex);
- nodedata.attributes["browse.name"] = browsename;
+ if (ref->nodeClass != UA_NODECLASS_VARIABLE) {
+ throw OPCException(GENERAL_EXCEPTION, "Only variable nodes are
supported!");
+ }
- auto splitted_base_path =
utils::string::splitAndTrimRemovingEmpty(base_path, "/");
- if (!splitted_base_path.empty() && splitted_base_path.back() ==
browsename) {
- nodedata.attributes["full.path"] = base_path;
- } else {
- nodedata.attributes["full.path"] = base_path + "/" + browsename;
- }
- UA_Variant* var = UA_Variant_new();
- if (UA_Client_readValueAttribute(client_, ref->nodeId.nodeId, var) ==
UA_STATUSCODE_GOOD && var->type != nullptr && var->data != nullptr) {
- // Because the timestamps are eliminated in readValueAttribute for
simplification
- // We need to call the inner function UA_Client_Service_read.
- UA_ReadValueId item;
- UA_ReadValueId_init(&item);
- item.nodeId = ref->nodeId.nodeId;
- item.attributeId = UA_ATTRIBUTEID_VALUE;
- UA_ReadRequest request;
- UA_ReadRequest_init(&request);
- request.nodesToRead = &item;
- request.nodesToReadSize = 1;
- // Differ from ua_client_highlevel.c src
- request.timestampsToReturn = UA_TIMESTAMPSTORETURN_BOTH;
- UA_ReadResponse response = UA_Client_Service_read(client_, request);
- UA_DataValue *dv = response.results;
- auto source_timestamp = OPCDateTime2String(dv->sourceTimestamp);
- nodedata.attributes["source.timestamp"] = source_timestamp;
- UA_ReadResponse_clear(&response);
-
- nodedata.addVariant(var);
- if (var->type->typeName) {
- nodedata.attributes["type.name"] = std::string(var->type->typeName);
- }
- if (UA_Variant_isScalar(var)) {
- if (var->type->pointerFree) {
- nodedata.attributes["data.size"] =
std::to_string(var->type->memSize);
- } else if (var->type->typeKind == UA_DATATYPEKIND_STRING ||
var->type->typeKind == UA_DATATYPEKIND_BYTESTRING || var->type->typeKind ==
UA_DATATYPEKIND_XMLELEMENT) {
- nodedata.attributes["data.size"] = std::to_string(static_cast<const
UA_String*>(var->data)->length);
- }
- }
- return nodedata;
- }
- UA_Variant_delete(var);
- throw OPCException(GENERAL_EXCEPTION, "Failed to read value of node: " +
browsename);
+ opc::NodeData nodedata;
+ std::string browsename(reinterpret_cast<const
char*>(ref->browseName.name.data), ref->browseName.name.length);
+
+ if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_STRING) {
+ std::string nodeidstr(reinterpret_cast<const
char*>(ref->nodeId.nodeId.identifier.string.data), //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ ref->nodeId.nodeId.identifier.string.length); //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ nodedata.attributes["node.id"] = nodeidstr;
+ nodedata.attributes["node.id.type"] = "string";
+ } else if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_BYTESTRING) {
+ std::string nodeidstr(reinterpret_cast<const
char*>(ref->nodeId.nodeId.identifier.byteString.data), //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ ref->nodeId.nodeId.identifier.byteString.length); //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ nodedata.attributes["node.id"] = nodeidstr;
+ nodedata.attributes["node.id.type"] = "bytestring";
+ } else if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_NUMERIC) {
+ nodedata.attributes["node.id"] =
std::to_string(ref->nodeId.nodeId.identifier.numeric); //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ nodedata.attributes["node.id.type"] = "numeric";
+ } else if (ref->nodeId.nodeId.identifierType == UA_NODEIDTYPE_GUID) {
+ nodedata.attributes["node.id"] = printToString(UA_Guid_print,
ref->nodeId.nodeId.identifier.guid, "GUID"); //
NOLINT(cppcoreguidelines-pro-type-union-access)
+ nodedata.attributes["node.id.type"] = "guid";
+ }
+ nodedata.attributes["namespace.index"] =
std::to_string(ref->nodeId.nodeId.namespaceIndex);
+ nodedata.attributes["browse.name"] = browsename;
+
+ auto splitted_base_path =
utils::string::splitAndTrimRemovingEmpty(base_path, "/");
+ if (!splitted_base_path.empty() && splitted_base_path.back() == browsename) {
+ nodedata.attributes["full.path"] = base_path;
} else {
- throw OPCException(GENERAL_EXCEPTION, "Only variable nodes are
supported!");
+ nodedata.attributes["full.path"] = base_path + "/" + browsename;
+ }
+
+ UA_ReadValueId item;
+ UA_ReadValueId_init(&item);
+ item.nodeId = ref->nodeId.nodeId;
+ item.attributeId = UA_ATTRIBUTEID_VALUE;
+ UA_ReadRequest request;
+ UA_ReadRequest_init(&request);
+ request.nodesToRead = &item;
+ request.nodesToReadSize = 1;
+ request.timestampsToReturn = UA_TIMESTAMPSTORETURN_BOTH;
+ UA_ReadResponse response = UA_Client_Service_read(client_, request);
+ const auto response_guard = gsl::finally([&response]() {
UA_ReadResponse_clear(&response); });
+
+ const auto read_failed = [&browsename](const std::string& reason) {
+ return OPCException(GENERAL_EXCEPTION, "Failed to read value of node '" +
browsename + "': " + reason);
+ };
+ if (response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
+ throw
read_failed(UA_StatusCode_name(response.responseHeader.serviceResult));
+ }
+ if (response.resultsSize != 1 || response.results == nullptr) {
+ throw read_failed("unexpected number of results: " +
std::to_string(response.resultsSize));
}
+ UA_DataValue& data_value = response.results[0];
+ if (data_value.hasStatus && data_value.status != UA_STATUSCODE_GOOD) {
+ throw read_failed(UA_StatusCode_name(data_value.status));
+ }
+ if (!data_value.hasValue || data_value.value.type == nullptr ||
data_value.value.data == nullptr) {
+ throw read_failed("no value returned");
+ }
+
+ UA_Variant* var = UA_Variant_new();
+ if (var == nullptr) {
+ throw read_failed("out of memory");
+ }
+ // Move the value out of the response, so that it is not freed by
UA_ReadResponse_clear, and hand it over to nodedata immediately
+ *var = data_value.value;
+ UA_Variant_init(&data_value.value);
+ nodedata.addVariant(var);
+
+ if (data_value.hasSourceTimestamp) {
+ nodedata.attributes["source.timestamp"] =
OPCDateTime2String(data_value.sourceTimestamp);
+ }
+ if (var->type->typeName) {
+ nodedata.attributes["type.name"] = std::string(var->type->typeName);
+ }
+ if (UA_Variant_isScalar(var)) {
+ if (var->type->pointerFree) {
+ nodedata.attributes["data.size"] = std::to_string(var->type->memSize);
+ } else if (var->type->typeKind == UA_DATATYPEKIND_STRING ||
var->type->typeKind == UA_DATATYPEKIND_BYTESTRING || var->type->typeKind ==
UA_DATATYPEKIND_XMLELEMENT) {
+ nodedata.attributes["data.size"] = std::to_string(static_cast<const
UA_String*>(var->data)->length);
+ }
+ }
+ return nodedata;
}
UA_ReferenceDescription * Client::getNodeReference(UA_NodeId node_id) {
@@ -462,9 +490,9 @@ UA_StatusCode Client::update_node(const UA_NodeId node_id,
T value) {
std::unique_ptr<Client> Client::createClient(const
std::shared_ptr<core::logging::Logger>& logger, const std::string&
application_uri,
const std::vector<char>&
cert_buffer, const std::vector<char>& key_buffer,
- const
std::vector<std::vector<char>>& trust_buffers) {
+ const
std::vector<std::vector<char>>& trust_buffers, std::optional<size_t>
max_event_queue_size) {
try {
- return ClientPtr(new Client(logger, application_uri, cert_buffer,
key_buffer, trust_buffers));
+ return ClientPtr(new Client(logger, application_uri, cert_buffer,
key_buffer, trust_buffers, max_event_queue_size));
} catch (const std::exception& exception) {
logger->log_error("Failed to create client: {}", exception.what());
}
@@ -587,10 +615,13 @@ std::string OPCDateTime2String(UA_DateTime raw_date) {
}
void logFunc(void *context, UA_LogLevel level, UA_LogCategory /*category*/,
const char *msg, va_list args) {
- std::array<char, 1024> buffer{};
- (void)mp_vsnprintf(buffer.data(), buffer.size(), msg, args);
- auto loggerPtr = reinterpret_cast<core::logging::Logger*>(context);
- loggerPtr->log_string(MapOPCLogLevel(level), buffer.data());
+ try {
+ std::array<char, 1024> buffer{};
+ (void)mp_vsnprintf(buffer.data(), buffer.size(), msg, args);
+ auto loggerPtr = reinterpret_cast<core::logging::Logger*>(context);
+ loggerPtr->log_string(MapOPCLogLevel(level), buffer.data());
+ } catch (...) {
+ }
}
std::optional<UA_UInt32> mapOpcReferenceType(const std::string& ref_type) {
@@ -657,4 +688,178 @@ std::expected<opc::NodeId, std::string>
buildNodeId(opc::OPCNodeIDType id_type,
}
}
+std::string buildEventFilterExpression(const EventFilter& options) {
+ if (!options.filter_expression.empty()) {
+ return options.filter_expression;
+ }
+
+ // The browse paths of the select clauses are written with a leading '/',
which is not required from the property. A field
+ // that is prefixed with the node id of an event type keeps its own prefix:
such a path starts with the node id, not a '/'.
+ gsl_Expects(!options.select_fields.empty());
+ std::string expression = "SELECT ";
+ for (const auto& select_field : options.select_fields) {
+ const bool is_full_path = select_field.starts_with('/') ||
select_field.contains('=');
+ expression += is_full_path ? select_field : "/" + select_field;
+ expression += ", ";
+ }
+ expression.erase(expression.size() - 2);
+
+ std::vector<std::string> conditions;
+ if (!options.event_type_node_id.empty()) {
+ conditions.push_back("OFTYPE " + options.event_type_node_id);
+ }
+ if (options.minimum_severity) {
+ conditions.push_back("/Severity >= " +
std::to_string(*options.minimum_severity));
+ }
+ if (!conditions.empty()) {
+ expression += " WHERE " + utils::string::join(" AND ", conditions);
+ }
+ return expression;
+}
+
+std::expected<EventFilterPtr, std::string> parseEventFilter(const std::string&
expression) {
+ EventFilterPtr filter{UA_EventFilter_new()};
+ if (!filter) {
+ return std::unexpected("Failed to allocate the event filter");
+ }
+ if (auto sc = UA_EventFilter_parse(filter.get(),
UA_STRING(const_cast<char*>(expression.c_str())), nullptr); sc !=
UA_STATUSCODE_GOOD) {
+ return std::unexpected(fmt::format("Failed to parse the event filter '{}':
{}", expression, UA_StatusCode_name(sc)));
+ }
+ return filter;
+}
+
+UA_StatusCode Client::subscribeToEvents(const UA_NodeId& node_id, const
UA_EventFilter& event_filter) {
+ if (subscription_) {
+ logger_->log_debug("Deleting the dead OPC UA event subscription {} before
resubscribing", subscription_->id);
+ UA_Client_Subscriptions_deleteSingle(client_, subscription_->id);
+ subscription_.reset();
+ }
+
+ UA_CreateSubscriptionResponse response =
UA_Client_Subscriptions_create(client_, UA_CreateSubscriptionRequest_default(),
this,
+
&Client::subscriptionStatusChangeCallback, &Client::subscriptionDeleteCallback);
+ const auto response_guard = gsl::finally([&response]() {
UA_CreateSubscriptionResponse_clear(&response); });
+ if (response.responseHeader.serviceResult != UA_STATUSCODE_GOOD) {
+ return response.responseHeader.serviceResult;
+ }
+ const auto subscription_id = response.subscriptionId;
+ auto subscription_id_guard = gsl::finally([this, &subscription_id]() {
+ if (!subscription_ || subscription_->id != subscription_id) {
+ UA_Client_Subscriptions_deleteSingle(client_, subscription_id);
+ }
+ });
+
+ UA_MonitoredItemCreateRequest item;
+ UA_MonitoredItemCreateRequest_init(&item);
+ const auto item_guard = gsl::finally([&item]() {
UA_MonitoredItemCreateRequest_clear(&item); });
+ UA_NodeId_copy(&node_id, &item.itemToMonitor.nodeId);
+ item.itemToMonitor.attributeId = UA_ATTRIBUTEID_EVENTNOTIFIER;
+ item.monitoringMode = UA_MONITORINGMODE_REPORTING;
+
+ UA_ExtensionObject_setValueNoDelete(&item.requestedParameters.filter,
const_cast<UA_EventFilter*>(&event_filter), &UA_TYPES[UA_TYPES_EVENTFILTER]);
+
+ UA_MonitoredItemCreateResult result =
UA_Client_MonitoredItems_createEvent(client_, subscription_id,
UA_TIMESTAMPSTORETURN_BOTH, item,
+
this, eventNotificationCallback, nullptr);
+ const auto result_guard = gsl::finally([&result]() {
UA_MonitoredItemCreateResult_clear(&result); });
+ if (result.statusCode != UA_STATUSCODE_GOOD) {
+ return result.statusCode;
+ }
+
+ subscription_ = EventSubscription{.id = subscription_id, .alive = true};
+ return UA_STATUSCODE_GOOD;
+}
+
+void Client::eventNotificationCallback(UA_Client* /*client*/, UA_UInt32
/*sub_id*/, void* /*sub_context*/, UA_UInt32 /*mon_id*/, void* mon_context,
+ const UA_KeyValueMap event_fields) {
+ auto* client = static_cast<Client*>(mon_context);
+
+ try {
+ Event event;
+ for (size_t i = 0; i < event_fields.mapSize; ++i) {
+ const UA_KeyValuePair& field = event_fields.map[i];
+ std::string name{reinterpret_cast<const char*>(field.key.name.data),
field.key.name.length};
+ if (name.starts_with('/')) {
+ name.erase(0, 1);
+ }
+ if (UA_Variant_isEmpty(&field.value)) {
+ continue;
+ }
+ try {
+ event.fields[name] = variantToString(field.value,
BinaryEncoding::Base64);
+ } catch (const std::exception& ex) {
+ client->logger_->log_warn("Failed to convert event field '{}' to
string, skipping field: {}", name, ex.what());
+ }
+ }
+ client->pushEvent(std::move(event));
+ } catch (const std::exception& ex) {
+ client->logger_->log_error("Failed to process an OPC UA event
notification: {}", ex.what());
+ } catch (...) {
+ client->logger_->log_error("Failed to process an OPC UA event
notification, exception type: {}", getCurrentExceptionTypeName());
+ }
+}
+
+void Client::subscriptionStatusChangeCallback(UA_Client* /*client*/, UA_UInt32
sub_id, void* sub_context, UA_StatusChangeNotification* notification) {
+ auto* client = static_cast<Client*>(sub_context);
+ try {
+ client->markSubscriptionDead();
+ client->logger_->log_warn("The OPC UA server reported the event
subscription {} as {}, a new subscription will be created", sub_id,
+ UA_StatusCode_name(notification->status));
+ } catch (const std::exception& ex) {
+ client->logger_->log_error("Failed to process the OPC UA subscription
status change: {}", ex.what());
+ } catch (...) {
+ client->logger_->log_error("Failed to process the OPC UA subscription
status change, exception type: {}", getCurrentExceptionTypeName());
+ }
+}
+
+void Client::subscriptionDeleteCallback(UA_Client* /*client*/, UA_UInt32
sub_id, void* sub_context) {
+ auto* client = static_cast<Client*>(sub_context);
+ try {
+ // The subscription is already gone from the client, so there is nothing
left to delete before resubscribing.
+ client->subscription_.reset();
+ client->logger_->log_debug("The OPC UA event subscription {} was deleted",
sub_id);
+ } catch (const std::exception& ex) {
+ client->logger_->log_error("Failed to process the OPC UA subscription
deletion: {}", ex.what());
+ } catch (...) {
+ client->logger_->log_error("Failed to process the OPC UA subscription
deletion, exception type: {}", getCurrentExceptionTypeName());
+ }
+}
+
+void Client::subscriptionInactivityCallback(UA_Client* /*client*/, UA_UInt32
sub_id, void* sub_context) {
+ auto* client = static_cast<Client*>(sub_context);
+ try {
+ client->markSubscriptionDead();
+ client->logger_->log_warn("The OPC UA event subscription {} stopped
delivering notifications, a new subscription will be created", sub_id);
+ } catch (const std::exception& ex) {
+ client->logger_->log_error("Failed to process the OPC UA subscription
inactivity: {}", ex.what());
+ } catch (...) {
+ client->logger_->log_error("Failed to process the OPC UA subscription
inactivity, exception type: {}", getCurrentExceptionTypeName());
+ }
+}
+
+void Client::pushEvent(Event&& event) {
+ const std::lock_guard<std::mutex> lock(event_queue_mutex_);
+ event_queue_.push_back(std::move(event));
+ while (max_event_queue_size_ && event_queue_.size() >
*max_event_queue_size_) {
+ event_queue_.pop_front();
+ ++dropped_event_count_;
+ }
+}
+
+UA_StatusCode Client::processSubscriptionNotifications(UA_UInt32
timeout_milliseconds) {
+ return UA_Client_run_iterate(client_, timeout_milliseconds);
+}
+
+std::vector<Event> Client::drainEvents() {
+ std::deque<Event> events;
+ {
+ const std::lock_guard<std::mutex> lock(event_queue_mutex_);
+ events.swap(event_queue_);
+ }
+ return {std::make_move_iterator(events.begin()),
std::make_move_iterator(events.end())};
+}
+
+uint64_t Client::getDroppedEventCountSinceLastCall() {
+ const std::lock_guard<std::mutex> lock(event_queue_mutex_);
+ return std::exchange(dropped_event_count_, 0);
+}
+
} // namespace org::apache::nifi::minifi::opc
diff --git a/extensions/opc/tests/FetchOPCEventsTests.cpp
b/extensions/opc/tests/FetchOPCEventsTests.cpp
new file mode 100644
index 000000000..4b9e85d0d
--- /dev/null
+++ b/extensions/opc/tests/FetchOPCEventsTests.cpp
@@ -0,0 +1,455 @@
+// 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 <algorithm>
+#include <cctype>
+#include <regex>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "OpcUaTestServer.h"
+#include "catch2/generators/catch_generators.hpp"
+#include "include/FetchOPCEvents.h"
+#include "unit/Catch.h"
+#include "unit/SingleProcessorTestController.h"
+#include "unit/TestBase.h"
+#include "unit/TestUtils.h"
+
+namespace org::apache::nifi::minifi::test {
+
+class FetchOPCEventsTestController {
+ public:
+ FetchOPCEventsTestController()
+ :
controller_(minifi::test::utils::make_processor<processors::FetchOPCEvents>("FetchOPCEvents")),
+ processor_(controller_.getProcessor()) {
+ LogTestController::getInstance().setDebug<TestPlan>();
+ LogTestController::getInstance().setDebug<minifi::core::Processor>();
+ LogTestController::getInstance().setTrace<minifi::core::ProcessSession>();
+ LogTestController::getInstance().setDebug<processors::FetchOPCEvents>();
+ }
+
+ void setupProcessor(const std::string& node_id_type, const std::string&
node_id) {
+ REQUIRE(controller_.plan->addController("JsonRecordSetWriter",
"JsonRecordSetWriter"));
+ REQUIRE(controller_.plan->setProperty(processor_,
processors::FetchOPCEvents::RecordSetWriter.name, "JsonRecordSetWriter"));
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::OPCServerEndPoint.name,
"opc.tcp://127.0.0.1:4843/"));
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::NodeIDType.name,
node_id_type));
+ REQUIRE(processor_->setProperty(processors::FetchOPCEvents::NodeID.name,
node_id));
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::NameSpaceIndex.name,
std::to_string(server_.getNamespaceIndex())));
+ }
+
+ void waitForSubscription() {
+
CHECK(controller_.trigger().at(processors::FetchOPCEvents::Success).empty());
+ REQUIRE(utils::verifyLogLinePresenceInPollTime(10s, "Subscribed to the
events of node"));
+ }
+
+ // The processor reports the events dropped since the previous trigger, so
the total has to be summed up over all the warnings.
+ static size_t countDroppedEvents() {
+ const std::regex dropped_event_pattern{R"(The event queue is full, (\d+)
OPC UA events were dropped)"};
+ const auto logs = LogTestController::getInstance().getLogs();
+ size_t dropped_count = 0;
+ for (auto match = std::sregex_iterator{logs.begin(), logs.end(),
dropped_event_pattern}; match != std::sregex_iterator{}; ++match) {
+ dropped_count += std::stoul((*match)[1].str());
+ }
+ return dropped_count;
+ }
+
+ void verifyResults(const ProcessorTriggerResult& results, const
std::vector<std::string>& expected_contents) const {
+ const auto& fetch_results =
results.at(processors::FetchOPCEvents::Success);
+ REQUIRE(fetch_results.size() == expected_contents.size());
+
+ for (size_t i = 0; i < expected_contents.size(); ++i) {
+ rapidjson::Document result_document;
+
result_document.Parse(controller_.plan->getContent(fetch_results[i]).c_str());
+ rapidjson::Document expected_document;
+ expected_document.Parse(expected_contents[i].c_str());
+
+ auto array = expected_document.GetArray();
+ for (rapidjson::SizeType j = 0; j < array.Size(); ++j) {
+ for (const auto& field : array[j].GetObject()) {
+ if (field.value == ".*") {
+ REQUIRE(result_document[j][field.name].IsString());
+ result_document[j][field.name].SetString(".*",
result_document.GetAllocator());
+ }
+ }
+ }
+
+ REQUIRE(result_document == expected_document);
+ }
+ }
+
+ protected:
+ minifi::test::SingleProcessorTestController controller_;
+ core::Processor* processor_;
+ OpcUaTestServer server_{4843};
+};
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching events of a
non-existent node", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "non-existent");
+
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ controller_.trigger();
+ return LogTestController::getInstance().getLogs().find("Failed to
subscribe to the events of node 'non-existent': BadNodeIdUnknown") !=
std::string::npos;
+ }, 100ms));
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching events of an
existing node but in the wrong namespace", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::NameSpaceIndex.name,
"7979"));
+
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ controller_.trigger();
+ return LogTestController::getInstance().getLogs().find("Failed to
subscribe to the events of node 'EventSource': BadNodeIdUnknown") !=
std::string::npos;
+ }, 100ms));
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test non-existent record set
writer", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+ REQUIRE(controller_.plan->setProperty(processor_,
processors::FetchOPCEvents::RecordSetWriter.name, "InvalidRecordSetWriter"));
+
+ REQUIRE_THROWS_WITH(controller_.trigger(), "Process Schedule Operation:
Controller service 'InvalidRecordSetWriter' not found");
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching a single event
of a node", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+ waitForSubscription();
+
+ server_.triggerEvent("test event", 500);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ const auto& flow_files = result.at(processors::FetchOPCEvents::Success);
+ REQUIRE(flow_files.size() == 1);
+ verifyResults(result, {R"([{"EventId":".*","Message":"test
event","Severity":"500","SourceName":"EventSource","EventType":"i=2041","Time":".*"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Events arriving between
triggers are all forwarded", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+ waitForSubscription();
+
+ constexpr size_t event_count = 5;
+ for (size_t i = 0; i < event_count; ++i) {
+ server_.triggerEvent(fmt::format("event {}", i), 500);
+ }
+
+ std::set<std::string> messages;
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ const auto triggered = controller_.trigger();
+ for (const auto& flow_file :
triggered.at(processors::FetchOPCEvents::Success)) {
+ rapidjson::Document document;
+ document.Parse(controller_.plan->getContent(flow_file).c_str());
+ for (const auto& event : document.GetArray()) {
+ messages.insert(event.GetObject()["Message"].GetString());
+ }
+ }
+ return messages.size() == event_count;
+ }, 100ms));
+
+ CHECK(messages == std::set<std::string>{"event 0", "event 1", "event 2",
"event 3", "event 4"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Events over the queue size
limit are dropped and reported", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::MaxQueueSize.name,
"2"));
+ waitForSubscription();
+
+ constexpr size_t event_count = 5;
+ for (size_t i = 0; i < event_count; ++i) {
+ server_.triggerEvent(fmt::format("event {}", i), 500);
+ }
+
+ // Each trigger both reports the events dropped since the last one and
drains the queue, so the two counts together must
+ // account for every event the server raised.
+ std::vector<std::string> delivered_messages;
+ size_t dropped_count = 0;
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ const auto triggered = controller_.trigger();
+ for (const auto& flow_file :
triggered.at(processors::FetchOPCEvents::Success)) {
+ rapidjson::Document document;
+ document.Parse(controller_.plan->getContent(flow_file).c_str());
+ for (const auto& event : document.GetArray()) {
+
delivered_messages.emplace_back(event.GetObject()["Message"].GetString());
+ }
+ }
+ dropped_count = countDroppedEvents();
+ return delivered_messages.size() + dropped_count == event_count;
+ }, 100ms));
+
+ CHECK(dropped_count > 0);
+ // The oldest events are the ones dropped, so the events left are the newest
ones and they keep the order they were raised in.
+ CHECK(std::ranges::is_sorted(delivered_messages));
+ CHECK(delivered_messages.back() == fmt::format("event {}", event_count - 1));
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching multiple events
with a batch size limit", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+ REQUIRE(processor_->setProperty(processors::FetchOPCEvents::BatchSize.name,
"2"));
+ waitForSubscription();
+
+ server_.triggerEvent("test event 1", 500);
+ server_.triggerEvent("test event 2", 300);
+ server_.triggerEvent("test event 3", 200);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 2}},
result, 10s));
+
+ const auto& flow_files = result.at(processors::FetchOPCEvents::Success);
+ REQUIRE(flow_files.size() == 2);
+ verifyResults(result, {R"([{"EventId":".*","Message":"test event
1","Severity":"500","SourceName":"EventSource","EventType":"i=2041","Time":".*"},)"
+ R"({"EventId":".*","Message":"test event
2","Severity":"300","SourceName":"EventSource","EventType":"i=2041","Time":".*"}])",
+ R"([{"EventId":".*","Message":"test event
3","Severity":"200","SourceName":"EventSource","EventType":"i=2041","Time":".*"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching events with
minimum severity limit", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::MinimumSeverity.name,
"300"));
+ waitForSubscription();
+
+ server_.triggerEvent("test event 1", 500);
+ server_.triggerEvent("test event 2", 300);
+ server_.triggerEvent("test event 3", 200);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ const auto& flow_files = result.at(processors::FetchOPCEvents::Success);
+ REQUIRE(flow_files.size() == 1);
+ verifyResults(result, {R"([{"EventId":".*","Message":"test event
1","Severity":"500","SourceName":"EventSource","EventType":"i=2041","Time":".*"},)"
+ R"({"EventId":".*","Message":"test event
2","Severity":"300","SourceName":"EventSource","EventType":"i=2041","Time":".*"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Only the selected fields are
requested and they name the record fields", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
"Message, /Severity"));
+ waitForSubscription();
+
+ server_.triggerEvent("test event", 500);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result, {R"([{"Message":"test event","Severity":"500"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Only the events of the
selected event type are reported", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+ // i=2052 is AuditEventType, a subtype of BaseEventType
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::EventTypeNodeId.name,
"i=2052"));
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
"Message,EventType"));
+ waitForSubscription();
+
+ server_.triggerEvent("base event", 500);
+ server_.triggerEvent("audit event", 500, UA_NS0ID_AUDITEVENTTYPE);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result, {R"([{"Message":"audit
event","EventType":"i=2052"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "The event filter expression
overrides the other filter properties", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
"EventId,SourceName,Time"));
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::EventTypeNodeId.name,
"i=2052"));
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::MinimumSeverity.name,
"900"));
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::EventFilterExpression.name,
"SELECT /Message, /Severity WHERE /Severity >= 400"));
+ waitForSubscription();
+
+ server_.triggerEvent("too quiet", 300);
+ server_.triggerEvent("loud enough", 500);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result, {R"([{"Message":"loud enough","Severity":"500"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "An unparsable event filter
expression is rejected", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::EventFilterExpression.name,
"PICK /Message WHENEVER /Severity"));
+
+ REQUIRE_THROWS_WITH(controller_.trigger(),
+ "Process Schedule Operation: Failed to parse the event filter 'PICK
/Message WHENEVER /Severity': BadInternalError");
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Selecting no fields at all is
rejected", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
" , "));
+
+ REQUIRE_THROWS_WITH(controller_.trigger(),
+ "Process Schedule Operation: At least one field must be set in 'Select
fields', otherwise the events would carry no data");
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "A select field can be a nested
path or a namespace qualified browse name", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
"Message,Tool/Diameter,1:Colour"));
+ waitForSubscription();
+
+ server_.triggerEventWithFields("nested event", 500, {{"/Tool/Diameter",
"42mm"}, {"/1:Colour", "red"}});
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result, {R"([{"Message":"nested
event","Tool/Diameter":"42mm","1:Colour":"red"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "A select field can be prefixed
with the node ID of an event type", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
+ // i=2052 is AuditEventType and ActionTimeStamp is one of its fields, so the
server accepts this clause.
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
"Message,i=2052/ActionTimeStamp"));
+ waitForSubscription();
+
+ server_.triggerEventWithFields("prefixed event", 500,
{{"i=2052/ActionTimeStamp", "2026-09-24T10:00:00Z"}});
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result, {R"([{"Message":"prefixed
event","i=2052/ActionTimeStamp":"2026-09-24T10:00:00Z"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "The event subscription is
replaced after the connection to the server is lost", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+ waitForSubscription();
+
+ server_.stop();
+ server_.start();
+ REQUIRE(utils::verifyLogLinePresenceInPollTime(30s, "Deleting the dead OPC
UA event subscription 1 before resubscribing"));
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(utils::verifyEventHappenedInPollTime(30s, [&]() {
+ server_.triggerEvent("event after the restart", 500);
+ result = controller_.trigger();
+ return !result.at(processors::FetchOPCEvents::Success).empty();
+ }, 200ms));
+
CHECK(controller_.plan->getContent(result.at(processors::FetchOPCEvents::Success)[0]).find("event
after the restart") != std::string::npos);
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching a single event
of a node addressed by its path", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("Path", "EventSource");
+ waitForSubscription();
+
+ server_.triggerEvent("path addressed event", 500);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result, {R"([{"EventId":".*","Message":"path addressed
event","Severity":"500","SourceName":"EventSource","EventType":"i=2041","Time":".*"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "A path that cannot be resolved
to a node is reported", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("Path", "Simulator/Default/NoSuchNode");
+
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ controller_.trigger();
+ return LogTestController::getInstance().getLogs().find(
+ "Failed to translate path 'Simulator/Default/NoSuchNode' to a node id:
BadNoDataAvailable") != std::string::npos;
+ }, 100ms));
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "A path that resolves to
multiple nodes is reported", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("Path", "Simulator/Default/AmbiguousParent/Ambiguous");
+
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ controller_.trigger();
+ return LogTestController::getInstance().getLogs().find(
+ "Path 'Simulator/Default/AmbiguousParent/Ambiguous' resolved to 2 node
ids; exactly one node is required") != std::string::npos;
+ }, 100ms));
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching a single event
of a node addressed by an int node ID", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("Int", "4200");
+ waitForSubscription();
+
+ server_.triggerEvent("int addressed event", 500, UA_NS0ID_BASEEVENTTYPE,
opc::OPCNodeIDType::Int);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result,
+ {R"([{"EventId":".*","Message":"int addressed
event","Severity":"500","SourceName":"IntEventSource","EventType":"i=2041","Time":".*"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "Test fetching a single event
of a node addressed by a GUID node ID", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("Guid", "aabbccdd-eeff-0a1b-2c3d-4e5f6a7b8c9d");
+ waitForSubscription();
+
+ server_.triggerEvent("GUID addressed event", 500, UA_NS0ID_BASEEVENTTYPE,
opc::OPCNodeIDType::Guid);
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result,
+ {R"([{"EventId":".*","Message":"GUID addressed
event","Severity":"500","SourceName":"GuidEventSource","EventType":"i=2041","Time":".*"}])"});
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "An event field that cannot be
converted to a string is skipped and reported", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
"Message,Tool/Range"));
+ waitForSubscription();
+
+ server_.triggerEventWithUnconvertibleField("event with a range field", 500,
"/Tool/Range");
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(controller_.triggerUntil({{processors::FetchOPCEvents::Success, 1}},
result, 10s));
+
+ verifyResults(result, {R"([{"Message":"event with a range field"}])"});
+ CHECK(LogTestController::getInstance().getLogs().find("Failed to convert
event field 'Tool/Range' to string, skipping field") != std::string::npos);
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "The event subscription is
recreated after the processor is stopped and started again",
"[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+ waitForSubscription();
+
+ // Unschedules the processor, which stops the event thread and drops the
client, then makes the next trigger schedule it again.
+ controller_.plan->reset(true);
+ LogTestController::getInstance().clear();
+ waitForSubscription();
+
+ minifi::test::ProcessorTriggerResult result;
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ server_.triggerEvent("event after the restart", 500);
+ result = controller_.trigger();
+ return !result.at(processors::FetchOPCEvents::Success).empty();
+ }, 200ms));
+
CHECK(controller_.plan->getContent(result.at(processors::FetchOPCEvents::Success)[0]).find("event
after the restart") != std::string::npos);
+}
+
+TEST_CASE_METHOD(FetchOPCEventsTestController, "A select field of an event
type unknown to the server is rejected", "[fetchopcevents]") {
+ server_.start();
+ setupProcessor("String", "EventSource");
+
REQUIRE(processor_->setProperty(processors::FetchOPCEvents::SelectFields.name,
"Message,ns=1;s=NoSuchEventType/Diameter"));
+
+ REQUIRE(utils::verifyEventHappenedInPollTime(10s, [&]() {
+ controller_.trigger();
+ return LogTestController::getInstance().getLogs().find("Failed to
subscribe to the events of node 'EventSource': BadEventFilterInvalid") !=
+ std::string::npos;
+ }, 100ms));
+}
+
+} // namespace org::apache::nifi::minifi::test
diff --git a/extensions/opc/tests/OpcUaTestServer.h
b/extensions/opc/tests/OpcUaTestServer.h
index fb607fe5c..0463cb8ba 100644
--- a/extensions/opc/tests/OpcUaTestServer.h
+++ b/extensions/opc/tests/OpcUaTestServer.h
@@ -108,6 +108,10 @@ class OpcUaTestServer {
addObject("Ambiguous", ambiguous_parent_node);
addObject("Ambiguous", ambiguous_parent_node);
+ addEventSource("EventSource", opc::OPCNodeIDType::String, "EventSource");
+ addEventSource("IntEventSource", opc::OPCNodeIDType::Int, "4200");
+ addEventSource("GuidEventSource", opc::OPCNodeIDType::Guid,
"aabbccdd-eeff-0a1b-2c3d-4e5f6a7b8c9d");
+
setHistory("INT1",
{HistoryModificationRecord{.value = 1,
.username = "test_user",
@@ -204,6 +208,32 @@ class OpcUaTestServer {
updateNodeValue(full_path, new_value);
}
+ void triggerEvent(const std::string& message, UA_UInt16 severity, UA_UInt32
event_type = UA_NS0ID_BASEEVENTTYPE,
+ opc::OPCNodeIDType source_id_type = opc::OPCNodeIDType::String) {
+ raiseEvent(event_source_nodes_.at(source_id_type), message, severity,
event_type, nullptr);
+ }
+
+ void triggerEventWithFields(const std::string& message, UA_UInt16 severity,
const std::vector<std::pair<std::string, std::string>>& fields) {
+ std::vector<UA_KeyValuePair> pairs(fields.size());
+ std::vector<UA_String> values(fields.size());
+ for (size_t i = 0; i < fields.size(); ++i) {
+ pairs[i].key = UA_QUALIFIEDNAME(0,
const_cast<char*>(fields[i].first.c_str()));
+ values[i] = UA_STRING(const_cast<char*>(fields[i].second.c_str()));
+ UA_Variant_setScalar(&pairs[i].value, &values[i],
&UA_TYPES[UA_TYPES_STRING]);
+ }
+ UA_KeyValueMap field_map{pairs.size(), pairs.data()};
+ raiseEvent(event_source_nodes_.at(opc::OPCNodeIDType::String), message,
severity, UA_NS0ID_BASEEVENTTYPE, &field_map);
+ }
+
+ void triggerEventWithUnconvertibleField(const std::string& message,
UA_UInt16 severity, const std::string& field_name) {
+ UA_Range range{.low = 0.0, .high = 100.0};
+ UA_KeyValuePair pair;
+ pair.key = UA_QUALIFIEDNAME(0, const_cast<char*>(field_name.c_str()));
+ UA_Variant_setScalar(&pair.value, &range, &UA_TYPES[UA_TYPES_RANGE]);
+ UA_KeyValueMap field_map{1, &pair};
+ raiseEvent(event_source_nodes_.at(opc::OPCNodeIDType::String), message,
severity, UA_NS0ID_BASEEVENTTYPE, &field_map);
+ }
+
void updateNodeValue(const std::string& full_path, int32_t new_value) {
std::lock_guard<std::mutex> lock(mutex_);
@@ -219,6 +249,14 @@ class OpcUaTestServer {
}
private:
+ void raiseEvent(const UA_NodeId& source_node, const std::string& message,
UA_UInt16 severity, UA_UInt32 event_type, const UA_KeyValueMap* fields) {
+ UA_LocalizedText message_text =
UA_LOCALIZEDTEXT(const_cast<char*>("en-US"),
const_cast<char*>(message.c_str()));
+ auto status = UA_Server_createEvent(server_, source_node,
UA_NODEID_NUMERIC(0, event_type), severity, message_text, fields, nullptr,
nullptr);
+ if (status != UA_STATUSCODE_GOOD) {
+ throw std::runtime_error("Failed to create event");
+ }
+ }
+
static std::string nodeIdToString(const UA_NodeId& id) {
if (id.identifierType == UA_NODEIDTYPE_STRING) {
return std::string(reinterpret_cast<const
char*>(id.identifier.string.data), id.identifier.string.length);
@@ -387,6 +425,40 @@ class OpcUaTestServer {
return object_id;
}
+ void addEventSource(const char* name, opc::OPCNodeIDType id_type, const
std::string& node_id) {
+ auto requested_node_id = opc::buildNodeId(id_type, ns_index_, node_id);
+ if (!requested_node_id) {
+ throw std::runtime_error("Failed to build the node id of the event
source: " + requested_node_id.error());
+ }
+ event_source_nodes_.emplace(id_type,
+ opc::NodeId{addEventSourceObject(name, UA_NODEID_NUMERIC(0,
UA_NS0ID_OBJECTSFOLDER), *requested_node_id)});
+ }
+
+ UA_NodeId addEventSourceObject(const char* name, UA_NodeId parent, const
UA_NodeId& requested_node_id) {
+ UA_ObjectAttributes attr = UA_ObjectAttributes_default;
+ attr.displayName = UA_LOCALIZEDTEXT_ALLOC("en-US", name);
+ attr.eventNotifier = UA_EVENTNOTIFIER_SUBSCRIBE_TO_EVENT;
+
+ UA_NodeId object_id;
+ auto status = UA_Server_addObjectNode(server_,
+ requested_node_id,
+ parent,
+ UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
+ UA_QUALIFIEDNAME(ns_index_, const_cast<char*>(name)),
+ UA_NODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE),
+ attr,
+ nullptr,
+ &object_id);
+
+ UA_LocalizedText_clear(&attr.displayName);
+
+ if (status != UA_STATUSCODE_GOOD) {
+ throw std::runtime_error("Failed to add event source object node");
+ }
+
+ return object_id;
+ }
+
UA_StatusCode addNode(UA_NodeId parent_node_id, UA_NodeId& target_node_id,
opc::OPCNodeIDType type, const std::string& browse_name,
const UA_VariableAttributes& attr, UA_UInt32 reference_type =
UA_NS0ID_HASCOMPONENT) {
UA_QualifiedName qname = UA_QUALIFIEDNAME(ns_index_,
const_cast<char*>(browse_name.c_str()));
@@ -486,6 +558,7 @@ class OpcUaTestServer {
mutable std::mutex server_logs_mutex_;
std::vector<std::string> server_logs_;
std::unordered_map<std::string, opc::NodeId> node_ids_;
+ std::unordered_map<opc::OPCNodeIDType, opc::NodeId> event_source_nodes_;
std::mutex history_mutex_;
std::unordered_map<std::string, std::vector<HistoryModificationRecord>>
history_records_;
size_t history_page_size_ = 0;
diff --git a/extensions/opc/tests/PutOPCProcessorTests.cpp
b/extensions/opc/tests/PutOPCProcessorTests.cpp
index 336667782..ab18b47cc 100644
--- a/extensions/opc/tests/PutOPCProcessorTests.cpp
+++ b/extensions/opc/tests/PutOPCProcessorTests.cpp
@@ -27,7 +27,7 @@ struct NodeData {
};
void verifyCreatedNode(const NodeData& expected_node,
SingleProcessorTestController& controller) {
- auto client = minifi::opc::Client::createClient(controller.getLogger(), "",
{}, {}, {});
+ auto client = minifi::opc::Client::createClient(controller.getLogger(), "",
{}, {}, {}, {});
REQUIRE(client->connect("opc.tcp://127.0.0.1:4840/") == UA_STATUSCODE_GOOD);
std::vector<opc::NodeId> found_node_ids;
std::vector<UA_UInt32> reference_types;
@@ -78,7 +78,7 @@ void verifyCreatedNode(const NodeData& expected_node,
SingleProcessorTestControl
}
void verifyNodeValue(SingleProcessorTestController& controller, const
opc::NodeId& target, uint16_t namespace_index, const std::string& browse_name,
uint8_t expected_value) {
- auto client = minifi::opc::Client::createClient(controller.getLogger(), "",
{}, {}, {});
+ auto client = minifi::opc::Client::createClient(controller.getLogger(), "",
{}, {}, {}, {});
REQUIRE(client->connect("opc.tcp://127.0.0.1:4840/") == UA_STATUSCODE_GOOD);
UA_ReferenceDescription ref_desc;