blob: 07f96605b3f6f52a336293fd89a1907477da36dc [file]
// 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 "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>
#include <functional>
#include <array>
#include "utils/StringUtils.h"
#include "minifi-cpp/core/logging/Logger.h"
#include "minifi-cpp/Exception.h"
#include "minifi-cpp/utils/gsl.h"
#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);
namespace org::apache::nifi::minifi::opc {
/*
* The following functions are only used internally in OPC lib, not to be exported
*/
namespace {
void add_value_to_variant(UA_Variant *variant, std::string &value) {
UA_String ua_value = UA_STRING(value.data());
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_STRING]);
}
void add_value_to_variant(UA_Variant *variant, const char *value) {
std::string strvalue(value);
add_value_to_variant(variant, strvalue);
}
void add_value_to_variant(UA_Variant *variant, int64_t value) {
UA_Int64 ua_value = value;
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_INT64]);
}
void add_value_to_variant(UA_Variant *variant, uint64_t value) {
UA_UInt64 ua_value = value;
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_UINT64]);
}
void add_value_to_variant(UA_Variant *variant, int32_t value) {
UA_Int32 ua_value = value;
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_INT32]);
}
void add_value_to_variant(UA_Variant *variant, uint32_t value) {
UA_UInt32 ua_value = value;
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_UINT32]);
}
void add_value_to_variant(UA_Variant *variant, bool value) {
UA_Boolean ua_value = value;
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_BOOLEAN]);
}
void add_value_to_variant(UA_Variant *variant, float value) {
UA_Float ua_value = value;
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_FLOAT]);
}
void add_value_to_variant(UA_Variant *variant, double value) {
UA_Double ua_value = value;
UA_Variant_setScalarCopy(variant, &ua_value, &UA_TYPES[UA_TYPES_DOUBLE]);
}
template<typename T>
std::string printToString(UA_StatusCode (*print_func)(const T*, UA_String*), const T& data, std::string_view type_name) {
UA_String printed = UA_STRING_NULL;
if (print_func(&data, &printed) != UA_STATUSCODE_GOOD) {
throw OPCException(GENERAL_EXCEPTION, utils::string::join_pack("Failed to convert a ", type_name, " to string"));
}
const auto guard = gsl::finally([&printed]() { UA_String_clear(&printed); });
return {reinterpret_cast<const char*>(printed.data), printed.length};
}
core::logging::LOG_LEVEL MapOPCLogLevel(UA_LogLevel ualvl) {
switch (ualvl) {
case UA_LOGLEVEL_TRACE:
return core::logging::trace;
case UA_LOGLEVEL_DEBUG:
return core::logging::debug;
case UA_LOGLEVEL_INFO:
return core::logging::info;
case UA_LOGLEVEL_WARNING:
return core::logging::warn;
case UA_LOGLEVEL_ERROR:
return core::logging::err;
case UA_LOGLEVEL_FATAL:
default:
return core::logging::critical;
}
}
} // namespace
/*
* End of internal functions
*/
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, 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).
UA_ClientConfig config{};
config.logging = &minifi_ua_logger_;
if (!use_encryption_) {
if (UA_StatusCode sc = UA_ClientConfig_setDefault(&config); sc != UA_STATUSCODE_GOOD) {
UA_ClientConfig_clear(&config);
throw OPCException(GENERAL_EXCEPTION, std::string("Failed to configure the OPC UA client: ") + UA_StatusCode_name(sc));
}
} else {
config.securityMode = UA_MESSAGESECURITYMODE_SIGNANDENCRYPT;
// Certificate
UA_ByteString cert_byte_string = UA_STRING_NULL;
cert_byte_string.length = cert_buffer.size();
cert_byte_string.data = reinterpret_cast<UA_Byte*>(UA_malloc(cert_byte_string.length * sizeof(UA_Byte))); // NOLINT(cppcoreguidelines-owning-memory)
memcpy(cert_byte_string.data, cert_buffer.data(), cert_byte_string.length);
// Key
UA_ByteString key_byte_string = UA_STRING_NULL;
key_byte_string.length = key_buffer.size();
key_byte_string.data = reinterpret_cast<UA_Byte*>(UA_malloc(key_byte_string.length * sizeof(UA_Byte))); // NOLINT(cppcoreguidelines-owning-memory)
memcpy(key_byte_string.data, key_buffer.data(), key_byte_string.length);
// Trusted certificates
std::vector<UA_ByteString> trust_list;
trust_list.resize(trust_buffers.size());
for (size_t i = 0; i < trust_buffers.size(); i++) {
trust_list[i] = UA_STRING_NULL;
trust_list[i].length = trust_buffers[i].size();
trust_list[i].data = reinterpret_cast<UA_Byte*>(UA_malloc(trust_list[i].length * sizeof(UA_Byte))); // NOLINT(cppcoreguidelines-owning-memory)
memcpy(trust_list[i].data, trust_buffers[i].data(), trust_list[i].length);
}
UA_StatusCode sc = UA_ClientConfig_setDefaultEncryption(&config, cert_byte_string, key_byte_string,
trust_list.data(), trust_buffers.size(),
nullptr, 0);
UA_ByteString_clear(&cert_byte_string);
UA_ByteString_clear(&key_byte_string);
for (size_t i = 0; i < trust_buffers.size(); i++) {
UA_ByteString_clear(&trust_list[i]);
}
if (sc != UA_STATUSCODE_GOOD) {
logger->log_error("Configuring the client for encryption failed: {}", UA_StatusCode_name(sc));
UA_ClientConfig_clear(&config);
throw OPCException(GENERAL_EXCEPTION, std::string("Failed to create the OPC UA client with the provided encryption settings: ") + UA_StatusCode_name(sc));
}
}
config.allowNonePolicyPassword = true;
config.subscriptionInactivityCallback = &Client::subscriptionInactivityCallback;
if (!application_uri.empty()) {
UA_String_clear(&config.clientDescription.applicationUri);
config.clientDescription.applicationUri = UA_STRING_ALLOC(application_uri.c_str());
}
client_ = UA_Client_newWithConfig(&config);
if (client_ == nullptr) {
UA_ClientConfig_clear(&config);
throw OPCException(GENERAL_EXCEPTION, "Failed to allocate the OPC UA client");
}
logger_ = logger;
}
Client::~Client() {
if (client_ == nullptr) {
return;
}
UA_SecureChannelState channel_state = UA_SECURECHANNELSTATE_CLOSED;
UA_Client_getState(client_, &channel_state, nullptr, nullptr);
if (channel_state != UA_SECURECHANNELSTATE_CLOSED) {
auto sc = UA_Client_disconnect(client_);
if (sc != UA_STATUSCODE_GOOD) {
logger_->log_warn("Failed to disconnect OPC client: {}", UA_StatusCode_name(sc));
}
}
UA_Client_delete(client_);
}
bool Client::isConnected() {
if (!client_) {
return false;
}
UA_SessionState session_state = UA_SESSIONSTATE_CLOSED;
UA_Client_getState(client_, nullptr, &session_state, nullptr);
return session_state == UA_SESSIONSTATE_ACTIVATED;
}
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 {
if (!use_encryption_) {
logger_->log_warn("Username/password authentication is used without encryption, which is not secure. Please consider configuring encryption for better security.");
}
return UA_Client_connectUsername(client_, url.c_str(), username.c_str(), password.c_str());
}
}
NodeData Client::getNodeData(const UA_ReferenceDescription *ref, const std::string& base_path) {
if (ref->nodeClass != UA_NODECLASS_VARIABLE) {
throw OPCException(GENERAL_EXCEPTION, "Only variable nodes are supported!");
}
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 {
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) {
UA_ReferenceDescription *ref = UA_ReferenceDescription_new();
UA_ReferenceDescription_init(ref);
UA_NodeId_copy(&node_id, &ref->nodeId.nodeId);
auto sc = UA_Client_readNodeClassAttribute(client_, node_id, &ref->nodeClass);
if (sc == UA_STATUSCODE_GOOD) {
sc = UA_Client_readBrowseNameAttribute(client_, node_id, &ref->browseName);
}
if (sc == UA_STATUSCODE_GOOD) {
UA_Client_readDisplayNameAttribute(client_, node_id, &ref->displayName);
}
return ref;
}
void Client::traverse(UA_NodeId node_id, const std::function<NodeFoundCallBackFunc>& cb, const std::string& base_path, uint64_t max_depth, bool fetch_root) {
if (fetch_root) {
UA_ReferenceDescription *rootRef = getNodeReference(node_id);
if ((rootRef->nodeClass == UA_NODECLASS_VARIABLE || rootRef->nodeClass == UA_NODECLASS_OBJECT) && rootRef->browseName.name.length > 0) {
cb(rootRef, base_path);
}
UA_ReferenceDescription_delete(rootRef);
}
if (max_depth != 0) {
max_depth--;
if (max_depth == 0) {
return;
}
}
UA_BrowseRequest browse_request;
UA_BrowseRequest_init(&browse_request);
browse_request.requestedMaxReferencesPerNode = 0;
browse_request.nodesToBrowse = UA_BrowseDescription_new();
browse_request.nodesToBrowseSize = 1;
UA_NodeId_copy(&node_id, &browse_request.nodesToBrowse[0].nodeId);
browse_request.nodesToBrowse[0].resultMask = UA_BROWSERESULTMASK_ALL;
UA_BrowseResponse browse_response = UA_Client_Service_browse(client_, browse_request);
const auto guard = gsl::finally([&browse_response]() {
UA_BrowseResponse_clear(&browse_response);
});
UA_BrowseRequest_clear(&browse_request);
for (size_t i = 0; i < browse_response.resultsSize; ++i) {
for (size_t j = 0; j < browse_response.results[i].referencesSize; ++j) {
UA_ReferenceDescription *ref = &(browse_response.results[i].references[j]);
if (cb(ref, base_path)) {
if (ref->nodeClass == UA_NODECLASS_VARIABLE || ref->nodeClass == UA_NODECLASS_OBJECT) {
std::string new_base_path = base_path;
new_base_path.append("/").append(reinterpret_cast<char *>(ref->browseName.name.data), ref->browseName.name.length);
traverse(ref->nodeId.nodeId, cb, new_base_path, max_depth, false);
}
} else {
return;
}
}
}
}
bool Client::exists(UA_NodeId node_id) {
bool retval = false;
auto callback = [&retval](const UA_ReferenceDescription* /*ref*/, const std::string& /*pat*/) -> bool {
retval = true;
return false; // If any node is found, the given node exists, so traverse can be stopped
};
traverse(node_id, callback, "", 1);
return retval;
}
UA_StatusCode Client::translateBrowsePathsToNodeIdsRequest(const std::string& path, std::vector<NodeId>& found_node_ids, UA_UInt16 namespace_index,
const std::vector<UA_UInt32>& path_reference_types, const std::shared_ptr<core::logging::Logger>& logger) {
logger->log_trace("Trying to find node ids for {}", path.c_str());
auto tokens = utils::string::splitAndTrimRemovingEmpty(path, "/");
gsl_Expects(!tokens.empty());
UA_BrowsePath browse_path;
UA_BrowsePath_init(&browse_path);
browse_path.startingNode = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
browse_path.relativePath.elements = reinterpret_cast<UA_RelativePathElement*>(UA_Array_new(tokens.size(), &UA_TYPES[UA_TYPES_RELATIVEPATHELEMENT]));
browse_path.relativePath.elementsSize = tokens.size();
std::vector<UA_UInt32> ids;
// OPC UA Part 5 8.2.4: only Organizes references are used to relate Objects to the Objects folder
ids.push_back(UA_NS0ID_ORGANIZES);
for (size_t i = 0; i < tokens.size() - 1; ++i) {
if (!path_reference_types.empty()) {
ids.push_back(path_reference_types[i]);
} else {
ids.push_back(UA_NS0ID_ORGANIZES);
}
}
for (size_t i = 0; i < tokens.size(); ++i) {
UA_RelativePathElement *elem = &browse_path.relativePath.elements[i];
elem->referenceTypeId = UA_NODEID_NUMERIC(0, ids[i]);
elem->includeSubtypes = true;
elem->targetName = UA_QUALIFIEDNAME_ALLOC(namespace_index, tokens[i].c_str());
}
UA_TranslateBrowsePathsToNodeIdsRequest request;
UA_TranslateBrowsePathsToNodeIdsRequest_init(&request);
request.browsePaths = &browse_path;
request.browsePathsSize = 1;
UA_TranslateBrowsePathsToNodeIdsResponse response = UA_Client_Service_translateBrowsePathsToNodeIds(client_, request);
const auto guard = gsl::finally([&browse_path, &tokens, &response]() {
for (size_t i = 0; i < tokens.size(); ++i) {
UA_RelativePathElement *elem = &browse_path.relativePath.elements[i];
UA_QualifiedName_clear(&elem->targetName);
}
UA_BrowsePath_clear(&browse_path);
UA_TranslateBrowsePathsToNodeIdsResponse_clear(&response);
});
if (response.resultsSize < 1 || response.results[0].statusCode != UA_STATUSCODE_GOOD) {
logger->log_warn("No node id in response for {}", path.c_str());
return UA_STATUSCODE_BADNODATAAVAILABLE;
}
bool found_data = false;
for (size_t i = 0; i < response.resultsSize; ++i) {
UA_BrowsePathResult res = response.results[i];
for (size_t j = 0; j < res.targetsSize; ++j) {
found_data = true;
found_node_ids.push_back(NodeId::copyOf(res.targets[j].targetId.nodeId));
}
}
if (found_data) {
logger->log_debug("Found {} nodes for path {}", found_node_ids.size(), path.c_str());
return UA_STATUSCODE_GOOD;
} else {
logger->log_warn("No node id found for path {}", path.c_str());
return UA_STATUSCODE_BADNODATAAVAILABLE;
}
}
template<typename T>
UA_StatusCode Client::add_node(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name, T value, UA_NodeId *received_node_id) {
UA_VariableAttributes attr = UA_VariableAttributes_default;
attr.accessLevel |= UA_ACCESSLEVELMASK_READ | UA_ACCESSLEVELMASK_WRITE;
attr.userAccessLevel |= UA_ACCESSLEVELMASK_READ | UA_ACCESSLEVELMASK_WRITE;
add_value_to_variant(&attr.value, value);
char local[6] = "en-US"; // NOLINT(cppcoreguidelines-avoid-c-arrays)
attr.displayName = UA_LOCALIZEDTEXT(local, const_cast<char*>(browse_name.data()));
UA_StatusCode sc = UA_Client_addVariableNode(client_,
target_node_id,
parent_node_id,
UA_NODEID_NUMERIC(0, ref_type_id),
UA_QUALIFIEDNAME(target_node_id.namespaceIndex, const_cast<char*>(browse_name.data())),
UA_NODEID_NULL,
attr, received_node_id);
UA_Variant_clear(&attr.value);
return sc;
}
template<typename T>
UA_StatusCode Client::update_node(const UA_NodeId node_id, T value) {
UA_Variant *variant = UA_Variant_new();
add_value_to_variant(variant, value);
UA_StatusCode sc = UA_Client_writeValueAttribute(client_, node_id, variant);
UA_Variant_delete(variant);
return sc;
}
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, std::optional<size_t> max_event_queue_size) {
try {
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());
}
return nullptr;
}
template UA_StatusCode Client::update_node<int64_t>(const UA_NodeId node_id, int64_t value);
template UA_StatusCode Client::update_node<uint64_t>(const UA_NodeId node_id, uint64_t value);
template UA_StatusCode Client::update_node<int32_t>(const UA_NodeId node_id, int32_t value);
template UA_StatusCode Client::update_node<uint32_t>(const UA_NodeId node_id, uint32_t value);
template UA_StatusCode Client::update_node<float>(const UA_NodeId node_id, float value);
template UA_StatusCode Client::update_node<double>(const UA_NodeId node_id, double value);
template UA_StatusCode Client::update_node<bool>(const UA_NodeId node_id, bool value);
template UA_StatusCode Client::update_node<const char *>(const UA_NodeId node_id, const char * value);
template UA_StatusCode Client::update_node<std::string>(const UA_NodeId node_id, std::string value);
template UA_StatusCode Client::add_node<int64_t>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
int64_t value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<uint64_t>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
uint64_t value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<int32_t>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
int32_t value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<uint32_t>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
uint32_t value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<float>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
float value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<double>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
double value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<bool>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
bool value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<const char *>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
const char * value, UA_NodeId *received_node_id);
template UA_StatusCode Client::add_node<std::string>(const UA_NodeId parent_node_id, const UA_NodeId target_node_id, const UA_UInt32 ref_type_id, std::string_view browse_name,
std::string value, UA_NodeId *received_node_id);
std::string variantToString(const UA_Variant& variant, BinaryEncoding binary_encoding) {
if (variant.type == nullptr || variant.data == nullptr) {
throw OPCException(GENERAL_EXCEPTION, "Cannot convert an empty variant to string");
}
if (!UA_Variant_isScalar(&variant)) {
throw OPCException(GENERAL_EXCEPTION, "Cannot convert an array variant to string");
}
switch (variant.type->typeKind) {
case UA_DATATYPEKIND_STRING:
case UA_DATATYPEKIND_XMLELEMENT: {
const auto* value = static_cast<const UA_String *>(variant.data);
return {reinterpret_cast<const char *>(value->data), value->length};
}
case UA_DATATYPEKIND_LOCALIZEDTEXT: {
const auto* value = static_cast<const UA_LocalizedText *>(variant.data);
return {reinterpret_cast<const char *>(value->text.data), value->text.length};
}
case UA_DATATYPEKIND_BYTESTRING: {
const auto* value = static_cast<const UA_ByteString *>(variant.data);
if (value->data == nullptr || value->length == 0) {
return {};
}
const std::string_view bytes{reinterpret_cast<const char *>(value->data), value->length};
return binary_encoding == BinaryEncoding::Raw ? std::string{bytes} : utils::string::to_base64(bytes);
}
case UA_DATATYPEKIND_BOOLEAN:
return *static_cast<const UA_Boolean *>(variant.data) ? "True" : "False";
case UA_DATATYPEKIND_SBYTE:
return std::to_string(*static_cast<const UA_SByte *>(variant.data));
case UA_DATATYPEKIND_BYTE:
return std::to_string(*static_cast<const UA_Byte *>(variant.data));
case UA_DATATYPEKIND_INT16:
return std::to_string(*static_cast<const UA_Int16 *>(variant.data));
case UA_DATATYPEKIND_UINT16:
return std::to_string(*static_cast<const UA_UInt16 *>(variant.data));
case UA_DATATYPEKIND_INT32:
return std::to_string(*static_cast<const UA_Int32 *>(variant.data));
case UA_DATATYPEKIND_UINT32:
return std::to_string(*static_cast<const UA_UInt32 *>(variant.data));
case UA_DATATYPEKIND_INT64:
return std::to_string(*static_cast<const UA_Int64 *>(variant.data));
case UA_DATATYPEKIND_UINT64:
return std::to_string(*static_cast<const UA_UInt64 *>(variant.data));
case UA_DATATYPEKIND_FLOAT:
if (sizeof(float) == 4 && std::numeric_limits<float>::is_iec559) {
return std::to_string(*static_cast<const UA_Float *>(variant.data));
}
throw OPCException(GENERAL_EXCEPTION, "Float is non-standard on this system, OPC data cannot be extracted!");
case UA_DATATYPEKIND_DOUBLE:
if (sizeof(double) == 8 && std::numeric_limits<double>::is_iec559) {
return std::to_string(*static_cast<const UA_Double *>(variant.data));
}
throw OPCException(GENERAL_EXCEPTION, "Double is non-standard on this system, OPC data cannot be extracted!");
case UA_DATATYPEKIND_DATETIME:
return opc::OPCDateTime2String(*static_cast<const UA_DateTime *>(variant.data));
case UA_DATATYPEKIND_NODEID:
return printToString(UA_NodeId_print, *static_cast<const UA_NodeId *>(variant.data), "node id");
case UA_DATATYPEKIND_EXPANDEDNODEID:
return printToString(UA_ExpandedNodeId_print, *static_cast<const UA_ExpandedNodeId *>(variant.data), "expanded node id");
case UA_DATATYPEKIND_GUID:
return printToString(UA_Guid_print, *static_cast<const UA_Guid *>(variant.data), "GUID");
case UA_DATATYPEKIND_QUALIFIEDNAME:
return printToString(UA_QualifiedName_print, *static_cast<const UA_QualifiedName *>(variant.data), "qualified name");
case UA_DATATYPEKIND_STATUSCODE:
return UA_StatusCode_name(*static_cast<const UA_StatusCode *>(variant.data));
default:
throw OPCException(GENERAL_EXCEPTION, "Data type is not supported: " + std::string(variant.type->typeName));
}
}
std::string nodeValue2String(const NodeData& nd) {
if (nd.var_ == nullptr) {
throw OPCException(GENERAL_EXCEPTION, "Node has no value to convert");
}
return variantToString(*nd.var_, BinaryEncoding::Raw);
}
std::string OPCDateTime2String(UA_DateTime raw_date) {
UA_DateTimeStruct dts = UA_DateTime_toStruct(raw_date);
std::array<char, 100> charBuf{};
int sz = snprintf(charBuf.data(), charBuf.size(), "%04hu-%02hu-%02huT%02hu:%02hu:%02hu.%03huZ", dts.year, dts.month, dts.day, dts.hour, dts.min, dts.sec, dts.milliSec);
return {charBuf.data(), gsl::narrow<std::size_t>(sz)};
}
void logFunc(void *context, UA_LogLevel level, UA_LogCategory /*category*/, const char *msg, va_list args) {
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) {
if (ref_type == "Organizes") {
return UA_NS0ID_ORGANIZES;
} else if (ref_type == "HasComponent") {
return UA_NS0ID_HASCOMPONENT;
} else if (ref_type == "HasProperty") {
return UA_NS0ID_HASPROPERTY;
} else if (ref_type == "HasSubtype") {
return UA_NS0ID_HASSUBTYPE;
}
return std::nullopt;
}
std::expected<std::vector<UA_UInt32>, std::string> parsePathReferenceTypes(const std::string& reference_types, const std::string& path) {
std::vector<UA_UInt32> result;
if (reference_types.empty()) {
return result;
}
auto reference_type_names = utils::string::splitAndTrimRemovingEmpty(reference_types, "/");
if (reference_type_names.size() + 1 != utils::string::splitAndTrimRemovingEmpty(path, "/").size()) {
return std::unexpected{"Path reference types must be provided for each node pair in the path!"};
}
for (const auto& reference_type : reference_type_names) {
if (auto ua_ref_type = mapOpcReferenceType(reference_type)) {
result.push_back(*ua_ref_type);
} else {
return std::unexpected{fmt::format("Unsupported path reference type: '{}'.", reference_type)};
}
}
return result;
}
UA_StatusCode Client::readHistory(HistoryReadTypeOption history_type, const UA_NodeId& node_id, const HistoryCallback callback,
void* callback_context, UA_DateTime start_time, UA_DateTime end_time) {
if (history_type == HistoryReadTypeOption::Audit) {
return UA_Client_HistoryRead_modified(client_, &node_id, callback, start_time, end_time, UA_STRING_NULL, false, 0, UA_TIMESTAMPSTORETURN_SOURCE, callback_context);
}
return UA_Client_HistoryRead_raw(client_, &node_id, callback, start_time, end_time, UA_STRING_NULL, false, 0, UA_TIMESTAMPSTORETURN_SOURCE, callback_context);
}
std::expected<opc::NodeId, std::string> buildNodeId(opc::OPCNodeIDType id_type, UA_UInt16 namespace_idx, const std::string& node_id) {
switch (id_type) {
case opc::OPCNodeIDType::String:
return opc::NodeId{UA_NODEID_STRING_ALLOC(namespace_idx, node_id.c_str())};
case opc::OPCNodeIDType::Int:
try {
return opc::NodeId{UA_NODEID_NUMERIC(namespace_idx, gsl::narrow<UA_UInt32>(std::stoul(node_id)))};
} catch(const std::exception&) {
auto error_msg = utils::string::join_pack(node_id, " cannot be used as an int type node ID");
return std::unexpected{error_msg};
}
case opc::OPCNodeIDType::Guid: {
UA_Guid guid;
if (UA_Guid_parse(&guid, UA_STRING(const_cast<char*>(node_id.c_str()))) != UA_STATUSCODE_GOOD) {
return std::unexpected{fmt::format("{} cannot be used as a GUID type node ID", node_id)};
}
return opc::NodeId{UA_NODEID_GUID(namespace_idx, guid)};
}
default:
return std::unexpected{fmt::format("Unsupported Node ID type: {}", magic_enum::enum_name(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