You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nifi.apache.org by sz...@apache.org on 2025/09/30 22:40:08 UTC
(nifi-minifi-cpp) branch main updated (92fb88dca -> 198c89078)
This is an automated email from the ASF dual-hosted git repository.
szaszm pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/nifi-minifi-cpp.git
from 92fb88dca MINIFICPP-2638 Fix package source and gitignore lists
new 4f296765b MINIFICPP-2558 Revamp site to site communication
new 1fd592fd0 MINIFICPP-2605 Generate MQTT client id in MQTT processors if not set in property
new 26409cfd5 MINIFICPP-2614 Add more authentication options to Azure processors
new 198c89078 MINIFICPP-2642 std::invocable should be used with std::invoke
The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
CONTROLLERS.md | 17 +-
PROCESSORS.md | 106 +--
README.md | 4 +
SITE_TO_SITE.md | 133 +++
core-framework/include/io/CRCStream.h | 2 +-
.../cluster/containers/NifiContainer.py | 2 +-
.../features/MiNiFi_integration_test_driver.py | 13 +
docker/test/integration/features/s2s.feature | 202 ++++-
docker/test/integration/features/steps/steps.py | 67 +-
docker/test/integration/minifi/core/Connectable.py | 3 +
docker/test/integration/minifi/core/InputPort.py | 3 +
.../minifi/core/{InputPort.py => OutputPort.py} | 7 +-
.../integration/minifi/core/RemoteProcessGroup.py | 3 +-
.../Minifi_flow_json_serializer.py | 99 ++-
.../Minifi_flow_yaml_serializer.py | 108 ++-
.../Nifi_flow_json_serializer.py | 26 +-
extensions/aws/processors/PutS3Object.h | 6 +-
.../AzureStorageCredentialsService.cpp | 13 +-
.../AzureStorageCredentialsService.h | 28 +-
.../processors/AzureBlobStorageProcessorBase.cpp | 13 +-
.../processors/AzureBlobStorageProcessorBase.h | 32 +-
.../azure/processors/FetchAzureBlobStorage.h | 2 +-
.../azure/processors/FetchAzureDataLakeStorage.h | 2 +-
.../azure/processors/PutAzureDataLakeStorage.cpp | 13 +-
.../azure/storage/AzureBlobStorageClient.cpp | 10 +-
.../azure/storage/AzureDataLakeStorageClient.cpp | 10 +-
.../azure/storage/AzureStorageCredentials.cpp | 51 +-
extensions/azure/storage/AzureStorageCredentials.h | 17 +-
.../azure/tests/DeleteAzureBlobStorageTests.cpp | 74 +-
.../tests/DeleteAzureDataLakeStorageTests.cpp | 32 +-
.../azure/tests/FetchAzureBlobStorageTests.cpp | 74 +-
.../azure/tests/FetchAzureDataLakeStorageTests.cpp | 32 +-
.../azure/tests/ListAzureBlobStorageTests.cpp | 64 +-
.../azure/tests/ListAzureDataLakeStorageTests.cpp | 42 +-
.../azure/tests/PutAzureBlobStorageTests.cpp | 74 +-
.../azure/tests/PutAzureDataLakeStorageTests.cpp | 32 +-
extensions/azure/utils/AzureEnums.h | 28 +
.../mqtt/processors/AbstractMQTTProcessor.cpp | 8 +-
extensions/mqtt/processors/AbstractMQTTProcessor.h | 5 +-
extensions/mqtt/processors/ConsumeMQTT.cpp | 10 -
extensions/mqtt/tests/ConsumeMQTTTests.cpp | 28 -
extensions/mqtt/tests/PublishMQTTTests.cpp | 8 -
extensions/procfs/ProcFsSerialization.h | 165 ++--
.../standard-processors/processors/InvokeHTTP.cpp | 12 +-
.../standard-processors/processors/InvokeHTTP.h | 2 +-
.../tests/unit/FlowJsonTests.cpp | 112 ++-
.../tests/unit/ProcessGroupTestUtils.h | 2 +-
.../tests/unit/ProcessorTests.cpp | 8 +-
.../tests/unit/YamlConfigurationTests.cpp | 86 +-
extensions/standard-processors/utils/JoltUtils.h | 4 +-
extensions/windows-event-log/wel/StringSplitter.h | 5 +-
...ocessorGroupPort.h => RemoteProcessGroupPort.h} | 199 ++---
libminifi/include/core/FlowConfiguration.h | 2 +-
libminifi/include/core/flow/FlowSchema.h | 5 +
.../include/core/flow/StructuredConfiguration.h | 2 +-
.../include/core/flow/StructuredConnectionParser.h | 2 +-
.../reporting/SiteToSiteProvenanceReportingTask.h | 6 +-
libminifi/include/sitetosite/HTTPProtocol.h | 157 ----
libminifi/include/sitetosite/HTTPTransaction.h | 32 +-
.../include/sitetosite/HttpSiteToSiteClient.h | 95 ++
libminifi/include/sitetosite/Peer.h | 305 ++-----
libminifi/include/sitetosite/PeersEntity.h | 117 ---
libminifi/include/sitetosite/RawSiteToSiteClient.h | 96 ++
libminifi/include/sitetosite/RawSocketProtocol.h | 177 ----
libminifi/include/sitetosite/SiteToSite.h | 373 ++++----
libminifi/include/sitetosite/SiteToSiteClient.h | 286 +++---
libminifi/include/sitetosite/SiteToSiteFactory.h | 63 +-
libminifi/src/RemoteProcessGroupPort.cpp | 369 ++++++++
libminifi/src/RemoteProcessorGroupPort.cpp | 354 --------
libminifi/src/agent/JsonSchema.cpp | 6 +-
libminifi/src/core/flow/FlowSchema.cpp | 10 +
.../src/core/flow/StructuredConfiguration.cpp | 47 +-
.../src/core/flow/StructuredConnectionParser.cpp | 13 +-
.../SiteToSiteProvenanceReportingTask.cpp | 8 +-
libminifi/src/sitetosite/HTTPProtocol.cpp | 304 -------
libminifi/src/sitetosite/HttpSiteToSiteClient.cpp | 394 +++++++++
libminifi/src/sitetosite/Peer.cpp | 30 +-
libminifi/src/sitetosite/RawSiteToSiteClient.cpp | 430 +++++++++
libminifi/src/sitetosite/RawSocketProtocol.cpp | 623 -------------
libminifi/src/sitetosite/SiteToSite.cpp | 49 --
libminifi/src/sitetosite/SiteToSiteClient.cpp | 969 +++++++++++----------
libminifi/src/sitetosite/SiteToSiteFactory.cpp | 83 ++
libminifi/test/integration/HTTPSiteToSiteTests.cpp | 8 +-
libminifi/test/integration/SiteToSiteRestTest.cpp | 6 +-
.../integration/TimeoutHTTPSiteToSiteTests.cpp | 6 +-
.../test/libtest/integration/HTTPHandlers.cpp | 29 +-
libminifi/test/libtest/unit/DummyProcessor.h | 3 +-
libminifi/test/resources/TestHTTPSiteToSite.yml | 10 +-
.../test/resources/TestTimeoutHTTPSiteToSite.yml | 8 +-
libminifi/test/unit/Site2SiteTests.cpp | 150 ----
libminifi/test/unit/SiteToSiteTests.cpp | 338 +++++++
packaging/rpm/expected-rpm-contents.in | 1 +
92 files changed, 4374 insertions(+), 3690 deletions(-)
create mode 100644 SITE_TO_SITE.md
copy docker/test/integration/minifi/core/{InputPort.py => OutputPort.py} (87%)
rename libminifi/include/{RemoteProcessorGroupPort.h => RemoteProcessGroupPort.h} (59%)
delete mode 100644 libminifi/include/sitetosite/HTTPProtocol.h
create mode 100644 libminifi/include/sitetosite/HttpSiteToSiteClient.h
delete mode 100644 libminifi/include/sitetosite/PeersEntity.h
create mode 100644 libminifi/include/sitetosite/RawSiteToSiteClient.h
delete mode 100644 libminifi/include/sitetosite/RawSocketProtocol.h
create mode 100644 libminifi/src/RemoteProcessGroupPort.cpp
delete mode 100644 libminifi/src/RemoteProcessorGroupPort.cpp
delete mode 100644 libminifi/src/sitetosite/HTTPProtocol.cpp
create mode 100644 libminifi/src/sitetosite/HttpSiteToSiteClient.cpp
create mode 100644 libminifi/src/sitetosite/RawSiteToSiteClient.cpp
delete mode 100644 libminifi/src/sitetosite/RawSocketProtocol.cpp
delete mode 100644 libminifi/src/sitetosite/SiteToSite.cpp
create mode 100644 libminifi/src/sitetosite/SiteToSiteFactory.cpp
delete mode 100644 libminifi/test/unit/Site2SiteTests.cpp
create mode 100644 libminifi/test/unit/SiteToSiteTests.cpp
(nifi-minifi-cpp) 04/04: MINIFICPP-2642 std::invocable should be used with std::invoke
Posted by sz...@apache.org.
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
commit 198c8907815fa4d311d0c32585aa7952e9aff579
Author: Marton Szasz <sz...@apache.org>
AuthorDate: Tue Sep 30 16:28:31 2025 +0200
MINIFICPP-2642 std::invocable should be used with std::invoke
Replacing calls with invoke where invocable is used.
https://en.cppreference.com/w/cpp/concepts/invocable
The invocable concept checks that type F can be called with arguments
Args... using std::invoke. Std::invoke is more general than a direct
function call: it supports member function and data member pointers too,
where the first "argument" is the object.
In theory, if we checked for invocable but called directly, someone
could pass a member pointer as the callback, and it would pass the
concept check but fail to build.
Closes #2038
Signed-off-by: Marton Szasz <sz...@apache.org>
---
extensions/procfs/ProcFsSerialization.h | 165 +++++++++++----------
.../standard-processors/processors/InvokeHTTP.cpp | 12 +-
.../standard-processors/processors/InvokeHTTP.h | 2 +-
extensions/standard-processors/utils/JoltUtils.h | 4 +-
extensions/windows-event-log/wel/StringSplitter.h | 5 +-
5 files changed, 96 insertions(+), 92 deletions(-)
diff --git a/extensions/procfs/ProcFsSerialization.h b/extensions/procfs/ProcFsSerialization.h
index ef791a319..4becf9dcc 100644
--- a/extensions/procfs/ProcFsSerialization.h
+++ b/extensions/procfs/ProcFsSerialization.h
@@ -16,8 +16,9 @@
*/
#pragma once
-#include <stdint.h>
+#include <cstdint>
#include <concepts>
+#include <functional>
#include <string_view>
#include "CpuStat.h"
@@ -33,16 +34,16 @@ template<class Serializer>
requires std::invocable<Serializer, const char*, uint64_t>
void SerializeCPUStatData(const CpuStatData& cpu_stat_data,
Serializer serializer) {
- serializer("user time", cpu_stat_data.getUser().count());
- serializer("nice time", cpu_stat_data.getNice().count());
- serializer("system time", cpu_stat_data.getSystem().count());
- serializer("idle time", cpu_stat_data.getIdle().count());
- serializer("io wait time", cpu_stat_data.getIoWait().count());
- serializer("irq time", cpu_stat_data.getIrq().count());
- serializer("soft irq time", cpu_stat_data.getSoftIrq().count());
- serializer("steal time", cpu_stat_data.getSteal().count());
- serializer("guest time", cpu_stat_data.getGuest().count());
- serializer("guest nice time", cpu_stat_data.getGuestNice().count());
+ std::invoke(serializer, "user time", cpu_stat_data.getUser().count());
+ std::invoke(serializer, "nice time", cpu_stat_data.getNice().count());
+ std::invoke(serializer, "system time", cpu_stat_data.getSystem().count());
+ std::invoke(serializer, "idle time", cpu_stat_data.getIdle().count());
+ std::invoke(serializer, "io wait time", cpu_stat_data.getIoWait().count());
+ std::invoke(serializer, "irq time", cpu_stat_data.getIrq().count());
+ std::invoke(serializer, "soft irq time", cpu_stat_data.getSoftIrq().count());
+ std::invoke(serializer, "steal time", cpu_stat_data.getSteal().count());
+ std::invoke(serializer, "guest time", cpu_stat_data.getGuest().count());
+ std::invoke(serializer, "guest nice time", cpu_stat_data.getGuestNice().count());
}
template<class Serializer>
@@ -50,31 +51,31 @@ requires std::invocable<Serializer, const char*, double>
void SerializeNormalizedCPUStat(const CpuStatData& cpu_stat_data,
Serializer serializer) {
gsl_Expects(cpu_stat_data.getTotal() > 0ms);
- serializer("user time %", cpu_stat_data.getUser()/cpu_stat_data.getTotal());
- serializer("nice time %", cpu_stat_data.getNice()/cpu_stat_data.getTotal());
- serializer("system time %", cpu_stat_data.getSystem()/cpu_stat_data.getTotal());
- serializer("idle time %", cpu_stat_data.getIdle()/cpu_stat_data.getTotal());
- serializer("io wait time %", cpu_stat_data.getIoWait()/cpu_stat_data.getTotal());
- serializer("irq time %", cpu_stat_data.getIrq()/cpu_stat_data.getTotal());
- serializer("soft irq %", cpu_stat_data.getSoftIrq()/cpu_stat_data.getTotal());
- serializer("steal time %", cpu_stat_data.getSteal()/cpu_stat_data.getTotal());
- serializer("guest time %", cpu_stat_data.getGuest()/cpu_stat_data.getTotal());
- serializer("guest nice time %", cpu_stat_data.getGuestNice()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "user time %", cpu_stat_data.getUser()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "nice time %", cpu_stat_data.getNice()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "system time %", cpu_stat_data.getSystem()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "idle time %", cpu_stat_data.getIdle()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "io wait time %", cpu_stat_data.getIoWait()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "irq time %", cpu_stat_data.getIrq()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "soft irq %", cpu_stat_data.getSoftIrq()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "steal time %", cpu_stat_data.getSteal()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "guest time %", cpu_stat_data.getGuest()/cpu_stat_data.getTotal());
+ std::invoke(serializer, "guest nice time %", cpu_stat_data.getGuestNice()/cpu_stat_data.getTotal());
}
template<class Serializer>
requires std::invocable<Serializer, const char*, uint64_t>
void SerializeDiskStatData(const DiskStatData& disk_stat_data,
Serializer serializer) {
- serializer("Major Device Number", disk_stat_data.getMajorDeviceNumber());
- serializer("Minor Device Number", disk_stat_data.getMinorDeviceNumber());
- serializer("Reads Completed", disk_stat_data.getReadsCompleted());
- serializer("Reads Merged", disk_stat_data.getReadsMerged());
- serializer("Sectors Read", disk_stat_data.getSectorsRead());
- serializer("Writes Completed", disk_stat_data.getWritesCompleted());
- serializer("Writes Merged", disk_stat_data.getWritesMerged());
- serializer("Sectors Written", disk_stat_data.getSectorsWritten());
- serializer("IOs in progress", disk_stat_data.getIosInProgress());
+ std::invoke(serializer, "Major Device Number", disk_stat_data.getMajorDeviceNumber());
+ std::invoke(serializer, "Minor Device Number", disk_stat_data.getMinorDeviceNumber());
+ std::invoke(serializer, "Reads Completed", disk_stat_data.getReadsCompleted());
+ std::invoke(serializer, "Reads Merged", disk_stat_data.getReadsMerged());
+ std::invoke(serializer, "Sectors Read", disk_stat_data.getSectorsRead());
+ std::invoke(serializer, "Writes Completed", disk_stat_data.getWritesCompleted());
+ std::invoke(serializer, "Writes Merged", disk_stat_data.getWritesMerged());
+ std::invoke(serializer, "Sectors Written", disk_stat_data.getSectorsWritten());
+ std::invoke(serializer, "IOs in progress", disk_stat_data.getIosInProgress());
}
template<class Serializer>
@@ -83,49 +84,49 @@ void SerializeDiskStatDataPerSec(const DiskStatData& disk_stat_data,
const std::chrono::duration<double> duration,
Serializer serializer) {
gsl_Expects(duration > 0ms);
- serializer("Major Device Number", disk_stat_data.getMajorDeviceNumber());
- serializer("Minor Device Number", disk_stat_data.getMinorDeviceNumber());
- serializer("Reads Completed/sec", disk_stat_data.getReadsCompleted()/duration.count());
- serializer("Reads Merged/sec", disk_stat_data.getReadsMerged()/duration.count());
- serializer("Sectors Read/sec", disk_stat_data.getSectorsRead()/duration.count());
- serializer("Writes Completed/sec", disk_stat_data.getWritesCompleted()/duration.count());
- serializer("Writes Merged/sec", disk_stat_data.getWritesMerged()/duration.count());
- serializer("Sectors Written/sec", disk_stat_data.getSectorsWritten()/duration.count());
- serializer("IOs in progress", disk_stat_data.getIosInProgress()/duration.count());
+ std::invoke(serializer, "Major Device Number", disk_stat_data.getMajorDeviceNumber());
+ std::invoke(serializer, "Minor Device Number", disk_stat_data.getMinorDeviceNumber());
+ std::invoke(serializer, "Reads Completed/sec", disk_stat_data.getReadsCompleted()/duration.count());
+ std::invoke(serializer, "Reads Merged/sec", disk_stat_data.getReadsMerged()/duration.count());
+ std::invoke(serializer, "Sectors Read/sec", disk_stat_data.getSectorsRead()/duration.count());
+ std::invoke(serializer, "Writes Completed/sec", disk_stat_data.getWritesCompleted()/duration.count());
+ std::invoke(serializer, "Writes Merged/sec", disk_stat_data.getWritesMerged()/duration.count());
+ std::invoke(serializer, "Sectors Written/sec", disk_stat_data.getSectorsWritten()/duration.count());
+ std::invoke(serializer, "IOs in progress", disk_stat_data.getIosInProgress()/duration.count());
}
template<class Serializer>
requires std::invocable<Serializer, const char*, uint64_t>
void SerializeMemInfo(const MemInfo& mem_info,
Serializer serializer) {
- serializer("MemTotal", mem_info.getTotalMemory());
- serializer("MemFree", mem_info.getFreeMemory());
- serializer("MemAvailable", mem_info.getAvailableMemory());
- serializer("SwapTotal", mem_info.getTotalSwap());
- serializer("SwapFree", mem_info.getFreeSwap());
+ std::invoke(serializer, "MemTotal", mem_info.getTotalMemory());
+ std::invoke(serializer, "MemFree", mem_info.getFreeMemory());
+ std::invoke(serializer, "MemAvailable", mem_info.getAvailableMemory());
+ std::invoke(serializer, "SwapTotal", mem_info.getTotalSwap());
+ std::invoke(serializer, "SwapFree", mem_info.getFreeSwap());
}
template<class Serializer>
requires std::invocable<Serializer, const char*, uint64_t>
void SerializeNetDevData(const NetDevData& net_dev_data,
Serializer serializer) {
- serializer("Bytes Received", net_dev_data.getBytesReceived());
- serializer("Packets Received", net_dev_data.getPacketsReceived());
- serializer("Receive Errors", net_dev_data.getReceiveErrors());
- serializer("Receive Drop Errors", net_dev_data.getReceiveDropErrors());
- serializer("Receive Fifo Errors", net_dev_data.getReceiveFifoErrors());
- serializer("Receive Frame Errors", net_dev_data.getReceiveFrameErrors());
- serializer("Compressed Packets Received", net_dev_data.getCompressedPacketsReceived());
- serializer("Multicast Frames Received", net_dev_data.getMulticastFramesReceived());
+ std::invoke(serializer, "Bytes Received", net_dev_data.getBytesReceived());
+ std::invoke(serializer, "Packets Received", net_dev_data.getPacketsReceived());
+ std::invoke(serializer, "Receive Errors", net_dev_data.getReceiveErrors());
+ std::invoke(serializer, "Receive Drop Errors", net_dev_data.getReceiveDropErrors());
+ std::invoke(serializer, "Receive Fifo Errors", net_dev_data.getReceiveFifoErrors());
+ std::invoke(serializer, "Receive Frame Errors", net_dev_data.getReceiveFrameErrors());
+ std::invoke(serializer, "Compressed Packets Received", net_dev_data.getCompressedPacketsReceived());
+ std::invoke(serializer, "Multicast Frames Received", net_dev_data.getMulticastFramesReceived());
- serializer("Bytes Transmitted", net_dev_data.getBytesTransmitted());
- serializer("Packets Transmitted", net_dev_data.getPacketsTransmitted());
- serializer("Transmit errors", net_dev_data.getTransmitErrors());
- serializer("Transmit drop errors", net_dev_data.getTransmitDropErrors());
- serializer("Transmit fifo errors", net_dev_data.getTransmitFifoErrors());
- serializer("Transmit collisions", net_dev_data.getTransmitCollisions());
- serializer("Transmit carrier losses", net_dev_data.getTransmitCarrierLosses());
- serializer("Compressed Packets Transmitted", net_dev_data.getCompressedPacketsTransmitted());
+ std::invoke(serializer, "Bytes Transmitted", net_dev_data.getBytesTransmitted());
+ std::invoke(serializer, "Packets Transmitted", net_dev_data.getPacketsTransmitted());
+ std::invoke(serializer, "Transmit errors", net_dev_data.getTransmitErrors());
+ std::invoke(serializer, "Transmit drop errors", net_dev_data.getTransmitDropErrors());
+ std::invoke(serializer, "Transmit fifo errors", net_dev_data.getTransmitFifoErrors());
+ std::invoke(serializer, "Transmit collisions", net_dev_data.getTransmitCollisions());
+ std::invoke(serializer, "Transmit carrier losses", net_dev_data.getTransmitCarrierLosses());
+ std::invoke(serializer, "Compressed Packets Transmitted", net_dev_data.getCompressedPacketsTransmitted());
}
template<class Serializer>
@@ -134,23 +135,23 @@ void SerializeNetDevDataPerSec(const NetDevData& net_dev_data,
const std::chrono::duration<double> duration,
Serializer serializer) {
gsl_Expects(duration > 0ms);
- serializer("Bytes Received/sec", net_dev_data.getBytesReceived()/duration.count());
- serializer("Packets Received/sec", net_dev_data.getPacketsReceived()/duration.count());
- serializer("Receive Errors/sec", net_dev_data.getReceiveErrors()/duration.count());
- serializer("Receive Drop Errors/sec", net_dev_data.getReceiveDropErrors()/duration.count());
- serializer("Receive Fifo Errors/sec", net_dev_data.getReceiveFifoErrors()/duration.count());
- serializer("Receive Frame Errors/sec", net_dev_data.getReceiveFrameErrors()/duration.count());
- serializer("Compressed Packets Received/sec", net_dev_data.getCompressedPacketsReceived()/duration.count());
- serializer("Multicast Frames Received/sec", net_dev_data.getMulticastFramesReceived()/duration.count());
+ std::invoke(serializer, "Bytes Received/sec", net_dev_data.getBytesReceived()/duration.count());
+ std::invoke(serializer, "Packets Received/sec", net_dev_data.getPacketsReceived()/duration.count());
+ std::invoke(serializer, "Receive Errors/sec", net_dev_data.getReceiveErrors()/duration.count());
+ std::invoke(serializer, "Receive Drop Errors/sec", net_dev_data.getReceiveDropErrors()/duration.count());
+ std::invoke(serializer, "Receive Fifo Errors/sec", net_dev_data.getReceiveFifoErrors()/duration.count());
+ std::invoke(serializer, "Receive Frame Errors/sec", net_dev_data.getReceiveFrameErrors()/duration.count());
+ std::invoke(serializer, "Compressed Packets Received/sec", net_dev_data.getCompressedPacketsReceived()/duration.count());
+ std::invoke(serializer, "Multicast Frames Received/sec", net_dev_data.getMulticastFramesReceived()/duration.count());
- serializer("Bytes Transmitted/sec", net_dev_data.getBytesTransmitted()/duration.count());
- serializer("Packets Transmitted/sec", net_dev_data.getPacketsTransmitted()/duration.count());
- serializer("Transmit errors/sec", net_dev_data.getTransmitErrors()/duration.count());
- serializer("Transmit drop errors/sec", net_dev_data.getTransmitDropErrors()/duration.count());
- serializer("Transmit fifo errors/sec", net_dev_data.getTransmitFifoErrors()/duration.count());
- serializer("Transmit collisions/sec", net_dev_data.getTransmitCollisions()/duration.count());
- serializer("Transmit carrier losses/sec", net_dev_data.getTransmitCarrierLosses()/duration.count());
- serializer("Compressed Packets Transmitted/sec", net_dev_data.getCompressedPacketsTransmitted()/duration.count());
+ std::invoke(serializer, "Bytes Transmitted/sec", net_dev_data.getBytesTransmitted()/duration.count());
+ std::invoke(serializer, "Packets Transmitted/sec", net_dev_data.getPacketsTransmitted()/duration.count());
+ std::invoke(serializer, "Transmit errors/sec", net_dev_data.getTransmitErrors()/duration.count());
+ std::invoke(serializer, "Transmit drop errors/sec", net_dev_data.getTransmitDropErrors()/duration.count());
+ std::invoke(serializer, "Transmit fifo errors/sec", net_dev_data.getTransmitFifoErrors()/duration.count());
+ std::invoke(serializer, "Transmit collisions/sec", net_dev_data.getTransmitCollisions()/duration.count());
+ std::invoke(serializer, "Transmit carrier losses/sec", net_dev_data.getTransmitCarrierLosses()/duration.count());
+ std::invoke(serializer, "Compressed Packets Transmitted/sec", net_dev_data.getCompressedPacketsTransmitted()/duration.count());
}
template<class Serializer>
@@ -158,9 +159,9 @@ requires std::invocable<Serializer, const char*, uint64_t> &&
std::invocable<Serializer, const char*, std::string_view>
void SerializeProcessStat(const ProcessStat& process_stat,
Serializer serializer) {
- serializer("COMM", process_stat.getComm());
- serializer("RES", process_stat.getMemory());
- serializer("CPUTIME", process_stat.getCpuTime().count());
+ std::invoke(serializer, "COMM", process_stat.getComm());
+ std::invoke(serializer, "RES", process_stat.getMemory());
+ std::invoke(serializer, "CPUTIME", process_stat.getCpuTime().count());
}
template<class Serializer>
@@ -175,9 +176,9 @@ void SerializeNormalizedProcessStat(const ProcessStat& process_stat_start,
gsl_Expects(process_stat_start.getComm() == process_stat_end.getComm());
gsl_Expects(process_stat_end.getCpuTime() >= process_stat_start.getCpuTime());
auto cpu_time_diff = process_stat_end.getCpuTime()-process_stat_start.getCpuTime();
- serializer("COMM", process_stat_start.getComm());
- serializer("RES", process_stat_end.getMemory());
- serializer("CPU%", 100*(cpu_time_diff/all_cpu_time));
+ std::invoke(serializer, "COMM", process_stat_start.getComm());
+ std::invoke(serializer, "RES", process_stat_end.getMemory());
+ std::invoke(serializer, "CPU%", 100*(cpu_time_diff/all_cpu_time));
}
} // namespace org::apache::nifi::minifi::extensions::procfs
diff --git a/extensions/standard-processors/processors/InvokeHTTP.cpp b/extensions/standard-processors/processors/InvokeHTTP.cpp
index 269479ede..7ca018fd4 100644
--- a/extensions/standard-processors/processors/InvokeHTTP.cpp
+++ b/extensions/standard-processors/processors/InvokeHTTP.cpp
@@ -19,6 +19,7 @@
#include "InvokeHTTP.h"
#include <cinttypes>
+#include <functional>
#include <memory>
#include <string>
#include <utility>
@@ -208,8 +209,7 @@ bool InvokeHTTP::shouldEmitFlowFile() const {
* @param append_header Callback to append HTTP header to the request
* @return false when the flow file should be routed to failure, true otherwise
*/
-bool InvokeHTTP::appendHeaders(const core::FlowFile& flow_file, /*std::invocable<std::string, std::string>*/ auto append_header) {
- static_assert(std::is_invocable_v<decltype(append_header), std::string, std::string>);
+bool InvokeHTTP::appendHeaders(const core::FlowFile& flow_file, std::invocable<std::string, std::string> auto append_header) {
if (!attributes_to_send_) return true;
const auto key_fn = [](const std::pair<std::string, std::string>& pair) { return pair.first; };
const auto original_attributes = flow_file.getAttributes();
@@ -219,16 +219,18 @@ bool InvokeHTTP::appendHeaders(const core::FlowFile& flow_file, /*std::invocable
switch (invalid_http_header_field_handling_strategy_) {
case invoke_http::InvalidHTTPHeaderFieldHandlingOption::fail:
if (ranges::any_of(matching_attributes, std::not_fn(&http::HTTPClient::isValidHttpHeaderField), key_fn)) return false;
- for (const auto& header: matching_attributes) append_header(header.first, http::HTTPClient::removeInvalidCharactersFromHttpHeaderFieldBody(header.second));
+ for (const auto& header: matching_attributes) {
+ std::invoke(append_header, header.first, http::HTTPClient::removeInvalidCharactersFromHttpHeaderFieldBody(header.second));
+ }
return true;
case invoke_http::InvalidHTTPHeaderFieldHandlingOption::drop:
for (const auto& header: matching_attributes | ranges::views::filter(&http::HTTPClient::isValidHttpHeaderField, key_fn)) {
- append_header(header.first, http::HTTPClient::removeInvalidCharactersFromHttpHeaderFieldBody(header.second));
+ std::invoke(append_header, header.first, http::HTTPClient::removeInvalidCharactersFromHttpHeaderFieldBody(header.second));
}
return true;
case invoke_http::InvalidHTTPHeaderFieldHandlingOption::transform:
for (const auto& header: matching_attributes) {
- append_header(http::HTTPClient::replaceInvalidCharactersInHttpHeaderFieldName(header.first), http::HTTPClient::removeInvalidCharactersFromHttpHeaderFieldBody(header.second));
+ std::invoke(append_header, http::HTTPClient::replaceInvalidCharactersInHttpHeaderFieldName(header.first), http::HTTPClient::removeInvalidCharactersFromHttpHeaderFieldBody(header.second));
}
return true;
}
diff --git a/extensions/standard-processors/processors/InvokeHTTP.h b/extensions/standard-processors/processors/InvokeHTTP.h
index a8950057f..744f9781f 100644
--- a/extensions/standard-processors/processors/InvokeHTTP.h
+++ b/extensions/standard-processors/processors/InvokeHTTP.h
@@ -341,7 +341,7 @@ class InvokeHTTP : public core::ProcessorImpl {
[[nodiscard]] bool shouldEmitFlowFile() const;
void onTriggerWithClient(core::ProcessContext& context, core::ProcessSession& session,
const std::shared_ptr<core::FlowFile>& flow_file, http::HTTPClient& client);
- [[nodiscard]] bool appendHeaders(const core::FlowFile& flow_file, /*std::invocable<std::string, std::string>*/ auto append_header);
+ [[nodiscard]] bool appendHeaders(const core::FlowFile& flow_file, std::invocable<std::string, std::string> auto append_header);
void setupMembersFromProperties(const core::ProcessContext& context);
diff --git a/extensions/standard-processors/utils/JoltUtils.h b/extensions/standard-processors/utils/JoltUtils.h
index 12a9c8078..8395391ed 100644
--- a/extensions/standard-processors/utils/JoltUtils.h
+++ b/extensions/standard-processors/utils/JoltUtils.h
@@ -61,9 +61,9 @@ class Spec {
template<std::invocable<std::shared_ptr<core::logging::Logger>> OnEnterFn, std::invocable<std::shared_ptr<core::logging::Logger>> OnExitFn>
::gsl::final_action<std::function<void()>> log(OnEnterFn on_enter, OnExitFn on_exit) const {
if (logger) {
- on_enter(logger);
+ std::invoke(on_enter, logger);
return gsl::finally<std::function<void()>>([on_exit, logger = logger] {
- on_exit(logger);
+ std::invoke(on_exit, logger);
});
}
if (parent) {
diff --git a/extensions/windows-event-log/wel/StringSplitter.h b/extensions/windows-event-log/wel/StringSplitter.h
index 5dbf620c2..67930d65c 100644
--- a/extensions/windows-event-log/wel/StringSplitter.h
+++ b/extensions/windows-event-log/wel/StringSplitter.h
@@ -19,6 +19,7 @@
#include <cctype>
#include <concepts>
+#include <functional>
#include <ranges>
#include <string_view>
#include <vector>
@@ -46,9 +47,9 @@ void splitCommaSeparatedKeyValuePairs(std::string_view input, Func output_callba
})
| std::ranges::to<std::vector>();
if (key_value_vec.size() == 2) {
- output_callback(key_value_vec[0], key_value_vec[1]);
+ std::invoke(output_callback, key_value_vec[0], key_value_vec[1]);
} else if (key_value_vec.size() == 1) {
- output_callback(key_value_vec[0], "");
+ std::invoke(output_callback, key_value_vec[0], "");
}
}
}
(nifi-minifi-cpp) 01/04: MINIFICPP-2558 Revamp site to site communication
Posted by sz...@apache.org.
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
commit 4f296765b4d06040d72c665ff0d8c4721ce4e636
Author: Gabor Gyimesi <ga...@gmail.com>
AuthorDate: Tue Sep 30 16:26:16 2025 +0200
MINIFICPP-2558 Revamp site to site communication
- Fix communicating with remote output port
- Add handling of remote port batch size properties
- Extend port management in config generation in docker integration tests
- Make input port in remote process groups optional (as using only output ports can also be a valid configuration)
- Add additional testing
- Refactor RPG and site to site clients
- Additional documentation
Closes #1966
Signed-off-by: Marton Szasz <sz...@apache.org>
---
README.md | 4 +
SITE_TO_SITE.md | 133 +++
core-framework/include/io/CRCStream.h | 2 +-
.../cluster/containers/NifiContainer.py | 2 +-
.../features/MiNiFi_integration_test_driver.py | 13 +
docker/test/integration/features/s2s.feature | 202 ++++-
docker/test/integration/features/steps/steps.py | 67 +-
docker/test/integration/minifi/core/Connectable.py | 3 +
docker/test/integration/minifi/core/InputPort.py | 3 +
.../minifi/core/{InputPort.py => OutputPort.py} | 7 +-
.../integration/minifi/core/RemoteProcessGroup.py | 3 +-
.../Minifi_flow_json_serializer.py | 99 ++-
.../Minifi_flow_yaml_serializer.py | 108 ++-
.../Nifi_flow_json_serializer.py | 26 +-
.../tests/unit/FlowJsonTests.cpp | 112 ++-
.../tests/unit/ProcessGroupTestUtils.h | 2 +-
.../tests/unit/ProcessorTests.cpp | 8 +-
.../tests/unit/YamlConfigurationTests.cpp | 86 +-
...ocessorGroupPort.h => RemoteProcessGroupPort.h} | 199 ++---
libminifi/include/core/FlowConfiguration.h | 2 +-
libminifi/include/core/flow/FlowSchema.h | 5 +
.../include/core/flow/StructuredConfiguration.h | 2 +-
.../include/core/flow/StructuredConnectionParser.h | 2 +-
.../reporting/SiteToSiteProvenanceReportingTask.h | 6 +-
libminifi/include/sitetosite/HTTPProtocol.h | 157 ----
libminifi/include/sitetosite/HTTPTransaction.h | 32 +-
.../include/sitetosite/HttpSiteToSiteClient.h | 95 ++
libminifi/include/sitetosite/Peer.h | 305 ++-----
libminifi/include/sitetosite/PeersEntity.h | 117 ---
libminifi/include/sitetosite/RawSiteToSiteClient.h | 96 ++
libminifi/include/sitetosite/RawSocketProtocol.h | 177 ----
libminifi/include/sitetosite/SiteToSite.h | 373 ++++----
libminifi/include/sitetosite/SiteToSiteClient.h | 286 +++---
libminifi/include/sitetosite/SiteToSiteFactory.h | 63 +-
libminifi/src/RemoteProcessGroupPort.cpp | 369 ++++++++
libminifi/src/RemoteProcessorGroupPort.cpp | 354 --------
libminifi/src/agent/JsonSchema.cpp | 6 +-
libminifi/src/core/flow/FlowSchema.cpp | 10 +
.../src/core/flow/StructuredConfiguration.cpp | 47 +-
.../src/core/flow/StructuredConnectionParser.cpp | 13 +-
.../SiteToSiteProvenanceReportingTask.cpp | 8 +-
libminifi/src/sitetosite/HTTPProtocol.cpp | 304 -------
libminifi/src/sitetosite/HttpSiteToSiteClient.cpp | 394 +++++++++
libminifi/src/sitetosite/Peer.cpp | 30 +-
libminifi/src/sitetosite/RawSiteToSiteClient.cpp | 430 +++++++++
libminifi/src/sitetosite/RawSocketProtocol.cpp | 623 -------------
libminifi/src/sitetosite/SiteToSite.cpp | 49 --
libminifi/src/sitetosite/SiteToSiteClient.cpp | 969 +++++++++++----------
libminifi/src/sitetosite/SiteToSiteFactory.cpp | 83 ++
libminifi/test/integration/HTTPSiteToSiteTests.cpp | 8 +-
libminifi/test/integration/SiteToSiteRestTest.cpp | 6 +-
.../integration/TimeoutHTTPSiteToSiteTests.cpp | 6 +-
.../test/libtest/integration/HTTPHandlers.cpp | 29 +-
libminifi/test/libtest/unit/DummyProcessor.h | 3 +-
libminifi/test/resources/TestHTTPSiteToSite.yml | 10 +-
.../test/resources/TestTimeoutHTTPSiteToSite.yml | 8 +-
libminifi/test/unit/Site2SiteTests.cpp | 150 ----
libminifi/test/unit/SiteToSiteTests.cpp | 338 +++++++
packaging/rpm/expected-rpm-contents.in | 1 +
59 files changed, 3648 insertions(+), 3397 deletions(-)
diff --git a/README.md b/README.md
index b1461c9f4..5faa8b8aa 100644
--- a/README.md
+++ b/README.md
@@ -100,6 +100,10 @@ The next table outlines CMAKE flags that correspond with MiNiFi extensions. Exte
Please see our [Python guide](extensions/python/PYTHON.md) on how to write Python processors and use them within MiNiFi C++.
+### Site-to-Site communication
+
+Communicating with Apache NiFi can be done using the Site-to-Site protocol. More information on configuring it in MiNiFi C++ can be found in the [Site-to-Site documentation](SITE_TO_SITE.md).
+
## Caveats
* We follow semver with regards to API compatibility, but no ABI compatibility is provided. See [semver's website](https://semver.org/) for more information
* Build and usage currently only supports Windows, Linux and macOS environments. MiNiFi C++ can be built and run through the Windows Subsystem for Linux but we provide no support for this platform.
diff --git a/SITE_TO_SITE.md b/SITE_TO_SITE.md
new file mode 100644
index 000000000..0869a3acc
--- /dev/null
+++ b/SITE_TO_SITE.md
@@ -0,0 +1,133 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+ http://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+
+## Table of Contents
+- [Site-to-Site Overview](#site-to-site-overview)
+- [Site-to-Site Configuration](#site-to-site-configuration)
+ - [Site-to-Site Configuration on NiFi side](#site-to-site-configuration-on-nifi-side)
+ - [Site-to-Site Configuration on MiNiFi C++ side](#site-to-site-configuration-on-minifi-c-side)
+- [Additional examples](#additional-examples)
+
+## Site-to-Site Overview
+
+Site-to-Site protocol allows data to be transferred between MiNiFi C++ and NiFi instances. MiNiFi C++ can send or receive data from NiFi using remote process groups. This is useful for scenarios where you want to send data from MiNiFi C++ to NiFi or vice versa. Site-to-Site protocol support raw TCP and HTTP protocols.
+
+At the moment site-to-site protocol is only supported between MiNiFi C++ and NiFi instances, it cannot be used to transfer data between multiple MiNiFi C++ instances. It is recommended to use processors like InvokeHTTP and ListenHTTP to transfer data between MiNiFi C++ instances.
+
+## Site-to-Site Configuration
+
+### Site-to-Site Configuration on NiFi side
+
+On NiFi side, site-to-site protocol is configured by creating input and output ports. The input port is used to receive data from MiNiFi C++ and the output port is used to send data to MiNiFi C++. The input and output ports can be created in the NiFi UI by dragging and dropping the input and output port icons onto the canvas.
+
+To use the input or output port of the NiFi flow in the MiNiFi C++ flow, the instance id of the port should be used. The instance id can be found in the NiFi UI by clicking on the input or output port and looking at the operation panel. It can be copied from that panel, or from the port "instanceIdentifier" field from configuration json file in the NiFi conf directory.
+
+### Site-to-Site Configuration on MiNiFi C++ side
+
+Site-to-Site protocol is configured on the MiNiFi C++ side by using remote process groups in the configuration. The remote process group represents the NiFi endpoint and uses the instance ids of the ports created on the NiFi side. The remote process group can be configured to use either raw TCP or HTTP protocol.
+
+Here is a yaml example of how to configure site-to-site protocol in MiNiFi C++ where the MiNiFi C++ instance is sending data to NiFi using raw socket protocol:
+
+```yaml
+MiNiFi Config Version: 3
+Flow Controller:
+ name: Simple GenerateFlowFile to RPG
+Processors:
+ - id: b0c04f28-0158-1000-0000-000000000000
+ name: GenerateFlowFile
+ class: org.apache.nifi.processors.standard.GenerateFlowFile
+ scheduling strategy: TIMER_DRIVEN
+ scheduling period: 5 sec
+ auto-terminated relationships list: []
+ Properties:
+ Data Format: Text
+ Unique FlowFiles: false
+ Custom Text: Custom text
+Connections:
+ - id: b0c0c3cc-0158-1000-0000-000000000000
+ name: GenerateFlowFile/succes/nifi-inputport
+ source id: b0c04f28-0158-1000-0000-000000000000
+ destination id: de7cc09a-0196-1000-2c63-ee6b4319ffb6
+ source relationship name: success
+Remote Process Groups:
+ - id: b0c09ff0-0158-1000-0000-000000000000
+ name: "RPG"
+ url: http://localhost:8080/nifi
+ timeout: 20 sec
+ yield period: 10 sec
+ transport protocol: RAW
+ Input Ports:
+ - id: de7cc09a-0196-1000-2c63-ee6b4319ffb6 # this is the instance id of the input port created in NiFi
+ name: nifi-inputport
+ max concurrent tasks: 1
+ use compression: false # currently not supported and ignored in MiNiFi C++
+ batch size:
+ size: 10 MB
+ count: 10
+ duration: 30 sec
+ Output Ports: []
+```
+
+Here is another example in yaml format how to configure site-to-site protocol in MiNiFi C++ where the MiNiFi C++ instance is receiving data from NiFi using the HTTP protocol:
+
+```yaml
+MiNiFi Config Version: 3
+Flow Controller:
+ name: MiNiFi Flow
+Processors:
+- Properties:
+ Directory: /tmp/output
+ auto-terminated relationships list:
+ - success
+ - failure
+ class: org.apache.nifi.processors.standard.PutFile
+ id: 6d6917dd-02ca-4add-b1e8-91468873009e
+ max concurrent tasks: 1
+ name: PutFile
+ penalization period: 30 sec
+ run duration nanos: 0
+ scheduling period: 1 sec
+ scheduling strategy: EVENT_DRIVEN
+ yield period: 1 sec
+Connections:
+- destination id: 6d6917dd-02ca-4add-b1e8-91468873009e
+ name: 64b65a70-4560-4717-89bb-d8335db99f27
+ source id: 22d38f35-4d25-4e68-878c-f46f46d5781c
+ source relationship name: undefined
+Remote Processing Groups:
+- Output Ports:
+ - Properties: {}
+ id: 22d38f35-4d25-4e68-878c-f46f46d5781c
+ max concurrent tasks: 1
+ name: from_nifi
+ id: 20ed42b0-d41e-4add-9e6d-8777223370b8
+ name: RemoteProcessGroup
+ timeout: 30 sec
+ url: http://localhost:8080/nifi
+ yield period: 3 sec
+```
+
+Notes on the configuration:
+
+- In the MiNiFi C++ configuration, in yaml configuration the remote input and output ports' `id` field, and in json configuration the ports' `identifier`, `instanceIdentifier`, and `targetId` fields should be set to the instance id of the input and output ports created in NiFi (`de7cc09a-0196-1000-2c63-ee6b4319ffb6` in the examples).
+- Connections from the remote output port to the processor should use the `undefined` relationship
+- `useCompression` can be set, but it is currently not supported in MiNiFi C++ so it will be set to false in the site-to-site messages
+- the `url` field (`targetUri` or `targetUris` in JSON) field in the remote process group should be set to the NiFi instance's URL, this can also use comma separated list of URLs if the remote process group is configured to use multiple NiFi nodes
+
+## Additional examples
+
+You can check out some additional examples of using site-to-site protocol in this [bidirectional site-to-site example](examples/BidirectionalSiteToSite/README.md).
+
+You can also check out a site-to-site example in [NiFi json](examples/site_to_site_config.nifi.schema.json), [MiNiFi C++ json](examples/site_to_site_config.json) and [yaml](examples/site_to_site_config.yml) formats.
diff --git a/core-framework/include/io/CRCStream.h b/core-framework/include/io/CRCStream.h
index 0331270aa..3cf1d844f 100644
--- a/core-framework/include/io/CRCStream.h
+++ b/core-framework/include/io/CRCStream.h
@@ -58,7 +58,7 @@ class CRCStreamBase : public virtual StreamImpl {
crc_ = crc32(crc_, buffer, length);
}
- uint64_t getCRC() {
+ uint64_t getCRC() const {
return gsl::narrow<uint64_t>(crc_);
}
diff --git a/docker/test/integration/cluster/containers/NifiContainer.py b/docker/test/integration/cluster/containers/NifiContainer.py
index 331099999..4120fa073 100644
--- a/docker/test/integration/cluster/containers/NifiContainer.py
+++ b/docker/test/integration/cluster/containers/NifiContainer.py
@@ -73,7 +73,7 @@ class NifiContainer(FlowContainer):
super().__init__(feature_context, config_dir, name, 'nifi', vols, network, image_store, command)
def get_startup_finished_log_entry(self):
- return "Starting Flow Controller"
+ return "Started Application in"
def __create_config(self):
serializer = Nifi_flow_json_serializer()
diff --git a/docker/test/integration/features/MiNiFi_integration_test_driver.py b/docker/test/integration/features/MiNiFi_integration_test_driver.py
index 27316150f..32f4f709f 100644
--- a/docker/test/integration/features/MiNiFi_integration_test_driver.py
+++ b/docker/test/integration/features/MiNiFi_integration_test_driver.py
@@ -20,6 +20,7 @@ import uuid
from typing import List
from pydoc import locate
from minifi.core.InputPort import InputPort
+from minifi.core.OutputPort import OutputPort
from cluster.DockerTestCluster import DockerTestCluster
from minifi.validators.OutputValidator import OutputValidator
from minifi.validators.EmptyFilesOutPutValidator import EmptyFilesOutPutValidator
@@ -94,6 +95,11 @@ class MiNiFi_integration_test:
self.cluster.deploy_container('couchbase-server')
assert self.cluster.wait_for_container_startup_to_finish('couchbase-server') or self.cluster.log_app_output()
+ def start_nifi(self, context):
+ self.cluster.acquire_container(context=context, name='nifi', engine='nifi')
+ self.cluster.deploy_container('nifi')
+ assert self.cluster.wait_for_container_startup_to_finish('nifi') or self.cluster.log_app_output()
+
def start(self, container_name=None):
if container_name is not None:
logging.info("Starting container %s", container_name)
@@ -155,6 +161,13 @@ class MiNiFi_integration_test:
input_port_node.set_uuid(uuid.uuid3(remote_process_group.get_uuid(), "input_port"))
return input_port_node
+ @staticmethod
+ def generate_output_port_for_remote_process_group(remote_process_group, name):
+ output_port_node = OutputPort(name, remote_process_group)
+ # Generate an MD5 hash unique to the remote process group id
+ output_port_node.set_uuid(uuid.uuid3(remote_process_group.get_uuid(), "output_port"))
+ return output_port_node
+
def add_test_data(self, path, test_data, file_name=None):
if file_name is None:
file_name = str(uuid.uuid4())
diff --git a/docker/test/integration/features/s2s.feature b/docker/test/integration/features/s2s.feature
index 80a8eb648..cf3a38988 100644
--- a/docker/test/integration/features/s2s.feature
+++ b/docker/test/integration/features/s2s.feature
@@ -25,73 +25,88 @@ Feature: Sending data from MiNiFi-C++ to NiFi using S2S protocol
Scenario: A MiNiFi instance produces and transfers data to a NiFi instance via s2s
Given a GetFile processor with the "Input Directory" property set to "/tmp/input"
And a file with the content "test" is present in "/tmp/input"
- And a RemoteProcessGroup node opened on "http://nifi-${feature_id}:8080/nifi"
- And the "success" relationship of the GetFile processor is connected to the input port on the RemoteProcessGroup
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "http://nifi-${feature_id}:8080/nifi"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
Scenario: A MiNiFi instance produces and transfers a large data file to a NiFi instance via s2s
Given a GetFile processor with the "Input Directory" property set to "/tmp/input"
And a file with the content "this is a very long file we want to send by site-to-site" is present in "/tmp/input"
- And a RemoteProcessGroup node opened on "http://nifi-${feature_id}:8080/nifi"
- And the "success" relationship of the GetFile processor is connected to the input port on the RemoteProcessGroup
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "http://nifi-${feature_id}:8080/nifi"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
Then a flowfile with the content "this is a very long file we want to send by site-to-site" is placed in the monitored directory in less than 90 seconds
And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
Scenario: Zero length files are transfered between via s2s if the "drop empty" connection property is false
Given a MiNiFi CPP server with yaml config
And a GenerateFlowFile processor with the "File Size" property set to "0B"
- And a RemoteProcessGroup node opened on "http://nifi-${feature_id}:8080/nifi"
- And the "success" relationship of the GenerateFlowFile processor is connected to the input port on the RemoteProcessGroup
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "http://nifi-${feature_id}:8080/nifi"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GenerateFlowFile processor is connected to the to_nifi
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
Then at least one empty flowfile is placed in the monitored directory in less than 90 seconds
Scenario: Zero length files are not transfered between via s2s if the "drop empty" connection property is true
# "drop empty" is only supported with yaml config
Given a MiNiFi CPP server with yaml config
And a GenerateFlowFile processor with the "File Size" property set to "0B"
- And a RemoteProcessGroup node opened on "http://nifi-${feature_id}:8080/nifi"
- And the "success" relationship of the GenerateFlowFile processor is connected to the input port on the RemoteProcessGroup
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "http://nifi-${feature_id}:8080/nifi"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GenerateFlowFile processor is connected to the to_nifi
And the connection going to the RemoteProcessGroup has "drop empty" set
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
Then no files are placed in the monitored directory in 50 seconds of running time
Scenario: A MiNiFi instance produces and transfers data to a NiFi instance via s2s using SSL
Given a GetFile processor with the "Input Directory" property set to "/tmp/input"
And the "Keep Source File" property of the GetFile processor is set to "true"
And a file with the content "test" is present in "/tmp/input"
- And a RemoteProcessGroup node opened on "https://nifi-${feature_id}:8443/nifi"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "https://nifi-${feature_id}:8443/nifi"
And a SSL context service is set up for the following remote process group: "RemoteProcessGroup"
- And the "success" relationship of the GetFile processor is connected to the input port on the RemoteProcessGroup
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
And SSL is enabled in NiFi flow
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
@@ -100,16 +115,19 @@ Feature: Sending data from MiNiFi-C++ to NiFi using S2S protocol
And a GetFile processor with the "Input Directory" property set to "/tmp/input"
And the "Keep Source File" property of the GetFile processor is set to "true"
And a file with the content "test" is present in "/tmp/input"
- And a RemoteProcessGroup node opened on "https://nifi-${feature_id}:8443/nifi"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "https://nifi-${feature_id}:8443/nifi"
And a SSL context service is set up for the following remote process group: "RemoteProcessGroup"
- And the "success" relationship of the GetFile processor is connected to the input port on the RemoteProcessGroup
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
And SSL is enabled in NiFi flow
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
@@ -117,16 +135,19 @@ Feature: Sending data from MiNiFi-C++ to NiFi using S2S protocol
Given a GetFile processor with the "Input Directory" property set to "/tmp/input"
And the "Keep Source File" property of the GetFile processor is set to "true"
And a file with the content "test" is present in "/tmp/input"
- And a RemoteProcessGroup node opened on "https://nifi-${feature_id}:8443/nifi"
- And the "success" relationship of the GetFile processor is connected to the input port on the RemoteProcessGroup
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "https://nifi-${feature_id}:8443/nifi"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
And SSL properties are set in MiNiFi
And SSL is enabled in NiFi flow
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
@@ -135,15 +156,132 @@ Feature: Sending data from MiNiFi-C++ to NiFi using S2S protocol
And a GetFile processor with the "Input Directory" property set to "/tmp/input"
And the "Keep Source File" property of the GetFile processor is set to "true"
And a file with the content "test" is present in "/tmp/input"
- And a RemoteProcessGroup node opened on "https://nifi-${feature_id}:8443/nifi"
- And the "success" relationship of the GetFile processor is connected to the input port on the RemoteProcessGroup
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "https://nifi-${feature_id}:8443/nifi"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
+ And SSL properties are set in MiNiFi
+
+ And SSL is enabled in NiFi flow
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
+ And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
+ And the "success" relationship of the from-minifi is connected to the PutFile
+
+ When NiFi is started
+ And all instances start up
+
+ Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
+ And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
+
+ Scenario: A MiNiFi instance produces and transfers data to a NiFi instance via s2s using HTTP protocol
+ Given a GetFile processor with the "Input Directory" property set to "/tmp/input"
+ And a file with the content "test" is present in "/tmp/input"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "http://nifi-${feature_id}:8080/nifi" with transport protocol set to "HTTP"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
+
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
+ And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
+ And the "success" relationship of the from-minifi is connected to the PutFile
+
+ When NiFi is started
+ And all instances start up
+
+ Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
+ And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
+
+ Scenario: A MiNiFi instance produces and transfers data to a NiFi instance via s2s using HTTP with YAML config and SSL config defined in minifi.properties
+ Given a MiNiFi CPP server with yaml config
+ And a GetFile processor with the "Input Directory" property set to "/tmp/input"
+ And the "Keep Source File" property of the GetFile processor is set to "true"
+ And a file with the content "test" is present in "/tmp/input"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "https://nifi-${feature_id}:8443/nifi" with transport protocol set to "HTTP"
+ And an input port with name "to_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile processor is connected to the to_nifi
And SSL properties are set in MiNiFi
And SSL is enabled in NiFi flow
- And a NiFi flow receiving data from a RemoteProcessGroup "from-minifi"
+ And a NiFi flow is receiving data from the RemoteProcessGroup named "RemoteProcessGroup" in an input port named "from-minifi" which has the same id as the port named "to_nifi"
And a PutFile processor with the "Directory" property set to "/tmp/output" in the "nifi" flow
And the "success" relationship of the from-minifi is connected to the PutFile
- When both instances start up
+ When NiFi is started
+ And all instances start up
+
+ Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
+ And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
+
+ Scenario: A NiFi instance produces and transfers data to a MiNiFi instance via s2s
+ Given a file with the content "test" is present in "/tmp/input"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "http://nifi-${feature_id}:8080/nifi"
+ And an output port with name "from_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And "from_nifi" port is a start node
+ And a PutFile processor with the "Directory" property set to "/tmp/output"
+ And the output port "from_nifi" is connected to the PutFile processor
+
+ And a GetFile processor with the "Input Directory" property set to "/tmp/input" in the "nifi" flow using the "nifi" engine
+ And a NiFi flow is sending data to an output port named "to-minifi-in-nifi" with the id of the port named "from_nifi" from the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile is connected to the to-minifi-in-nifi
+
+ When NiFi is started
+ And all instances start up
+
+ Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
+ And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
+
+ Scenario: A NiFi instance produces and transfers data to a MiNiFi instance via s2s using HTTP protocol
+ Given a file with the content "test" is present in "/tmp/input"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "http://nifi-${feature_id}:8080/nifi" with transport protocol set to "HTTP"
+ And an output port with name "from_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And "from_nifi" port is a start node
+ And a PutFile processor with the "Directory" property set to "/tmp/output"
+ And the output port "from_nifi" is connected to the PutFile processor
+
+ And a GetFile processor with the "Input Directory" property set to "/tmp/input" in the "nifi" flow using the "nifi" engine
+ And a NiFi flow is sending data to an output port named "to-minifi-in-nifi" with the id of the port named "from_nifi" from the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile is connected to the to-minifi-in-nifi
+
+ When NiFi is started
+ And all instances start up
+
+ Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
+ And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
+
+ Scenario: A NiFi instance produces and transfers data to a MiNiFi instance via s2s with SSL config defined in minifi.properties
+ Given a file with the content "test" is present in "/tmp/input"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "https://nifi-${feature_id}:8443/nifi"
+ And an output port with name "from_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And "from_nifi" port is a start node
+ And a PutFile processor with the "Directory" property set to "/tmp/output"
+ And the output port "from_nifi" is connected to the PutFile processor
+ And SSL properties are set in MiNiFi
+
+ And SSL is enabled in NiFi flow
+ And a GetFile processor with the "Input Directory" property set to "/tmp/input" in the "nifi" flow using the "nifi" engine
+ And a NiFi flow is sending data to an output port named "to-minifi-in-nifi" with the id of the port named "from_nifi" from the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile is connected to the to-minifi-in-nifi
+
+ When NiFi is started
+ And all instances start up
+
+ Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
+ And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
+
+ Scenario: A NiFi instance produces and transfers data to a MiNiFi instance via s2s using HTTP protocol with SSL config defined in minifi.properties
+ Given a file with the content "test" is present in "/tmp/input"
+ And a RemoteProcessGroup node with name "RemoteProcessGroup" is opened on "https://nifi-${feature_id}:8443/nifi" with transport protocol set to "HTTP"
+ And an output port with name "from_nifi" is created on the RemoteProcessGroup named "RemoteProcessGroup"
+ And "from_nifi" port is a start node
+ And a PutFile processor with the "Directory" property set to "/tmp/output"
+ And the output port "from_nifi" is connected to the PutFile processor
+ And SSL properties are set in MiNiFi
+
+ And SSL is enabled in NiFi flow
+ And a GetFile processor with the "Input Directory" property set to "/tmp/input" in the "nifi" flow using the "nifi" engine
+ And a NiFi flow is sending data to an output port named "to-minifi-in-nifi" with the id of the port named "from_nifi" from the RemoteProcessGroup named "RemoteProcessGroup"
+ And the "success" relationship of the GetFile is connected to the to-minifi-in-nifi
+
+ When NiFi is started
+ And all instances start up
+
Then a flowfile with the content "test" is placed in the monitored directory in less than 90 seconds
And the Minifi logs do not contain the following message: "ProcessSession rollback" after 1 seconds
diff --git a/docker/test/integration/features/steps/steps.py b/docker/test/integration/features/steps/steps.py
index e3ed90946..c7bb827d0 100644
--- a/docker/test/integration/features/steps/steps.py
+++ b/docker/test/integration/features/steps/steps.py
@@ -74,9 +74,7 @@ def step_impl(context, processor_type, processor_name, property_name, property_v
@given(
- "a {processor_type} processor with the name \"{processor_name}\" and the \"{property_name}\" property set to \"{property_value}\" in a \"{minifi_container_name}\" flow with engine \"{engine_name}\"")
-@given(
- "a {processor_type} processor with the name \"{processor_name}\" and the \"{property_name}\" property set to \"{property_value}\" in the \"{minifi_container_name}\" flow with engine \"{engine_name}\"")
+ "a {processor_type} processor with the name \"{processor_name}\" and the \"{property_name}\" property set to \"{property_value}\" in the \"{minifi_container_name}\" flow using the \"{engine_name}\" engine")
def step_impl(context, processor_type, processor_name, property_name, property_value, minifi_container_name, engine_name):
__create_processor(context, processor_type, processor_name, property_name, property_value, minifi_container_name, engine_name)
@@ -87,7 +85,7 @@ def step_impl(context, processor_type, property_name, property_value, minifi_con
__create_processor(context, processor_type, processor_type, property_name, property_value, minifi_container_name)
-@given("a {processor_type} processor the \"{property_name}\" property set to \"{property_value}\" in the \"{minifi_container_name}\" flow with engine \"{engine_name}\"")
+@given("a {processor_type} processor with the \"{property_name}\" property set to \"{property_value}\" in the \"{minifi_container_name}\" flow using the \"{engine_name}\" engine")
def step_impl(context, processor_type, property_name, property_value, minifi_container_name, engine_name):
__create_processor(context, processor_type, processor_type, property_name, property_value, minifi_container_name, engine_name)
@@ -107,7 +105,7 @@ def step_impl(context, processor_type, processor_name, minifi_container_name):
__create_processor(context, processor_type, processor_name, None, None, minifi_container_name)
-@given("a {processor_type} processor with the name \"{processor_name}\" in the \"{minifi_container_name}\" flow with engine \"{engine_name}\"")
+@given("a {processor_type} processor with the name \"{processor_name}\" in the \"{minifi_container_name}\" flow using the \"{engine_name}\" engine")
def step_impl(context, processor_type, processor_name, minifi_container_name, engine_name):
__create_processor(context, processor_type, processor_name, None, None, minifi_container_name, engine_name)
@@ -164,12 +162,17 @@ def step_impl(context):
""".format(minifi_container_name="minifi-cpp-flow", table=rendered_table))
-@given("a RemoteProcessGroup node opened on \"{address}\"")
-def step_impl(context, address):
- remote_process_group = RemoteProcessGroup(address, "RemoteProcessGroup")
+@given("a RemoteProcessGroup node with name \"{rpg_name}\" is opened on \"{address}\" with transport protocol set to \"{transport_protocol}\"")
+def step_impl(context, rpg_name, address, transport_protocol):
+ remote_process_group = RemoteProcessGroup(address, rpg_name, transport_protocol)
context.test.add_remote_process_group(remote_process_group)
+@given("a RemoteProcessGroup node with name \"{rpg_name}\" is opened on \"{address}\"")
+def step_impl(context, rpg_name, address):
+ context.execute_steps(f"given a RemoteProcessGroup node with name \"{rpg_name}\" is opened on \"{address}\" with transport protocol set to \"RAW\"")
+
+
@given("the \"{property_name}\" property of the {processor_name} processor is set to \"{property_value}\"")
def step_impl(context, property_name, processor_name, property_value):
processor = context.test.get_node_by_name(processor_name)
@@ -219,13 +222,25 @@ def step_impl(context):
context.test.get_node_by_name(row["processor name"]).set_property(row["property name"], row["property value"])
-@given("the \"{relationship}\" relationship of the {source_name} processor is connected to the input port on the {remote_process_group_name}")
-def step_impl(context, relationship, source_name, remote_process_group_name):
- source = context.test.get_node_by_name(source_name)
- remote_process_group = context.test.get_remote_process_group_by_name(remote_process_group_name)
- input_port_node = context.test.generate_input_port_for_remote_process_group(remote_process_group, "to_nifi")
+@given("an input port with name \"{port_name}\" is created on the RemoteProcessGroup named \"{rpg_name}\"")
+def step_impl(context, port_name, rpg_name):
+ remote_process_group = context.test.get_remote_process_group_by_name(rpg_name)
+ input_port_node = context.test.generate_input_port_for_remote_process_group(remote_process_group, port_name)
context.test.add_node(input_port_node)
- source.out_proc.connect({relationship: input_port_node})
+
+
+@given("an output port with name \"{port_name}\" is created on the RemoteProcessGroup named \"{rpg_name}\"")
+def step_impl(context, port_name, rpg_name):
+ remote_process_group = context.test.get_remote_process_group_by_name(rpg_name)
+ input_port_node = context.test.generate_output_port_for_remote_process_group(remote_process_group, port_name)
+ context.test.add_node(input_port_node)
+
+
+@given("the output port \"{port_name}\" is connected to the {destination_name} processor")
+def step_impl(context, port_name, destination_name):
+ destination = context.test.get_node_by_name(destination_name)
+ output_port_node = context.test.get_node_by_name(port_name)
+ output_port_node.out_proc.connect({"undefined": destination})
@given("the \"{relationship}\" relationship of the {source_name} is connected to the {destination_name}")
@@ -291,6 +306,7 @@ def step_impl(context, source_name, destination_name):
@given("\"{processor_name}\" processor is a start node")
+@given("\"{processor_name}\" port is a start node")
def step_impl(context, processor_name):
container = context.test.acquire_container(context=context, name="minifi-cpp-flow")
processor = context.test.get_or_create_node_by_name(processor_name)
@@ -298,11 +314,11 @@ def step_impl(context, processor_name):
# NiFi setups
-@given("a NiFi flow receiving data from a RemoteProcessGroup \"{source_name}\"")
-def step_impl(context, source_name):
- remote_process_group = context.test.get_remote_process_group_by_name("RemoteProcessGroup")
- source = context.test.generate_input_port_for_remote_process_group(remote_process_group, source_name)
- source.instance_id = context.test.get_node_by_name("to_nifi").instance_id
+@given("a NiFi flow is receiving data from the RemoteProcessGroup named \"{rpg_name}\" in an input port named \"{input_port_name}\" which has the same id as the port named \"{rpg_port_name}\"")
+def step_impl(context, input_port_name, rpg_port_name, rpg_name):
+ remote_process_group = context.test.get_remote_process_group_by_name(rpg_name)
+ source = context.test.generate_input_port_for_remote_process_group(remote_process_group, input_port_name)
+ source.instance_id = context.test.get_node_by_name(rpg_port_name).instance_id
context.test.add_node(source)
container = context.test.acquire_container(context=context, name='nifi', engine='nifi')
# Assume that the first node declared is primary unless specified otherwise
@@ -310,6 +326,14 @@ def step_impl(context, source_name):
container.add_start_node(source)
+@given("a NiFi flow is sending data to an output port named \"{port_name}\" with the id of the port named \"{rpg_port_name}\" from the RemoteProcessGroup named \"{rpg_name}\"")
+def step_impl(context, port_name, rpg_port_name, rpg_name):
+ remote_process_group = context.test.get_remote_process_group_by_name(rpg_name)
+ destination = context.test.generate_output_port_for_remote_process_group(remote_process_group, port_name)
+ destination.instance_id = context.test.get_node_by_name(rpg_port_name).instance_id
+ context.test.add_node(destination)
+
+
@given("a NiFi flow with the name \"{flow_name}\" is set up")
def step_impl(context, flow_name):
context.test.acquire_container(context=context, name=flow_name, engine='nifi')
@@ -1320,3 +1344,8 @@ def step_impl(context, service_name):
@given("a LlamaCpp model is present on the MiNiFi host")
def step_impl(context):
context.test.llama_model_is_downloaded_in_minifi()
+
+
+@when(u'NiFi is started')
+def step_impl(context):
+ context.test.start_nifi(context)
diff --git a/docker/test/integration/minifi/core/Connectable.py b/docker/test/integration/minifi/core/Connectable.py
index fb65c731c..dbf43544c 100644
--- a/docker/test/integration/minifi/core/Connectable.py
+++ b/docker/test/integration/minifi/core/Connectable.py
@@ -65,3 +65,6 @@ class Connectable(object):
def set_uuid(self, uuid):
self.uuid = uuid
+
+ def id_for_connection(self):
+ return self.uuid
diff --git a/docker/test/integration/minifi/core/InputPort.py b/docker/test/integration/minifi/core/InputPort.py
index cb9d60dc6..e37320a5f 100644
--- a/docker/test/integration/minifi/core/InputPort.py
+++ b/docker/test/integration/minifi/core/InputPort.py
@@ -25,3 +25,6 @@ class InputPort(Connectable):
self.properties = {}
if self.remote_process_group:
self.properties = self.remote_process_group.properties
+
+ def id_for_connection(self):
+ return self.instance_id
diff --git a/docker/test/integration/minifi/core/InputPort.py b/docker/test/integration/minifi/core/OutputPort.py
similarity index 87%
copy from docker/test/integration/minifi/core/InputPort.py
copy to docker/test/integration/minifi/core/OutputPort.py
index cb9d60dc6..c42255444 100644
--- a/docker/test/integration/minifi/core/InputPort.py
+++ b/docker/test/integration/minifi/core/OutputPort.py
@@ -17,11 +17,14 @@
from .Connectable import Connectable
-class InputPort(Connectable):
+class OutputPort(Connectable):
def __init__(self, name=None, remote_process_group=None):
- super(InputPort, self).__init__(name=name)
+ super(OutputPort, self).__init__(name=name)
self.remote_process_group = remote_process_group
self.properties = {}
if self.remote_process_group:
self.properties = self.remote_process_group.properties
+
+ def id_for_connection(self):
+ return self.instance_id
diff --git a/docker/test/integration/minifi/core/RemoteProcessGroup.py b/docker/test/integration/minifi/core/RemoteProcessGroup.py
index e3f54fa43..84ecc8e6f 100644
--- a/docker/test/integration/minifi/core/RemoteProcessGroup.py
+++ b/docker/test/integration/minifi/core/RemoteProcessGroup.py
@@ -18,7 +18,7 @@ import uuid
class RemoteProcessGroup(object):
- def __init__(self, url, name=None):
+ def __init__(self, url, name=None, transport_protocol="RAW"):
self.uuid = uuid.uuid4()
if name is None:
@@ -28,6 +28,7 @@ class RemoteProcessGroup(object):
self.url = url
self.properties = {}
+ self.transport_protocol = transport_protocol
def get_name(self):
return self.name
diff --git a/docker/test/integration/minifi/flow_serialization/Minifi_flow_json_serializer.py b/docker/test/integration/minifi/flow_serialization/Minifi_flow_json_serializer.py
index a100ae038..ed260cef3 100644
--- a/docker/test/integration/minifi/flow_serialization/Minifi_flow_json_serializer.py
+++ b/docker/test/integration/minifi/flow_serialization/Minifi_flow_json_serializer.py
@@ -19,6 +19,7 @@ import json
from ..core.Processor import Processor
from ..core.InputPort import InputPort
+from ..core.OutputPort import OutputPort
from ..core.Funnel import Funnel
@@ -32,7 +33,9 @@ class Minifi_flow_json_serializer:
'funnels': [],
'connections': [],
'remoteProcessGroups': [],
- 'controllerServices': []
+ 'controllerServices': [],
+ 'inputPorts': [],
+ 'outputPorts': []
}
}
visited = []
@@ -73,30 +76,72 @@ class Minifi_flow_json_serializer:
if isinstance(connectable, InputPort):
group = connectable.remote_process_group
- res_group = None
-
- for res_group_candidate in root['remoteProcessGroups']:
- assert isinstance(res_group_candidate, dict)
- if res_group_candidate['identifier'] == str(group.uuid):
- res_group = res_group_candidate
-
- if res_group is None:
- res_group = {
- 'name': group.name,
- 'identifier': str(group.uuid),
- 'targetUri': group.url,
- 'communicationsTimeout': '30 sec',
- 'yieldDuration': '3 sec',
- 'inputPorts': []
- }
-
- root['remoteProcessGroups'].append(res_group)
-
- res_group['inputPorts'].append({
- 'identifier': str(connectable.instance_id),
- 'name': connectable.name,
- 'properties': connectable.properties
- })
+ if group is None:
+ root['inputPorts'].append({
+ 'name': connectable_name,
+ 'identifier': str(connectable.instance_id),
+ 'properties': connectable.properties
+ })
+ else:
+ res_group = None
+
+ for res_group_candidate in root['remoteProcessGroups']:
+ assert isinstance(res_group_candidate, dict)
+ if res_group_candidate['identifier'] == str(group.uuid):
+ res_group = res_group_candidate
+
+ if res_group is None:
+ res_group = {
+ 'name': group.name,
+ 'identifier': str(group.uuid),
+ 'targetUri': group.url,
+ 'communicationsTimeout': '30 sec',
+ 'yieldDuration': '3 sec',
+ 'transportProtocol': group.transport_protocol,
+ 'inputPorts': []
+ }
+
+ root['remoteProcessGroups'].append(res_group)
+
+ res_group['inputPorts'].append({
+ 'identifier': str(connectable.instance_id),
+ 'name': connectable.name,
+ 'properties': connectable.properties
+ })
+
+ if isinstance(connectable, OutputPort):
+ group = connectable.remote_process_group
+ if group is None:
+ root['outputPorts'].append({
+ 'name': connectable_name,
+ 'identifier': str(connectable.instance_id),
+ 'properties': connectable.properties
+ })
+ else:
+ res_group = None
+
+ for res_group_candidate in root['remoteProcessGroups']:
+ assert isinstance(res_group_candidate, dict)
+ if res_group_candidate['identifier'] == str(group.uuid):
+ res_group = res_group_candidate
+
+ if res_group is None:
+ res_group = {
+ 'name': group.name,
+ 'identifier': str(group.uuid),
+ 'targetUri': group.url,
+ 'communicationsTimeout': '30 sec',
+ 'yieldDuration': '3 sec',
+ 'outputPorts': []
+ }
+
+ root['remoteProcessGroups'].append(res_group)
+
+ res_group['outputPorts'].append({
+ 'identifier': str(connectable.instance_id),
+ 'name': connectable.name,
+ 'properties': connectable.properties
+ })
if isinstance(connectable, Processor):
root['processors'].append({
@@ -134,8 +179,8 @@ class Minifi_flow_json_serializer:
for proc in conn_procs:
root['connections'].append({
'name': str(uuid.uuid4()),
- 'source': {'id': str(connectable.uuid)},
- 'destination': {'id': str(proc.uuid) if not isinstance(proc, InputPort) else str(proc.instance_id)}
+ 'source': {'id': str(connectable.id_for_connection())},
+ 'destination': {'id': str(proc.id_for_connection())}
})
if (all(str(connectable.uuid) != x['identifier'] for x in root['funnels'])):
root['connections'][-1]['selectedRelationships'] = [conn_name]
diff --git a/docker/test/integration/minifi/flow_serialization/Minifi_flow_yaml_serializer.py b/docker/test/integration/minifi/flow_serialization/Minifi_flow_yaml_serializer.py
index 14cbabc98..a2e1b6997 100644
--- a/docker/test/integration/minifi/flow_serialization/Minifi_flow_yaml_serializer.py
+++ b/docker/test/integration/minifi/flow_serialization/Minifi_flow_yaml_serializer.py
@@ -19,6 +19,7 @@ import yaml
from ..core.Processor import Processor
from ..core.InputPort import InputPort
+from ..core.OutputPort import OutputPort
from ..core.Funnel import Funnel
@@ -32,7 +33,9 @@ class Minifi_flow_yaml_serializer:
'Funnels': [],
'Connections': [],
'Remote Processing Groups': [],
- 'Controller Services': []
+ 'Controller Services': [],
+ 'Input Ports': [],
+ 'Output Ports': []
}
visited = []
@@ -73,31 +76,76 @@ class Minifi_flow_yaml_serializer:
if isinstance(connectable, InputPort):
group = connectable.remote_process_group
- res_group = None
-
- for res_group_candidate in res['Remote Processing Groups']:
- assert isinstance(res_group_candidate, dict)
- if res_group_candidate['id'] == str(group.uuid):
- res_group = res_group_candidate
-
- if res_group is None:
- res_group = {
- 'name': group.name,
- 'id': str(group.uuid),
- 'url': group.url,
- 'timeout': '30 sec',
- 'yield period': '3 sec',
- 'Input Ports': []
- }
-
- res['Remote Processing Groups'].append(res_group)
-
- res_group['Input Ports'].append({
- 'id': str(connectable.instance_id),
- 'name': connectable.name,
- 'max concurrent tasks': 1,
- 'Properties': connectable.properties
- })
+ if group is None:
+ res['Input Ports'].append({
+ 'name': connectable_name,
+ 'id': str(connectable.instance_id),
+ 'max concurrent tasks': 1,
+ 'Properties': connectable.properties
+ })
+ else:
+ res_group = None
+
+ for res_group_candidate in res['Remote Processing Groups']:
+ assert isinstance(res_group_candidate, dict)
+ if res_group_candidate['id'] == str(group.uuid):
+ res_group = res_group_candidate
+
+ if res_group is None:
+ res_group = {
+ 'name': group.name,
+ 'id': str(group.uuid),
+ 'url': group.url,
+ 'timeout': '30 sec',
+ 'yield period': '3 sec',
+ 'transport protocol': group.transport_protocol,
+ 'Input Ports': []
+ }
+
+ res['Remote Processing Groups'].append(res_group)
+
+ res_group['Input Ports'].append({
+ 'id': str(connectable.instance_id),
+ 'name': connectable.name,
+ 'max concurrent tasks': 1,
+ 'Properties': connectable.properties
+ })
+
+ if isinstance(connectable, OutputPort):
+ group = connectable.remote_process_group
+ if group is None:
+ res['Output Ports'].append({
+ 'name': connectable_name,
+ 'id': str(connectable.instance_id),
+ 'max concurrent tasks': 1,
+ 'Properties': connectable.properties
+ })
+ else:
+ res_group = None
+
+ for res_group_candidate in res['Remote Processing Groups']:
+ assert isinstance(res_group_candidate, dict)
+ if res_group_candidate['id'] == str(group.uuid):
+ res_group = res_group_candidate
+
+ if res_group is None:
+ res_group = {
+ 'name': group.name,
+ 'id': str(group.uuid),
+ 'url': group.url,
+ 'timeout': '30 sec',
+ 'yield period': '3 sec',
+ 'Output Ports': []
+ }
+
+ res['Remote Processing Groups'].append(res_group)
+
+ res_group['Output Ports'].append({
+ 'id': str(connectable.instance_id),
+ 'name': connectable.name,
+ 'max concurrent tasks': 1,
+ 'Properties': connectable.properties
+ })
if isinstance(connectable, Processor):
res['Processors'].append({
@@ -133,8 +181,8 @@ class Minifi_flow_yaml_serializer:
for proc in conn_procs:
res['Connections'].append({
'name': str(uuid.uuid4()),
- 'source id': str(connectable.uuid),
- 'destination id': str(proc.uuid) if not isinstance(proc, InputPort) else str(proc.instance_id),
+ 'source id': str(connectable.id_for_connection()),
+ 'destination id': str(proc.id_for_connection()),
'drop empty': ("true" if proc.drop_empty_flowfiles else "false")
})
if (all(str(connectable.uuid) != x['id'] for x in res['Funnels'])):
@@ -144,8 +192,8 @@ class Minifi_flow_yaml_serializer:
else:
res['Connections'].append({
'name': str(uuid.uuid4()),
- 'source id': str(connectable.uuid),
- 'destination id': str(conn_procs.uuid) if not isinstance(conn_procs, InputPort) else str(conn_procs.instance_id),
+ 'source id': str(connectable.id_for_connection()),
+ 'destination id': str(conn_procs.id_for_connection()),
'drop empty': ("true" if proc.drop_empty_flowfiles else "false")
})
if (all(str(connectable.uuid) != x['id'] for x in res['Funnels'])):
diff --git a/docker/test/integration/minifi/flow_serialization/Nifi_flow_json_serializer.py b/docker/test/integration/minifi/flow_serialization/Nifi_flow_json_serializer.py
index fa3f36ac6..4b78127ad 100644
--- a/docker/test/integration/minifi/flow_serialization/Nifi_flow_json_serializer.py
+++ b/docker/test/integration/minifi/flow_serialization/Nifi_flow_json_serializer.py
@@ -19,6 +19,7 @@ import json
from ..core.Processor import Processor
from ..core.InputPort import InputPort
+from ..core.OutputPort import OutputPort
class Nifi_flow_json_serializer:
@@ -103,6 +104,25 @@ class Nifi_flow_json_serializer:
"groupIdentifier": "9802c873-3322-3b60-a71d-732d02bd60f8"
})
+ if isinstance(connectable, OutputPort):
+ root['outputPorts'].append({
+ 'identifier': str(connectable.uuid),
+ 'instanceIdentifier': str(connectable.instance_id),
+ 'name': connectable_name_text,
+ "comments": "",
+ 'position': {
+ 'x': 0,
+ 'y': 0
+ },
+ 'type': 'OUTPUT_PORT',
+ 'concurrentlySchedulableTaskCount': 1,
+ 'scheduledState': 'RUNNING',
+ 'allowRemoteAccess': True,
+ 'portFunction': 'STANDARD',
+ 'componentType': 'OUTPUT_PORT',
+ "groupIdentifier": "9802c873-3322-3b60-a71d-732d02bd60f8"
+ })
+
if isinstance(connectable, Processor):
root['processors'].append({
"identifier": str(connectable.uuid),
@@ -175,6 +195,8 @@ class Nifi_flow_json_serializer:
source_type = 'PROCESSOR'
elif isinstance(connectable, InputPort):
source_type = 'INPUT_PORT'
+ elif isinstance(connectable, OutputPort):
+ source_type = 'OUTPUT_PORT'
else:
raise Exception('Unexpected source type: %s' % type(connectable))
@@ -184,6 +206,8 @@ class Nifi_flow_json_serializer:
dest_type = 'PROCESSOR'
elif isinstance(proc, InputPort):
dest_type = 'INPUT_PORT'
+ elif isinstance(proc, OutputPort):
+ dest_type = 'OUTPUT_PORT'
else:
raise Exception('Unexpected destination type: %s' % type(proc))
@@ -209,7 +233,7 @@ class Nifi_flow_json_serializer:
},
"labelIndex": 1,
"zIndex": 0,
- "selectedRelationships": [conn_name] if not isinstance(connectable, InputPort) else [""],
+ "selectedRelationships": [conn_name] if not isinstance(connectable, InputPort) and not isinstance(connectable, OutputPort) else [""],
"backPressureObjectThreshold": 10,
"backPressureDataSizeThreshold": "50 B",
"flowFileExpiration": "0 sec",
diff --git a/extensions/standard-processors/tests/unit/FlowJsonTests.cpp b/extensions/standard-processors/tests/unit/FlowJsonTests.cpp
index 05cccb361..4fe379fdf 100644
--- a/extensions/standard-processors/tests/unit/FlowJsonTests.cpp
+++ b/extensions/standard-processors/tests/unit/FlowJsonTests.cpp
@@ -162,14 +162,14 @@ TEST_CASE("NiFi flow json format is correctly parsed") {
CHECK(funnel->getUUIDStr() == "00000000-0000-0000-0000-000000000010");
// verify RPG input port
- TypedProcessorWrapper<minifi::RemoteProcessorGroupPort> port = flow->findProcessorByName("AmazingInputPort");
+ TypedProcessorWrapper<minifi::RemoteProcessGroupPort> port = flow->findProcessorByName("AmazingInputPort");
REQUIRE(port);
CHECK(port->getUUIDStr() == "00000000-0000-0000-0000-000000000003");
CHECK(port->getMaxConcurrentTasks() == 7);
CHECK(port.get().getInstances().size() == 1);
- CHECK(port.get().getInstances().front().host_ == "localhost");
- CHECK(port.get().getInstances().front().port_ == 8090);
- CHECK(port.get().getInstances().front().protocol_ == "https://");
+ CHECK(port.get().getInstances().front().host == "localhost");
+ CHECK(port.get().getInstances().front().port == 8090);
+ CHECK(port.get().getInstances().front().protocol == "https://");
CHECK(port->getProperty("Port UUID") == "00000000-0000-0000-0000-000000000005");
// verify connection
@@ -821,7 +821,6 @@ TEST_CASE("Dynamic properties can use parameters") {
REQUIRE(values->size() == 2);
CHECK((*values)[0] == "value1");
CHECK((*values)[1] == "value2");
- std::string value;
REQUIRE("value1" == proc->getDynamicProperty("My Dynamic Property"));
}
@@ -965,7 +964,13 @@ TEST_CASE("NiFi flow json can use alternative targetUris field") {
"identifier": "00000000-0000-0000-0000-000000000003",
"name": "AmazingInputPort",
"targetId": "00000000-0000-0000-0000-000000000005",
- "concurrentlySchedulableTaskCount": 7
+ "concurrentlySchedulableTaskCount": 7,
+ "useCompression": true,
+ "batchSize": {
+ "size": "10 B",
+ "count": "3",
+ "duration": "5 sec"
+ }
}]
}],
"parameterContextName": "my-context"
@@ -991,7 +996,13 @@ TEST_CASE("NiFi flow json can use alternative targetUris field") {
"identifier": "00000000-0000-0000-0000-000000000003",
"name": "AmazingInputPort",
"targetId": "00000000-0000-0000-0000-000000000005",
- "concurrentlySchedulableTaskCount": 7
+ "concurrentlySchedulableTaskCount": 7,
+ "useCompression": true,
+ "batchSize": {
+ "size": "10 B",
+ "count": "3",
+ "duration": "5 sec"
+ }
}]
}],
"parameterContextName": "my-context"
@@ -1018,7 +1029,13 @@ TEST_CASE("NiFi flow json can use alternative targetUris field") {
"identifier": "00000000-0000-0000-0000-000000000003",
"name": "AmazingInputPort",
"targetId": "00000000-0000-0000-0000-000000000005",
- "concurrentlySchedulableTaskCount": 7
+ "concurrentlySchedulableTaskCount": 7,
+ "useCompression": true,
+ "batchSize": {
+ "size": "10 B",
+ "count": "3",
+ "duration": "5 sec"
+ }
}]
}],
"parameterContextName": "my-context"
@@ -1031,15 +1048,19 @@ TEST_CASE("NiFi flow json can use alternative targetUris field") {
REQUIRE(flow);
// verify RPG input port
- TypedProcessorWrapper<minifi::RemoteProcessorGroupPort> port = flow->findProcessorByName("AmazingInputPort");
+ TypedProcessorWrapper<minifi::RemoteProcessGroupPort> port = flow->findProcessorByName("AmazingInputPort");
REQUIRE(port);
- CHECK(port.get().getUUIDStr() == "00000000-0000-0000-0000-000000000003");
+ CHECK(port->getUUIDStr() == "00000000-0000-0000-0000-000000000003");
CHECK(port->getMaxConcurrentTasks() == 7);
+ CHECK(port.get().getUseCompression() == true);
+ CHECK(port.get().getBatchSize().value() == 10);
+ CHECK(port.get().getBatchCount().value() == 3);
+ CHECK(port.get().getBatchDuration().value() == std::chrono::seconds(5));
if (target_uri_valid) {
CHECK(port.get().getInstances().size() == 1);
- CHECK(port.get().getInstances().front().host_ == "localhost");
- CHECK(port.get().getInstances().front().port_ == 8090);
- CHECK(port.get().getInstances().front().protocol_ == "https://");
+ CHECK(port.get().getInstances().front().host == "localhost");
+ CHECK(port.get().getInstances().front().port == 8090);
+ CHECK(port.get().getInstances().front().protocol == "https://");
} else {
CHECK(port.get().getInstances().empty());
}
@@ -1786,4 +1807,69 @@ TEST_CASE("Parameter context names cannot conflict with parameter provider gener
"with no parameter provider or generated by other parameter provider");
}
+TEST_CASE("Output port can also be used in RPG") {
+ ConfigurationTestController test_controller;
+
+ core::flow::AdaptiveConfiguration config(test_controller.getContext());
+
+ static const std::string CONFIG_JSON =
+ R"(
+{
+ "rootGroup": {
+ "name": "MiNiFi Flow",
+ "processors": [{
+ "identifier": "00000000-0000-0000-0000-000000000001",
+ "name": "PutFile",
+ "type": "org.apache.nifi.processors.standard.PutFile",
+ "schedulingStrategy": "Event_DRIVEN",
+ "autoTerminatedRelationships": ["success"],
+ "properties": {}
+ }],
+ "connections": [{
+ "identifier": "00000000-0000-0000-0000-000000000008",
+ "name": "S2SToRPG",
+ "source": {
+ "id": "00000000-0000-0000-0000-000000000003",
+ "name": "AmazingOutputPort"
+ },
+ "destination": {
+ "id": "00000000-0000-0000-0000-000000000001",
+ "name": "PutFile"
+ },
+ "selectedRelationships": [""]
+ }],
+ "remoteProcessGroups": [{
+ "name": "NiFi Flow",
+ "targetUri": "https://localhost:8090/nifi",
+ "communicationsTimeout": "19 sec",
+ "outputPorts": [{
+ "identifier": "00000000-0000-0000-0000-000000000003",
+ "name": "AmazingOutputPort",
+ "targetId": "00000000-0000-0000-0000-000000000005",
+ "concurrentlySchedulableTaskCount": 7,
+ "useCompression": true,
+ "batchSize": {
+ "size": "10 B",
+ "count": "3",
+ "duration": "5 sec"
+ }
+ }]
+ }],
+ "parameterContextName": "my-context"
+ }
+})";
+
+ std::unique_ptr<core::ProcessGroup> flow = config.getRootFromPayload(CONFIG_JSON);
+ REQUIRE(flow);
+
+ TypedProcessorWrapper<minifi::RemoteProcessGroupPort> port = flow->findProcessorByName("AmazingOutputPort");
+ REQUIRE(port);
+ CHECK(port->getUUIDStr() == "00000000-0000-0000-0000-000000000003");
+ CHECK(port.get().getUseCompression() == true);
+ CHECK(port.get().getBatchSize().value() == 10);
+ CHECK(port.get().getBatchCount().value() == 3);
+ CHECK(port.get().getBatchDuration().value() == std::chrono::seconds(5));
+ CHECK(port.get().getTimeout().value() == std::chrono::seconds(19));
+}
+
} // namespace org::apache::nifi::minifi::test
diff --git a/extensions/standard-processors/tests/unit/ProcessGroupTestUtils.h b/extensions/standard-processors/tests/unit/ProcessGroupTestUtils.h
index b74d6b261..a473471cf 100644
--- a/extensions/standard-processors/tests/unit/ProcessGroupTestUtils.h
+++ b/extensions/standard-processors/tests/unit/ProcessGroupTestUtils.h
@@ -378,7 +378,7 @@ void verifyProcessGroup(core::ProcessGroup& group, const Group& pattern) {
const auto& input_ports = ProcessGroupTestAccessor::get_processors_(*rpg);
REQUIRE(input_ports.size() == expected.input_ports.size());
for (auto& expected_input_port : expected.input_ports) {
- TypedProcessorWrapper<minifi::RemoteProcessorGroupPort> input_port = findByName(input_ports, expected_input_port.name);
+ TypedProcessorWrapper<minifi::RemoteProcessGroupPort> input_port = findByName(input_ports, expected_input_port.name);
REQUIRE(input_port);
REQUIRE(input_port->getName() == expected_input_port.name);
}
diff --git a/extensions/standard-processors/tests/unit/ProcessorTests.cpp b/extensions/standard-processors/tests/unit/ProcessorTests.cpp
index afec8d9f2..727af353b 100644
--- a/extensions/standard-processors/tests/unit/ProcessorTests.cpp
+++ b/extensions/standard-processors/tests/unit/ProcessorTests.cpp
@@ -532,7 +532,7 @@ TEST_CASE("TestEmptyContent", "[emptyContent]") {
*/
void testRPGBypass(const std::string &host, const std::string &port, bool has_error = true) {
TestController testController;
- LogTestController::getInstance().setTrace<minifi::RemoteProcessorGroupPort>();
+ LogTestController::getInstance().setTrace<minifi::RemoteProcessGroupPort>();
LogTestController::getInstance().setTrace<minifi::core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
@@ -543,10 +543,10 @@ void testRPGBypass(const std::string &host, const std::string &port, bool has_er
std::shared_ptr<core::Repository> test_repo = std::make_shared<TestRepository>();
std::shared_ptr<TestRepository> repo = std::dynamic_pointer_cast<TestRepository>(test_repo);
- auto rpg = minifi::test::utils::make_custom_processor<minifi::RemoteProcessorGroupPort>("rpg", "http://localhost:8989/nifi", configuration, utils::IdGenerator::getIdGenerator()->generate());
+ auto rpg = minifi::test::utils::make_custom_processor<minifi::RemoteProcessGroupPort>("rpg", "http://localhost:8989/nifi", configuration, utils::IdGenerator::getIdGenerator()->generate());
rpg->initialize();
- REQUIRE(rpg->setProperty(minifi::RemoteProcessorGroupPort::hostName.name, host));
- REQUIRE(rpg->setProperty(minifi::RemoteProcessorGroupPort::port.name, port));
+ REQUIRE(rpg->setProperty(minifi::RemoteProcessGroupPort::hostName.name, host));
+ REQUIRE(rpg->setProperty(minifi::RemoteProcessGroupPort::port.name, port));
auto context = std::make_shared<core::ProcessContextImpl>(*rpg, nullptr, repo, repo, content_repo);
auto psf = std::make_shared<core::ProcessSessionFactoryImpl>(context);
if (has_error) {
diff --git a/extensions/standard-processors/tests/unit/YamlConfigurationTests.cpp b/extensions/standard-processors/tests/unit/YamlConfigurationTests.cpp
index 53c6118c3..c36fbcffa 100644
--- a/extensions/standard-processors/tests/unit/YamlConfigurationTests.cpp
+++ b/extensions/standard-processors/tests/unit/YamlConfigurationTests.cpp
@@ -223,7 +223,7 @@ Provenance Reporting:
}
}
-TEST_CASE("Test YAML v3 Invalid Type", "[YamlConfiguration3]") {
+TEST_CASE("Test YAML v3 Invalid Type", "[YamlConfiguration]") {
ConfigurationTestController test_controller;
core::YamlConfiguration yamlConfig(test_controller.getContext());
@@ -343,7 +343,7 @@ NiFi Properties Overrides: {}
REQUIRE_THROWS_AS(yamlConfig.getRootFromPayload(TEST_CONFIG_YAML), minifi::Exception);
}
-TEST_CASE("Test YAML v3 Config Processing", "[YamlConfiguration3]") {
+TEST_CASE("Test YAML v3 Config Processing", "[YamlConfiguration]") {
ConfigurationTestController test_controller;
core::YamlConfiguration yamlConfig(test_controller.getContext());
@@ -437,7 +437,7 @@ Remote Process Groups:
name: ''
url: http://localhost:8080/nifi
comment: ''
- timeout: 30 sec
+ timeout: 20 sec
yield period: 10 sec
transport protocol: RAW
proxy host: ''
@@ -446,16 +446,15 @@ Remote Process Groups:
proxy password: ''
local network interface: ''
Input Ports:
- - id: aca664f8-0158-1000-a139-92485891d349
- name: test2
- comment: ''
- max concurrent tasks: 1
- use compression: false
- id: ac0e798c-0158-1000-0588-cda9b944e011
- name: test
+ name: AmazingInputPort
comment: ''
max concurrent tasks: 1
- use compression: false
+ use compression: true
+ batch size:
+ size: 10 B
+ count: 3
+ duration: 5 sec
Output Ports: []
NiFi Properties Overrides: {}
)";
@@ -485,6 +484,15 @@ NiFi Properties Overrides: {}
REQUIRE(it.second->getSource());
REQUIRE(0s == it.second->getFlowExpirationDuration());
}
+
+ TypedProcessorWrapper<minifi::RemoteProcessGroupPort> port = rootFlowConfig->findProcessorByName("AmazingInputPort");
+ REQUIRE(port);
+ CHECK(port->getUUIDStr() == "ac0e798c-0158-1000-0588-cda9b944e011");
+ CHECK(port.get().getUseCompression() == true);
+ CHECK(port.get().getBatchSize().value() == 10);
+ CHECK(port.get().getBatchCount().value() == 3);
+ CHECK(port.get().getBatchDuration().value() == std::chrono::seconds(5));
+ CHECK(port.get().getTimeout().value() == std::chrono::seconds(20));
}
TEST_CASE("Test Dynamic Unsupported", "[YamlConfigurationDynamicUnsupported]") {
@@ -2108,7 +2116,6 @@ Parameter Context Name: c-context
REQUIRE(flow);
auto* proc = flow->findProcessorByName("DummyProcessor");
REQUIRE(proc);
- std::string value;
REQUIRE("1" == proc->getDynamicProperty("My A Property"));
REQUIRE("3" == proc->getDynamicProperty("My B Property"));
REQUIRE("5" == proc->getDynamicProperty("My C Property"));
@@ -2403,4 +2410,61 @@ Processors:
}
}
+TEST_CASE("Output port can also be used in RPG", "[YamlConfiguration]") {
+ ConfigurationTestController test_controller;
+
+ core::YamlConfiguration yamlConfig(test_controller.getContext());
+
+ static const std::string TEST_CONFIG_YAML =
+ R"(
+MiNiFi Config Version: 3
+Flow Controller:
+ name: Simple RPG To PutFile
+ comment: ''
+Processors:
+- id: b0c04f28-0158-1000-0000-000000000000
+ name: PutFile
+ class: org.apache.nifi.processors.standard.PutFile
+ max concurrent tasks: 1
+ scheduling strategy: EVENT_DRIVEN
+ auto-terminated relationships list: []
+ Properties: []
+
+Connections:
+- id: b0c0c3cc-0158-1000-0000-000000000000
+ name: ac0e798c-0158-1000-0588-cda9b944e011/success/PutFile
+ source id: ac0e798c-0158-1000-0588-cda9b944e011
+ destination id: b0c04f28-0158-1000-0000-000000000000
+Remote Process Groups:
+- id: b0c09ff0-0158-1000-0000-000000000000
+ name: ''
+ url: http://localhost:8080/nifi
+ comment: ''
+ timeout: 20 sec
+ yield period: 10 sec
+ transport protocol: RAW
+ Output Ports:
+ - id: ac0e798c-0158-1000-0588-cda9b944e011
+ name: AmazingOutputPort
+ max concurrent tasks: 1
+ use compression: true
+ batch size:
+ size: 10 B
+ count: 3
+ duration: 5 sec
+ Input Ports: []
+NiFi Properties Overrides: {}
+ )";
+ std::unique_ptr<core::ProcessGroup> rootFlowConfig = yamlConfig.getRootFromPayload(TEST_CONFIG_YAML);
+
+ TypedProcessorWrapper<minifi::RemoteProcessGroupPort> port = rootFlowConfig->findProcessorByName("AmazingOutputPort");
+ REQUIRE(port);
+ CHECK(port->getUUIDStr() == "ac0e798c-0158-1000-0588-cda9b944e011");
+ CHECK(port.get().getUseCompression() == true);
+ CHECK(port.get().getBatchSize().value() == 10);
+ CHECK(port.get().getBatchCount().value() == 3);
+ CHECK(port.get().getBatchDuration().value() == std::chrono::seconds(5));
+ CHECK(port.get().getTimeout().value() == std::chrono::seconds(20));
+}
+
} // namespace org::apache::nifi::minifi::test
diff --git a/libminifi/include/RemoteProcessorGroupPort.h b/libminifi/include/RemoteProcessGroupPort.h
similarity index 59%
rename from libminifi/include/RemoteProcessorGroupPort.h
rename to libminifi/include/RemoteProcessGroupPort.h
index 7374aad43..1f4538c00 100644
--- a/libminifi/include/RemoteProcessorGroupPort.h
+++ b/libminifi/include/RemoteProcessGroupPort.h
@@ -1,6 +1,6 @@
/**
- * @file RemoteProcessorGroupPort.h
- * RemoteProcessorGroupPort class declaration
+ * @file RemoteProcessGroupPort.h
+ * RemoteProcessGroupPort class declaration
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -42,57 +42,26 @@
namespace org::apache::nifi::minifi {
-/**
- * Count down latch implementation that's used across
- * all threads of the RPG. This is okay since the latch increments
- * and decrements based on its construction. Using RAII we should
- * never have the concern of thread safety.
- */
-class RPGLatch {
- public:
- RPGLatch(bool increment = true) { // NOLINT
- static std::atomic<int> latch_count(0);
- count = &latch_count;
- if (increment)
- count++;
- }
-
- ~RPGLatch() {
- count--;
- }
-
- int getCount() {
- return *count;
- }
-
- private:
- std::atomic<int> *count;
-};
-
struct RPG {
- std::string host_;
- int port_;
- std::string protocol_;
+ std::string host;
+ int port;
+ std::string protocol;
};
-class RemoteProcessorGroupPort : public core::ProcessorImpl {
+class RemoteProcessGroupPort : public core::ProcessorImpl {
public:
- RemoteProcessorGroupPort(std::string_view name, std::string url, std::shared_ptr<Configure> configure, const utils::Identifier &uuid, std::shared_ptr<core::logging::Logger> logger = nullptr)
- : core::ProcessorImpl({.uuid = uuid, .name = std::string{name}, .logger = logger ? logger : core::logging::LoggerFactory<RemoteProcessorGroupPort>::getLogger(uuid)}),
+ RemoteProcessGroupPort(std::string_view name, std::string url, std::shared_ptr<Configure> configure, const utils::Identifier &uuid, std::shared_ptr<core::logging::Logger> logger = nullptr)
+ : core::ProcessorImpl({.uuid = uuid, .name = std::string{name}, .logger = logger ? logger : core::logging::LoggerFactory<RemoteProcessGroupPort>::getLogger(uuid)}),
configure_(std::move(configure)),
- direction_(sitetosite::SEND),
+ direction_(sitetosite::TransferDirection::SEND),
transmitting_(false),
- timeout_(0),
- bypass_rest_api_(false),
- ssl_service(nullptr) {
- client_type_ = sitetosite::CLIENT_TYPE::RAW;
- protocol_uuid_ = uuid;
- site2site_secure_ = false;
- peer_index_ = -1;
+ protocol_uuid_(uuid),
+ client_type_(sitetosite::ClientType::RAW),
+ peer_index_(-1) {
// REST API port and host
setURL(std::move(url));
}
- virtual ~RemoteProcessorGroupPort() = default;
+ virtual ~RemoteProcessGroupPort() = default;
MINIFIAPI static constexpr auto hostName = core::PropertyDefinitionBuilder<>::createProperty("Host Name")
.withDescription("Remote Host Name.")
@@ -121,9 +90,8 @@ class RemoteProcessorGroupPort : public core::ProcessorImpl {
idleTimeout
});
-
- MINIFIAPI static constexpr auto relation = core::RelationshipDefinition{"", ""};
- MINIFIAPI static constexpr auto Relationships = std::array{relation};
+ MINIFIAPI static constexpr auto DefaultRelationship = core::RelationshipDefinition{"undefined", ""};
+ MINIFIAPI static constexpr auto Relationships = std::array{DefaultRelationship};
MINIFIAPI static constexpr bool SupportsDynamicProperties = false;
MINIFIAPI static constexpr bool SupportsDynamicRelationships = false;
@@ -138,14 +106,21 @@ class RemoteProcessorGroupPort : public core::ProcessorImpl {
void setDirection(sitetosite::TransferDirection direction) {
direction_ = direction;
- if (direction_ == sitetosite::RECEIVE)
- this->setTriggerWhenEmpty(true);
+ if (direction_ == sitetosite::TransferDirection::RECEIVE) {
+ setTriggerWhenEmpty(true);
+ } else {
+ setTriggerWhenEmpty(false);
+ }
}
- void setTimeout(uint64_t timeout) {
+ void setTimeout(std::chrono::milliseconds timeout) {
timeout_ = timeout;
}
+ [[nodiscard]] std::optional<std::chrono::milliseconds> getTimeout() const {
+ return timeout_;
+ }
+
void setTransmitting(bool val) {
transmitting_ = val;
}
@@ -154,102 +129,90 @@ class RemoteProcessorGroupPort : public core::ProcessorImpl {
local_network_interface_ = ifc;
}
- std::string getInterface() {
- return local_network_interface_;
- }
-
- /**
- * Sets the url. Supports a CSV
- */
- void setURL(std::string val) {
- auto urls = utils::string::split(val, ",");
- for (const auto& url : urls) {
- http::URL parsed_url{utils::string::trim(url)};
- if (parsed_url.isValid()) {
- logger_->log_debug("Parsed RPG URL '{}' -> '{}'", url, parsed_url.hostPort());
- nifi_instances_.push_back({parsed_url.host(), parsed_url.port(), parsed_url.protocol()});
- } else {
- logger_->log_error("Could not parse RPG URL '{}'", url);
- }
- }
- }
+ void setURL(const std::string& val);
- std::vector<RPG> getInstances() const {
+ [[nodiscard]] std::vector<RPG> getInstances() const {
return nifi_instances_;
}
void setHTTPProxy(const http::HTTPProxy &proxy) {
- this->proxy_ = proxy;
+ proxy_ = proxy;
}
- http::HTTPProxy getHTTPProxy() {
- return this->proxy_;
- }
- // refresh remoteSite2SiteInfo via nifi rest api
- std::pair<std::string, int> refreshRemoteSite2SiteInfo();
- // refresh site2site peer list
- void refreshPeerList();
+ [[nodiscard]] http::HTTPProxy getHTTPProxy() const {
+ return proxy_;
+ }
void notifyStop() override;
void enableHTTP() {
- client_type_ = sitetosite::HTTP;
+ client_type_ = sitetosite::ClientType::HTTP;
}
- protected:
- /**
- * Non static in case anything is loaded when this object is re-scheduled
- */
- bool is_http_disabled() {
- auto ptr = core::ClassLoader::getDefaultClassLoader().instantiateRaw("HTTPClient", "HTTPClient");
- if (ptr != nullptr) {
- delete ptr;
- return false;
- } else {
- return true;
- }
+ void setUseCompression(bool use_compression) {
+ use_compression_ = use_compression;
}
- std::unique_ptr<sitetosite::SiteToSiteClient> getNextProtocol(bool create);
+ [[nodiscard]] bool getUseCompression() const {
+ return use_compression_;
+ }
+
+ void setBatchCount(uint64_t count) {
+ batch_count_ = count;
+ }
+
+ [[nodiscard]] std::optional<uint64_t> getBatchCount() const {
+ return batch_count_;
+ }
+
+ void setBatchSize(uint64_t size) {
+ batch_size_ = size;
+ }
+
+ [[nodiscard]] std::optional<uint64_t> getBatchSize() const {
+ return batch_size_;
+ }
+
+ void setBatchDuration(std::chrono::milliseconds duration) {
+ batch_duration_ = duration;
+ }
+
+ [[nodiscard]] std::optional<std::chrono::milliseconds> getBatchDuration() const {
+ return batch_duration_;
+ }
+
+ protected:
+ std::optional<std::pair<std::string, uint16_t>> refreshRemoteSiteToSiteInfo();
+ void refreshPeerList();
+ std::unique_ptr<sitetosite::SiteToSiteClient> getNextProtocol();
void returnProtocol(core::ProcessContext& context, std::unique_ptr<sitetosite::SiteToSiteClient> protocol);
moodycamel::ConcurrentQueue<std::unique_ptr<sitetosite::SiteToSiteClient>> available_protocols_;
-
std::shared_ptr<Configure> configure_;
- // Transaction Direction
sitetosite::TransferDirection direction_;
- // Transmitting
std::atomic<bool> transmitting_;
- // timeout
- uint64_t timeout_;
- // local network interface
+ std::optional<std::chrono::milliseconds> timeout_;
std::string local_network_interface_;
-
utils::Identifier protocol_uuid_;
-
- std::chrono::milliseconds idle_timeout_ = std::chrono::seconds(15);
-
- // rest API end point info
- std::vector<struct RPG> nifi_instances_;
-
- // http proxy
+ std::chrono::milliseconds idle_timeout_ = 15s;
+ std::vector<RPG> nifi_instances_;
http::HTTPProxy proxy_;
-
- bool bypass_rest_api_;
-
- sitetosite::CLIENT_TYPE client_type_;
-
- // Remote Site2Site Info
- bool site2site_secure_;
+ sitetosite::ClientType client_type_;
std::vector<sitetosite::PeerStatus> peers_;
- std::atomic<int> peer_index_;
+ int64_t peer_index_;
std::mutex peer_mutex_;
- std::string rest_user_name_;
- std::string rest_password_;
-
- std::shared_ptr<controllers::SSLContextServiceInterface> ssl_service;
+ std::shared_ptr<controllers::SSLContextServiceInterface> ssl_service_;
+ bool use_compression_{false};
+ std::optional<uint64_t> batch_count_;
+ std::optional<uint64_t> batch_size_;
+ std::optional<std::chrono::milliseconds> batch_duration_;
private:
+ gsl::not_null<std::unique_ptr<sitetosite::SiteToSiteClient>> initializeProtocol(sitetosite::SiteToSiteClientConfiguration& config) const;
+ [[nodiscard]] std::optional<std::string> getRestApiToken(const RPG& nifi) const;
+ std::optional<std::pair<std::string, uint16_t>> parseSiteToSiteDataFromControllerConfig(const RPG& nifi, const std::string& controller) const;
+ std::optional<std::pair<std::string, uint16_t>> tryRefreshSiteToSiteInstance(RPG nifi) const;
+
static const char* RPG_SSL_CONTEXT_SERVICE_NAME;
};
diff --git a/libminifi/include/core/FlowConfiguration.h b/libminifi/include/core/FlowConfiguration.h
index 652674651..7347c12e6 100644
--- a/libminifi/include/core/FlowConfiguration.h
+++ b/libminifi/include/core/FlowConfiguration.h
@@ -27,7 +27,7 @@
#include "core/Core.h"
#include "Connection.h"
-#include "RemoteProcessorGroupPort.h"
+#include "RemoteProcessGroupPort.h"
#include "core/controller/ControllerServiceNode.h"
#include "core/controller/StandardControllerServiceProvider.h"
#include "provenance/Provenance.h"
diff --git a/libminifi/include/core/flow/FlowSchema.h b/libminifi/include/core/flow/FlowSchema.h
index ebbb2ab26..1949c8dd2 100644
--- a/libminifi/include/core/flow/FlowSchema.h
+++ b/libminifi/include/core/flow/FlowSchema.h
@@ -80,6 +80,11 @@ struct FlowSchema {
Keys rpg_output_ports;
Keys rpg_port_properties;
Keys rpg_port_target_id;
+ Keys rpg_port_use_compression;
+ Keys rpg_port_batch_size;
+ Keys rpg_port_batch_size_count;
+ Keys rpg_port_batch_size_size;
+ Keys rpg_port_batch_size_duration;
Keys parameter_contexts;
Keys parameters;
diff --git a/libminifi/include/core/flow/StructuredConfiguration.h b/libminifi/include/core/flow/StructuredConfiguration.h
index d452f1019..95da310ea 100644
--- a/libminifi/include/core/flow/StructuredConfiguration.h
+++ b/libminifi/include/core/flow/StructuredConfiguration.h
@@ -88,7 +88,7 @@ class StructuredConfiguration : public FlowConfiguration {
/**
* Parses a port from its corresponding config node and adds
* it to a parent ProcessGroup. The port_node argument must point
- * to a Node containing the port configuration. A RemoteProcessorGroupPort
+ * to a Node containing the port configuration. A RemoteProcessGroupPort
* object will be created a added to the parent ProcessGroup specified
* by the parent argument.
*
diff --git a/libminifi/include/core/flow/StructuredConnectionParser.h b/libminifi/include/core/flow/StructuredConnectionParser.h
index 0fed50452..730fade25 100644
--- a/libminifi/include/core/flow/StructuredConnectionParser.h
+++ b/libminifi/include/core/flow/StructuredConnectionParser.h
@@ -56,7 +56,7 @@ class StructuredConnectionParser {
private:
void addNewRelationshipToConnection(std::string_view relationship_name, minifi::Connection& connection) const;
- void addFunnelRelationshipToConnection(minifi::Connection& connection) const;
+ void addFunnelOrPortRelationshipToConnection(minifi::Connection& connection) const;
const Node& connectionNode_;
const std::string& name_;
diff --git a/libminifi/include/core/reporting/SiteToSiteProvenanceReportingTask.h b/libminifi/include/core/reporting/SiteToSiteProvenanceReportingTask.h
index dea93e616..24d467058 100644
--- a/libminifi/include/core/reporting/SiteToSiteProvenanceReportingTask.h
+++ b/libminifi/include/core/reporting/SiteToSiteProvenanceReportingTask.h
@@ -27,15 +27,15 @@
#include "FlowFileRecord.h"
#include "core/Processor.h"
#include "core/ProcessSession.h"
-#include "RemoteProcessorGroupPort.h"
+#include "RemoteProcessGroupPort.h"
#include "core/logging/LoggerFactory.h"
namespace org::apache::nifi::minifi::core::reporting {
-class SiteToSiteProvenanceReportingTask : public minifi::RemoteProcessorGroupPort {
+class SiteToSiteProvenanceReportingTask : public minifi::RemoteProcessGroupPort {
public:
explicit SiteToSiteProvenanceReportingTask(std::shared_ptr<Configure> configure)
- : minifi::RemoteProcessorGroupPort(ReportTaskName, "", std::move(configure),
+ : minifi::RemoteProcessGroupPort(ReportTaskName, "", std::move(configure),
utils::IdGenerator::getIdGenerator()->generate(), logging::LoggerFactory<SiteToSiteProvenanceReportingTask>::getLogger()) {
this->setTriggerWhenEmpty(true);
batch_size_ = 100;
diff --git a/libminifi/include/sitetosite/HTTPProtocol.h b/libminifi/include/sitetosite/HTTPProtocol.h
deleted file mode 100644
index 342078d29..000000000
--- a/libminifi/include/sitetosite/HTTPProtocol.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#pragma once
-
-#include <map>
-#include <memory>
-#include <optional>
-#include <string>
-#include <utility>
-#include <vector>
-#include "HTTPTransaction.h"
-#include "sitetosite/SiteToSite.h"
-#include "sitetosite/SiteToSiteClient.h"
-#include "core/logging/LoggerConfiguration.h"
-#include "core/ProcessContext.h"
-#include "core/ProcessSession.h"
-#include "sitetosite/Peer.h"
-#include "utils/Id.h"
-
-namespace org::apache::nifi::minifi::sitetosite {
-
-class HttpSiteToSiteClient : public sitetosite::SiteToSiteClient {
- static constexpr char const* PROTOCOL_VERSION_HEADER = "x-nifi-site-to-site-protocol-version";
-
- public:
- explicit HttpSiteToSiteClient(std::string /*name*/, const utils::Identifier& /*uuid*/ = {})
- : SiteToSiteClient(),
- current_code(sitetosite::UNRECOGNIZED_RESPONSE_CODE) {
- peer_state_ = sitetosite::READY;
- }
-
- explicit HttpSiteToSiteClient(std::unique_ptr<sitetosite::SiteToSitePeer> peer)
- : SiteToSiteClient(),
- current_code(sitetosite::UNRECOGNIZED_RESPONSE_CODE) {
- peer_ = std::move(peer);
- peer_state_ = sitetosite::READY;
- }
- ~HttpSiteToSiteClient() override = default;
-
- MINIFIAPI static constexpr auto Properties = std::array<core::PropertyReference, 0>{};
- MINIFIAPI static constexpr bool SupportsDynamicProperties = false;
- MINIFIAPI static constexpr bool SupportsDynamicRelationships = false;
-
- void setPeer(std::unique_ptr<sitetosite::SiteToSitePeer> peer) override {
- peer_ = std::move(peer);
- }
-
- bool getPeerList(std::vector<sitetosite::PeerStatus> &peers) override;
-
- /**
- * Establish the protocol connection. Not needed for the HTTP connection, so we simply
- * return true.
- */
- bool establish() override {
- return true;
- }
-
- std::shared_ptr<sitetosite::Transaction> createTransaction(sitetosite::TransferDirection direction) override;
-
- //! Transfer string for the process session
- bool transmitPayload(core::ProcessContext& context, core::ProcessSession& session, const std::string &payload,
- std::map<std::string, std::string> attributes) override;
- // deleteTransaction
- void deleteTransaction(const utils::Identifier& transactionID) override;
-
- protected:
- /**
- * Closes the transaction
- * @param transactionID transaction id reference.
- */
- void closeTransaction(const utils::Identifier &transactionID);
-
- int readResponse(const std::shared_ptr<sitetosite::Transaction> &transaction, sitetosite::RespondCode &code, std::string &message) override;
- // write respond
- int writeResponse(const std::shared_ptr<sitetosite::Transaction> &transaction, sitetosite::RespondCode code, const std::string& message) override;
-
- /**
- * Bootstrapping is not really required for the HTTP Site To Site so we will set the peer state and return true.
- */
- bool bootstrap() override {
- peer_state_ = sitetosite::READY;
- return true;
- }
-
- /**
- * Creates a connection for sending, returning an HTTP client that is structured and configured
- * to receive flow files.
- * @param transaction transaction against which we are performing our sends
- * @return HTTP Client shared pointer.
- */
- std::shared_ptr<minifi::http::HTTPClient> openConnectionForSending(const std::shared_ptr<HttpTransaction> &transaction);
-
- /**
- * Creates a connection for receiving, returning an HTTP client that is structured and configured
- * to receive flow files.
- * @param transaction transaction against which we are performing our reads
- * @return HTTP Client shared pointer.
- */
- std::shared_ptr<minifi::http::HTTPClient> openConnectionForReceive(const std::shared_ptr<HttpTransaction> &transaction);
-
- std::string getBaseURI() {
- std::string uri = ssl_context_service_ != nullptr ? "https://" : "http://";
- uri.append(peer_->getHostName());
- uri.append(":");
- uri.append(std::to_string(peer_->getPort()));
- uri.append("/nifi-api/");
- return uri;
- }
-
- void tearDown() override;
-
- static std::optional<utils::Identifier> parseTransactionId(const std::string &uri);
-
- std::unique_ptr<minifi::http::HTTPClient> create_http_client(const std::string &uri, http::HttpRequestMethod method = http::HttpRequestMethod::POST, bool setPropertyHeaders = false) {
- std::unique_ptr<minifi::http::HTTPClient> http_client_ = std::make_unique<minifi::http::HTTPClient>(uri, ssl_context_service_);
- http_client_->initialize(method, uri, ssl_context_service_);
- if (setPropertyHeaders) {
- if (_currentVersion >= 5) {
- // batch count, size, and duratin don't appear to be set through the interfaces.
- }
- }
- if (!this->peer_->getInterface().empty()) {
- logger_->log_info("HTTP Site2Site bind local network interface {}", this->peer_->getInterface());
- http_client_->setInterface(this->peer_->getInterface());
- }
- if (!this->peer_->getHTTPProxy().host.empty()) {
- logger_->log_info("HTTP Site2Site setup http proxy host {}", this->peer_->getHTTPProxy().host);
- http_client_->setHTTPProxy(this->peer_->getHTTPProxy());
- }
- http_client_->setReadTimeout(idle_timeout_);
- return http_client_;
- }
-
- private:
- sitetosite::RespondCode current_code;
- std::shared_ptr<core::logging::Logger> logger_ = core::logging::LoggerFactory<HttpSiteToSiteClient>::getLogger();
-
- HttpSiteToSiteClient(const HttpSiteToSiteClient &parent);
- HttpSiteToSiteClient &operator=(const HttpSiteToSiteClient &parent);
- static std::shared_ptr<utils::IdGenerator> id_generator_;
-};
-
-} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/include/sitetosite/HTTPTransaction.h b/libminifi/include/sitetosite/HTTPTransaction.h
index faa6129a6..e8842a6f9 100644
--- a/libminifi/include/sitetosite/HTTPTransaction.h
+++ b/libminifi/include/sitetosite/HTTPTransaction.h
@@ -28,35 +28,33 @@
namespace org::apache::nifi::minifi::sitetosite {
-/**
- * Purpose: HTTP Transaction is an implementation that exposes the site to site client.
- * Includes the transaction URL.
- */
-class HttpTransaction : public sitetosite::Transaction {
+class HttpTransaction final : public sitetosite::Transaction {
public:
explicit HttpTransaction(sitetosite::TransferDirection direction, org::apache::nifi::minifi::io::CRCStream<sitetosite::SiteToSitePeer> &&stream)
- : Transaction(direction, std::move(stream)),
- client_ref_(nullptr) {
- }
+ : Transaction(direction, std::move(stream)) {}
- ~HttpTransaction() {
- auto stream = dynamic_cast<http::HttpStream*>(dynamic_cast<sitetosite::SiteToSitePeer*>(crcStream.getstream())->getStream() );
- if (stream)
- stream->forceClose();
+ HttpTransaction(const HttpTransaction&) = delete;
+ HttpTransaction& operator=(const HttpTransaction&) = delete;
+ HttpTransaction(HttpTransaction&&) = delete;
+ HttpTransaction& operator=(HttpTransaction&&) = delete;
+
+ ~HttpTransaction() override {
+ if (auto stream = dynamic_cast<http::HttpStream*>(dynamic_cast<sitetosite::SiteToSitePeer*>(crc_stream_.getstream())->getStream())) {
+ stream->forceClose();
+ }
}
- void initialize(sitetosite::SiteToSiteClient *client, const std::string &url) {
- client_ref_ = client;
+ void initialize(sitetosite::SiteToSiteClient* client, const std::string &url) {
+ client_ = client;
transaction_url_ = url;
}
-
- const std::string &getTransactionUrl() {
+ [[nodiscard]] const std::string &getTransactionUrl() const {
return transaction_url_;
}
protected:
- sitetosite::SiteToSiteClient *client_ref_;
+ sitetosite::SiteToSiteClient* client_ = nullptr;
std::string transaction_url_;
};
diff --git a/libminifi/include/sitetosite/HttpSiteToSiteClient.h b/libminifi/include/sitetosite/HttpSiteToSiteClient.h
new file mode 100644
index 000000000..3e051be83
--- /dev/null
+++ b/libminifi/include/sitetosite/HttpSiteToSiteClient.h
@@ -0,0 +1,95 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+#include "HTTPTransaction.h"
+#include "sitetosite/SiteToSite.h"
+#include "sitetosite/SiteToSiteClient.h"
+#include "core/logging/LoggerConfiguration.h"
+#include "core/ProcessContext.h"
+#include "core/ProcessSession.h"
+#include "sitetosite/Peer.h"
+#include "utils/Id.h"
+
+namespace org::apache::nifi::minifi::sitetosite {
+
+class HttpSiteToSiteClient final : public SiteToSiteClient {
+ public:
+ static constexpr char const* PROTOCOL_VERSION_HEADER = "x-nifi-site-to-site-protocol-version";
+ static constexpr char const* HANDSHAKE_PROPERTY_USE_COMPRESSION = "x-nifi-site-to-site-use-compression";
+ static constexpr char const* HANDSHAKE_PROPERTY_REQUEST_EXPIRATION = "x-nifi-site-to-site-request-expiration";
+ static constexpr char const* HANDSHAKE_PROPERTY_BATCH_COUNT = "x-nifi-site-to-site-batch-count";
+ static constexpr char const* HANDSHAKE_PROPERTY_BATCH_SIZE = "x-nifi-site-to-site-batch-size";
+ static constexpr char const* HANDSHAKE_PROPERTY_BATCH_DURATION = "x-nifi-site-to-site-batch-duration";
+
+ explicit HttpSiteToSiteClient(gsl::not_null<std::unique_ptr<SiteToSitePeer>> peer)
+ : SiteToSiteClient(std::move(peer)),
+ current_code_(ResponseCode::UNRECOGNIZED_RESPONSE_CODE) {
+ peer_state_ = PeerState::READY;
+ }
+
+ HttpSiteToSiteClient(const HttpSiteToSiteClient&) = delete;
+ HttpSiteToSiteClient(HttpSiteToSiteClient&&) = delete;
+ HttpSiteToSiteClient& operator=(const HttpSiteToSiteClient&) = delete;
+ HttpSiteToSiteClient& operator=(HttpSiteToSiteClient&&) = delete;
+ ~HttpSiteToSiteClient() override = default;
+
+ MINIFIAPI static constexpr auto Properties = std::array<core::PropertyReference, 0>{};
+ MINIFIAPI static constexpr bool SupportsDynamicProperties = false;
+ MINIFIAPI static constexpr bool SupportsDynamicRelationships = false;
+
+ std::optional<std::vector<PeerStatus>> getPeerList() override;
+ bool transmitPayload(core::ProcessContext& context, const std::string &payload, const std::map<std::string, std::string>& attributes) override;
+
+ protected:
+ bool bootstrap() override {
+ peer_state_ = PeerState::READY;
+ return true;
+ }
+
+ bool establish() override {
+ return true;
+ }
+
+ std::optional<SiteToSiteResponse> readResponse(const std::shared_ptr<Transaction> &transaction) override;
+ bool writeResponse(const std::shared_ptr<Transaction> &transaction, const SiteToSiteResponse& response) override;
+ std::shared_ptr<Transaction> createTransaction(TransferDirection direction) override;
+ void deleteTransaction(const utils::Identifier& transaction_id) override;
+ void tearDown() override;
+
+ private:
+ void setSiteToSiteHeaders(minifi::http::HTTPClient& client);
+ void closeTransaction(const utils::Identifier &transaction_id);
+ std::shared_ptr<minifi::http::HTTPClient> openConnectionForSending(const std::shared_ptr<HttpTransaction> &transaction);
+ std::shared_ptr<minifi::http::HTTPClient> openConnectionForReceive(const std::shared_ptr<HttpTransaction> &transaction);
+ std::unique_ptr<minifi::http::HTTPClient> createHttpClient(const std::string &uri, http::HttpRequestMethod method);
+ [[nodiscard]] std::string getBaseURI();
+
+ std::optional<SiteToSiteResponse> readResponseForReceiveTransfer(const std::shared_ptr<Transaction>& transaction);
+ std::optional<SiteToSiteResponse> readResponseForSendTransfer(const std::shared_ptr<Transaction>& transaction);
+
+ ResponseCode current_code_;
+ std::shared_ptr<core::logging::Logger> logger_ = core::logging::LoggerFactory<HttpSiteToSiteClient>::getLogger();
+};
+
+} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/include/sitetosite/Peer.h b/libminifi/include/sitetosite/Peer.h
index 8261d2d2b..b5c32d41f 100644
--- a/libminifi/include/sitetosite/Peer.h
+++ b/libminifi/include/sitetosite/Peer.h
@@ -17,88 +17,29 @@
*/
#pragma once
-#include <errno.h>
-#include <stdio.h>
-
#include <atomic>
-#include <map>
#include <memory>
-#include <mutex>
#include <string>
#include <utility>
+#include <array>
#include "core/logging/LoggerFactory.h"
-#include "core/Property.h"
-#include "io/BaseStream.h"
-#include "io/BufferStream.h"
-#include "properties/Configure.h"
#include "http/BaseHTTPClient.h"
-#include "utils/TimeUtil.h"
+#include "io/BaseStream.h"
#include "io/NetworkPrioritizer.h"
-namespace org::apache::nifi::minifi::sitetosite {
-
-class Peer {
- public:
- explicit Peer(const utils::Identifier &port_id, const std::string &host, uint16_t port, bool secure = false)
- : host_(host),
- port_(port),
- secure_(secure) {
- port_id_ = port_id;
- }
-
- explicit Peer(const std::string &host, uint16_t port, bool secure = false)
- : host_(host),
- port_(port),
- secure_(secure) {
- }
-
- explicit Peer(const Peer &other)
- : host_(other.host_),
- port_(other.port_),
- secure_(other.secure_) {
- port_id_ = other.port_id_;
- }
-
- explicit Peer(Peer &&other)
- : host_(std::move(other.host_)),
- port_(std::move(other.port_)),
- secure_(std::move(other.secure_)) {
- port_id_ = other.port_id_;
- }
-
- uint16_t getPort() const {
- return port_;
- }
-
- const std::string &getHost() const {
- return host_;
- }
+using namespace std::literals::chrono_literals;
- bool isSecure() const {
- return secure_;
- }
-
- utils::Identifier getPortId() const {
- return port_id_;
- }
-
- protected:
- std::string host_;
-
- uint16_t port_;
-
- utils::Identifier port_id_;
-
- // secore comms
+namespace org::apache::nifi::minifi::sitetosite {
- bool secure_;
-};
+inline constexpr std::array<char, 4> MAGIC_BYTES = { 'N', 'i', 'F', 'i' };
class PeerStatus {
public:
- PeerStatus(const std::shared_ptr<Peer> &peer, uint32_t flow_file_count, bool query_for_peers)
- : peer_(peer),
+ PeerStatus(utils::Identifier port_id, std::string host, uint16_t port, uint32_t flow_file_count, bool query_for_peers)
+ : port_id_(port_id),
+ host_(std::move(host)),
+ port_(port),
flow_file_count_(flow_file_count),
query_for_peers_(query_for_peers) {
}
@@ -109,175 +50,108 @@ class PeerStatus {
PeerStatus& operator=(const PeerStatus &other) = default;
PeerStatus& operator=(PeerStatus &&other) = default;
- const std::shared_ptr<Peer> &getPeer() const {
- return peer_;
+ const utils::Identifier &getPortId() const {
+ return port_id_;
+ }
+
+ const std::string &getHost() const {
+ return host_;
+ }
+
+ [[nodiscard]] uint16_t getPort() const {
+ return port_;
}
- uint32_t getFlowFileCount() {
+ [[nodiscard]] uint32_t getFlowFileCount() const {
return flow_file_count_;
}
- bool getQueryForPeers() {
+ [[nodiscard]] bool getQueryForPeers() const {
return query_for_peers_;
}
protected:
- std::shared_ptr<Peer> peer_;
+ utils::Identifier port_id_;
+ std::string host_;
+ uint16_t port_;
uint32_t flow_file_count_;
bool query_for_peers_;
};
-static const char MAGIC_BYTES[] = { 'N', 'i', 'F', 'i' };
-
-// Site2SitePeer Class
-class SiteToSitePeer : public org::apache::nifi::minifi::io::BaseStreamImpl {
+class SiteToSitePeer : public io::BaseStreamImpl {
public:
- SiteToSitePeer()
- : stream_(nullptr),
- host_(""),
- port_(-1) {
- }
- /*
- * Create a new site2site peer
- */
- explicit SiteToSitePeer(std::unique_ptr<org::apache::nifi::minifi::io::BaseStream> injected_socket,
- const std::string host,
- uint16_t port,
- const std::string &ifc)
+ SiteToSitePeer(std::unique_ptr<io::BaseStream> injected_socket, const std::string& host, uint16_t port, const std::string& ifc)
: SiteToSitePeer(host, port, ifc) {
stream_ = std::move(injected_socket);
}
- explicit SiteToSitePeer(const std::string &host, uint16_t port, const std::string &ifc)
- : stream_(nullptr),
- host_(host),
+ SiteToSitePeer(const std::string &host, uint16_t port, const std::string &ifc)
+ : host_(host),
port_(port),
- timeout_(std::chrono::seconds(30)),
- logger_(core::logging::LoggerFactory<SiteToSitePeer>::getLogger()) {
- url_ = "nifi://" + host_ + ":" + std::to_string(port_);
- yield_expiration_ = std::chrono::system_clock::time_point();
- timeout_ = std::chrono::seconds(30);
- local_network_interface_ = io::NetworkInterface(ifc, nullptr);
+ url_("nifi://" + host_ + ":" + std::to_string(port_)),
+ local_network_interface_(io::NetworkInterface(ifc, nullptr)) {
}
- explicit SiteToSitePeer(SiteToSitePeer &&ss)
- : stream_(ss.stream_.release()),
- host_(std::move(ss.host_)),
- port_(std::move(ss.port_)),
- local_network_interface_(std::move(ss.local_network_interface_)),
- proxy_(std::move(ss.proxy_)),
- logger_(std::move(ss.logger_)) {
- yield_expiration_.store(ss.yield_expiration_);
- timeout_.store(ss.timeout_);
- url_ = std::move(ss.url_);
- }
- // Destructor
- ~SiteToSitePeer() {
- Close();
- }
- // Set Processor yield period in MilliSecond
- void setYieldPeriodMsec(std::chrono::milliseconds period) {
- yield_period_msec_ = period;
+ SiteToSitePeer(SiteToSitePeer &&ss) = delete;
+ SiteToSitePeer& operator=(SiteToSitePeer&& other) = delete;
+ SiteToSitePeer(const SiteToSitePeer &parent) = delete;
+ SiteToSitePeer &operator=(const SiteToSitePeer &parent) = delete;
+
+ ~SiteToSitePeer() override {
+ close();
}
- // get URL
- std::string getURL() {
+
+ [[nodiscard]] std::string getURL() const {
return url_;
}
- // setInterface
- void setInterface(std::string &ifc) {
+
+ void setInterface(const std::string &ifc) {
local_network_interface_ = io::NetworkInterface(ifc, nullptr);
}
- std::string getInterface() {
+
+ [[nodiscard]] std::string getInterface() const {
return local_network_interface_.getInterface();
}
- // Get Processor yield period in MilliSecond
- std::chrono::milliseconds getYieldPeriodMsec(void) {
- return (yield_period_msec_);
- }
- // Yield based on the yield period
- void yield() {
- yield_expiration_ = std::chrono::system_clock::now() + yield_period_msec_.load();
- }
- // setHostName
- void setHostName(std::string host_) {
- this->host_ = host_;
+
+ void setHostName(const std::string& host) {
+ host_ = host;
url_ = "nifi://" + host_ + ":" + std::to_string(port_);
}
- // setPort
- void setPort(uint16_t port_) {
- this->port_ = port_;
+
+ void setPort(uint16_t port) {
+ port_ = port;
url_ = "nifi://" + host_ + ":" + std::to_string(port_);
}
- // getHostName
- std::string getHostName() {
+
+ [[nodiscard]] std::string getHostName() const {
return host_;
}
- // getPort
- uint16_t getPort() {
+
+ [[nodiscard]] uint16_t getPort() const {
return port_;
}
- // Yield based on the input time
- void yield(std::chrono::milliseconds time) {
- yield_expiration_ = (std::chrono::system_clock::now() + time);
- }
- // whether need be to yield
- bool isYield() {
- return yield_expiration_.load() >= std::chrono::system_clock::now();
- }
- // clear yield expiration
- void clearYield() {
- yield_expiration_ = std::chrono::system_clock::time_point();
- }
- // Yield based on the yield period
- void yield(std::string portId) {
- std::lock_guard<std::mutex> lock(mutex_);
- yield_expiration_PortIdMap[portId] = std::chrono::system_clock::now() + yield_period_msec_.load();
- }
- // Yield based on the input time
- void yield(std::string portId, std::chrono::milliseconds time) {
- yield_expiration_PortIdMap[portId] = std::chrono::system_clock::now() + time;
- }
- // whether need be to yield
- bool isYield(std::string portId) {
- std::lock_guard<std::mutex> lock(mutex_);
- auto it = this->yield_expiration_PortIdMap.find(portId);
- if (it != yield_expiration_PortIdMap.end()) {
- auto yieldExpiration = it->second;
- return (yieldExpiration >= std::chrono::system_clock::now());
- } else {
- return false;
- }
- }
- // clear yield expiration
- void clearYield(std::string portId) {
- std::lock_guard<std::mutex> lock(mutex_);
- auto it = this->yield_expiration_PortIdMap.find(portId);
- if (it != yield_expiration_PortIdMap.end()) {
- yield_expiration_PortIdMap.erase(portId);
- }
- }
- // setTimeout
+
void setTimeout(std::chrono::milliseconds time) {
timeout_ = time;
}
- // getTimeout
- std::chrono::milliseconds getTimeout() {
- return timeout_;
+
+ [[nodiscard]] std::chrono::milliseconds getTimeout() const {
+ return timeout_.load();
}
+
void setHTTPProxy(const http::HTTPProxy &proxy) {
- this->proxy_ = proxy;
+ proxy_ = proxy;
}
- http::HTTPProxy getHTTPProxy() {
- return this->proxy_;
+
+ [[nodiscard]] http::HTTPProxy getHTTPProxy() const {
+ return proxy_;
}
- void setStream(std::unique_ptr<org::apache::nifi::minifi::io::BaseStream> stream) {
- stream_ = nullptr;
- if (stream)
- stream_ = std::move(stream);
+ void setStream(std::unique_ptr<io::BaseStream> stream) {
+ stream_ = std::move(stream);
}
- org::apache::nifi::minifi::io::BaseStream *getStream() {
+ [[nodiscard]] io::BaseStream* getStream() const {
return stream_.get();
}
@@ -292,56 +166,17 @@ class SiteToSitePeer : public org::apache::nifi::minifi::io::BaseStreamImpl {
return stream_->read(data);
}
- // open connection to the peer
- bool Open();
- // close connection to the peer
- void Close();
-
- /**
- * Move assignment operator.
- */
- SiteToSitePeer& operator=(SiteToSitePeer&& other) {
- if (this == &other) {
- return *this;
- }
- stream_ = std::move(other.stream_);
- host_ = std::move(other.host_);
- port_ = std::move(other.port_);
- local_network_interface_ = std::move(other.local_network_interface_);
- yield_expiration_ = std::chrono::system_clock::time_point();
- timeout_ = std::chrono::seconds(30);
- url_ = "nifi://" + host_ + ":" + std::to_string(port_);
-
- return *this;
- }
-
- SiteToSitePeer(const SiteToSitePeer &parent) = delete;
- SiteToSitePeer &operator=(const SiteToSitePeer &parent) = delete;
+ bool open();
+ void close() override;
private:
- std::unique_ptr<org::apache::nifi::minifi::io::BaseStream> stream_;
-
+ std::unique_ptr<io::BaseStream> stream_;
std::string host_;
-
uint16_t port_;
-
+ std::string url_;
+ std::atomic<std::chrono::milliseconds> timeout_{30s};
io::NetworkInterface local_network_interface_;
-
http::HTTPProxy proxy_;
-
- // Mutex for protection
- std::mutex mutex_;
- // URL
- std::string url_;
- // socket timeout;
- std::atomic<std::chrono::milliseconds> timeout_{};
- // Yield Period in Milliseconds
- std::atomic<std::chrono::milliseconds> yield_period_msec_;
- // Yield Expiration
- std::atomic<std::chrono::time_point<std::chrono::system_clock>> yield_expiration_{};
- // Yield Expiration per destination PortID
- std::map<std::string, std::chrono::time_point<std::chrono::system_clock>> yield_expiration_PortIdMap;
- // Logger
std::shared_ptr<core::logging::Logger> logger_ = core::logging::LoggerFactory<SiteToSitePeer>::getLogger();
};
diff --git a/libminifi/include/sitetosite/PeersEntity.h b/libminifi/include/sitetosite/PeersEntity.h
deleted file mode 100644
index dfbec250c..000000000
--- a/libminifi/include/sitetosite/PeersEntity.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#pragma once
-
-#include <string>
-#include <vector>
-#include <memory>
-#include <utility>
-
-#include "rapidjson/document.h"
-#include "rapidjson/error/en.h"
-
-#include "sitetosite/Peer.h"
-#include "utils/StringUtils.h"
-#include "utils/Enum.h"
-#include "Exception.h"
-
-namespace org::apache::nifi::minifi::sitetosite {
-
-/**
- * Represents a peer. Contains the parser for the Peer JSON.
- */
-class PeersEntity {
- public:
- static bool parse(const std::shared_ptr<core::logging::Logger> &logger, const std::string &entity, const utils::Identifier &id, std::vector<PeerStatus> &peer_statuses) {
- try {
- rapidjson::Document root;
- rapidjson::ParseResult ok = root.Parse(entity.c_str());
-
- if (!ok) {
- std::stringstream ss;
- ss << "Failed to parse archive lens stack from JSON string with reason: "
- << rapidjson::GetParseError_En(ok.Code())
- << " at offset " << ok.Offset();
-
- throw Exception(ExceptionType::GENERAL_EXCEPTION, ss.str());
- }
-
- if (root.HasMember("peers") && root["peers"].IsArray() && root["peers"].Size() > 0) {
- for (const auto &peer : root["peers"].GetArray()) {
- std::string hostname;
- int port = 0, flowFileCount = 0;
- bool secure = false;
-
- if (peer.HasMember("hostname") && peer["hostname"].IsString() &&
- peer.HasMember("port") && peer["port"].IsNumber()) {
- hostname = peer["hostname"].GetString();
- port = peer["port"].GetInt();
- }
-
- if (peer.HasMember("secure")) {
- if (peer["secure"].IsBool()) {
- secure = peer["secure"].GetBool();
- } else if (peer["secure"].IsString()) {
- std::string secureStr = peer["secure"].GetString();
-
- if (utils::string::equalsIgnoreCase(secureStr, "true")) {
- secure = true;
- } else if (utils::string::equalsIgnoreCase(secureStr, "false")) {
- secure = false;
- } else {
- const auto err = utils::string::join_pack("could not parse secure string ", secureStr);
- logger->log_error("{}", err);
- throw std::logic_error{err};
- }
- } else {
- logger->log_warn("Invalid value type for secure, assuming false (rapidjson type id {})",
- magic_enum::enum_underlying(peer["secure"].GetType()));
- }
- }
-
- if (peer.HasMember("flowFileCount")) {
- if (peer["flowFileCount"].IsNumber()) {
- flowFileCount = gsl::narrow<int>(peer["flowFileCount"].GetInt64());
- } else {
- logger->log_debug("Could not parse flowFileCount, so we're going to continue without it");
- }
- }
-
- // host name and port are required.
- if (!IsNullOrEmpty(hostname) && port > 0) {
- sitetosite::PeerStatus status(std::make_shared<sitetosite::Peer>(id, hostname, port, secure), flowFileCount, true);
- peer_statuses.push_back(std::move(status));
- } else {
- logger->log_debug("hostname empty or port is zero. hostname: {}, port: {}", hostname, port);
- }
- }
- } else {
- logger->log_debug("Peers is either not a member or is empty. String to analyze: {}", entity);
- }
- return true;
- } catch (Exception &exception) {
- logger->log_debug("Caught Exception {}", exception.what());
- return false;
- } catch (...) {
- logger->log_debug("General exception occurred");
- return false;
- }
- }
-};
-
-} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/include/sitetosite/RawSiteToSiteClient.h b/libminifi/include/sitetosite/RawSiteToSiteClient.h
new file mode 100644
index 000000000..2de163f4d
--- /dev/null
+++ b/libminifi/include/sitetosite/RawSiteToSiteClient.h
@@ -0,0 +1,96 @@
+/**
+ * @file RawSiteToSiteClient.h
+ * RawSiteToSiteClient class declaration
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <algorithm>
+#include <chrono>
+#include <map>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "core/logging/LoggerFactory.h"
+#include "core/ProcessContext.h"
+#include "core/ProcessSession.h"
+#include "FlowFileRecord.h"
+#include "io/CRCStream.h"
+#include "Peer.h"
+#include "SiteToSite.h"
+#include "SiteToSiteClient.h"
+#include "utils/Id.h"
+
+using namespace std::literals::chrono_literals;
+
+namespace org::apache::nifi::minifi {
+
+namespace test {
+class SiteToSiteClientTestAccessor;
+} // namespace test
+
+namespace sitetosite {
+
+class RawSiteToSiteClient final : public SiteToSiteClient {
+ public:
+ explicit RawSiteToSiteClient(gsl::not_null<std::unique_ptr<SiteToSitePeer>> peer) : SiteToSiteClient(std::move(peer)) {
+ timeout_ = 30s;
+ }
+
+ RawSiteToSiteClient(const RawSiteToSiteClient &parent) = delete;
+ RawSiteToSiteClient &operator=(const RawSiteToSiteClient &parent) = delete;
+ RawSiteToSiteClient(RawSiteToSiteClient &&parent) = delete;
+ RawSiteToSiteClient &operator=(RawSiteToSiteClient &&parent) = delete;
+
+ ~RawSiteToSiteClient() override {
+ tearDown();
+ }
+
+ public:
+ void setTimeout(std::chrono::milliseconds time) override {
+ timeout_ = time;
+ peer_->setTimeout(time);
+ }
+
+ std::optional<std::vector<PeerStatus>> getPeerList() override;
+ bool transmitPayload(core::ProcessContext& context, const std::string &payload, const std::map<std::string, std::string>& attributes) override;
+
+ protected:
+ friend class test::SiteToSiteClientTestAccessor;
+ bool bootstrap() override;
+ bool establish() override;
+ std::shared_ptr<Transaction> createTransaction(TransferDirection direction) override;
+ void tearDown() override;
+
+ private:
+ static constexpr std::string_view PROTOCOL_RESOURCE_NAME = "SocketFlowFileProtocol";
+ static constexpr std::string_view CODEC_RESOURCE_NAME = "StandardFlowFileCodec";
+
+ bool handShake();
+ bool negotiateCodec();
+ bool initiateResourceNegotiation();
+ bool initiateCodecResourceNegotiation();
+ int64_t writeRequestType(RequestType type);
+
+ std::shared_ptr<core::logging::Logger> logger_ = core::logging::LoggerFactory<RawSiteToSiteClient>::getLogger();
+ utils::Identifier comms_identifier_;
+};
+
+} // namespace sitetosite
+} // namespace org::apache::nifi::minifi
diff --git a/libminifi/include/sitetosite/RawSocketProtocol.h b/libminifi/include/sitetosite/RawSocketProtocol.h
deleted file mode 100644
index 2bee3b311..000000000
--- a/libminifi/include/sitetosite/RawSocketProtocol.h
+++ /dev/null
@@ -1,177 +0,0 @@
-/**
- * @file RawSiteToSiteClient.h
- * RawSiteToSiteClient class declaration
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#pragma once
-
-#include <errno.h>
-#include <stdio.h>
-#include <sys/types.h>
-
-#include <algorithm>
-#include <chrono>
-#include <map>
-#include <memory>
-#include <string>
-#include <thread>
-#include <utility>
-#include <vector>
-
-#include "core/logging/LoggerFactory.h"
-#include "core/ProcessContext.h"
-#include "core/ProcessSession.h"
-#include "core/Property.h"
-#include "FlowFileRecord.h"
-#include "io/CRCStream.h"
-#include "Peer.h"
-#include "properties/Configure.h"
-#include "SiteToSite.h"
-#include "SiteToSiteClient.h"
-#include "utils/Id.h"
-
-namespace org::apache::nifi::minifi::sitetosite {
-
-
-// RawSiteToSiteClient Class
-class RawSiteToSiteClient : public sitetosite::SiteToSiteClient {
- public:
- // HandShakeProperty Str
- static const char *HandShakePropertyStr[MAX_HANDSHAKE_PROPERTY];
-
- RawSiteToSiteClient(std::unique_ptr<SiteToSitePeer> peer) { // NOLINT
- peer_ = std::move(peer);
- _batchSize = 0;
- _batchCount = 0;
- _batchDuration = std::chrono::seconds(0);
- _batchSendNanos = std::chrono::seconds(5);
- _timeout = std::chrono::seconds(30);
- _supportedVersion[0] = 5;
- _supportedVersion[1] = 4;
- _supportedVersion[2] = 3;
- _supportedVersion[3] = 2;
- _supportedVersion[4] = 1;
- _currentVersion = _supportedVersion[0];
- _currentVersionIndex = 0;
- _supportedCodecVersion[0] = 1;
- _currentCodecVersion = _supportedCodecVersion[0];
- _currentCodecVersionIndex = 0;
- }
-
- ~RawSiteToSiteClient() override {
- tearDown();
- }
-
- public:
- // setBatchSize
- void setBatchSize(uint64_t size) {
- _batchSize = size;
- }
- // setBatchCount
- void setBatchCount(uint64_t count) {
- _batchCount = count;
- }
- // setBatchDuration
- void setBatchDuration(std::chrono::milliseconds duration) {
- _batchDuration = duration;
- }
- // setTimeout
- void setTimeout(std::chrono::milliseconds time) {
- _timeout = time;
- if (peer_)
- peer_->setTimeout(time);
- }
-
- /**
- * Provides a reference to the time out
- * @returns timeout
- */
- std::chrono::milliseconds getTimeout() const {
- return _timeout;
- }
-
- // getResourceName
- std::string getResourceName() {
- return "SocketFlowFileProtocol";
- }
- // getCodecResourceName
- std::string getCodecResourceName() {
- return "StandardFlowFileCodec";
- }
-
- // get peerList
- bool getPeerList(std::vector<PeerStatus> &peer) override;
- // negotiateCodec
- virtual bool negotiateCodec();
- // initiateResourceNegotiation
- virtual bool initiateResourceNegotiation();
- // initiateCodecResourceNegotiation
- virtual bool initiateCodecResourceNegotiation();
- // tearDown
- void tearDown() override;
- // write Request Type
- virtual int writeRequestType(RequestType type);
- // read Request Type
- virtual int readRequestType(RequestType &type);
-
- // read Respond
- virtual int readRespond(const std::shared_ptr<Transaction> &transaction, RespondCode &code, std::string &message);
- // write respond
- virtual int writeRespond(const std::shared_ptr<Transaction> &transaction, RespondCode code, const std::string& message);
- // getRespondCodeContext
- RespondCodeContext *getRespondCodeContext(RespondCode code) override {
- return SiteToSiteClient::getRespondCodeContext(code);
- }
-
- // Creation of a new transaction, return the transaction ID if success,
- // Return NULL when any error occurs
- std::shared_ptr<Transaction> createTransaction(TransferDirection direction) override;
-
- //! Transfer string for the process session
- bool transmitPayload(core::ProcessContext& context, core::ProcessSession& session, const std::string &payload,
- std::map<std::string, std::string> attributes) override;
-
- // bootstrap the protocol to the ready for transaction state by going through the state machine
- bool bootstrap() override;
-
- protected:
- // establish
- bool establish() override;
- // handShake
- virtual bool handShake();
-
- private:
- // Logger
- std::shared_ptr<core::logging::Logger> logger_ = core::logging::LoggerFactory<RawSiteToSiteClient>::getLogger();
- // Batch Count
- std::atomic<uint64_t> _batchCount;
- // Batch Size
- std::atomic<uint64_t> _batchSize;
- // Batch Duration in msec
- std::atomic<std::chrono::milliseconds> _batchDuration;
- // Timeout in msec
- std::atomic<std::chrono::milliseconds> _timeout;
-
- // commsIdentifier
- utils::Identifier _commsIdentifier;
-
- RawSiteToSiteClient(const RawSiteToSiteClient &parent);
- RawSiteToSiteClient &operator=(const RawSiteToSiteClient &parent);
- static std::shared_ptr<utils::IdGenerator> id_generator_;
-};
-
-} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/include/sitetosite/SiteToSite.h b/libminifi/include/sitetosite/SiteToSite.h
index 178d6730a..c6608e56a 100644
--- a/libminifi/include/sitetosite/SiteToSite.h
+++ b/libminifi/include/sitetosite/SiteToSite.h
@@ -23,35 +23,28 @@
#include "minifi-cpp/controllers/SSLContextServiceInterface.h"
#include "Peer.h"
-#include "core/Property.h"
-#include "properties/Configure.h"
#include "io/CRCStream.h"
#include "utils/Id.h"
-#include "http/BaseHTTPClient.h"
-#include "utils/Export.h"
namespace org::apache::nifi::minifi::sitetosite {
-#if defined(__GNUC__) || defined(__GNUG__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wunused-variable"
-#endif
-
-// Resource Negotiated Status Code
-#define RESOURCE_OK 20
-#define DIFFERENT_RESOURCE_VERSION 21
-#define NEGOTIATED_ABORT 255
-// ! Max attributes
-#define MAX_NUM_ATTRIBUTES 25000
-
-// Respond Code Sequence Pattern
-static const uint8_t CODE_SEQUENCE_VALUE_1 = (uint8_t) 'R';
-static const uint8_t CODE_SEQUENCE_VALUE_2 = (uint8_t) 'C';
+
+enum class ResourceNegotiationStatusCode : uint8_t {
+ RESOURCE_OK = 20,
+ DIFFERENT_RESOURCE_VERSION = 21,
+ NEGOTIATED_ABORT = 255
+};
+
+static constexpr uint32_t MAX_NUM_ATTRIBUTES = 25000;
+
+// Response Code Sequence Pattern
+inline constexpr uint8_t CODE_SEQUENCE_VALUE_1 = static_cast<uint8_t>('R');
+inline constexpr uint8_t CODE_SEQUENCE_VALUE_2 = static_cast<uint8_t>('C');
/**
* Enumeration of Properties that can be used for the Site-to-Site Socket
* Protocol.
*/
-typedef enum {
+enum class HandshakeProperty {
/**
* Boolean value indicating whether or not the contents of a FlowFile should
* be GZipped when transferred.
@@ -87,95 +80,44 @@ typedef enum {
*/
BATCH_DURATION,
MAX_HANDSHAKE_PROPERTY
-} HandshakeProperty;
+};
-typedef enum {
+enum class ClientType {
RAW,
HTTP
-} CLIENT_TYPE;
+};
-/**
- * An enumeration for specifying the direction in which data should be
- * transferred between a client and a remote NiFi instance.
- */
-typedef enum {
- /**
- * * The client is to send data to the remote instance.
- * */
+enum class TransferDirection {
SEND,
- /**
- * * The client is to receive data from the remote instance.
- * */
RECEIVE
-} TransferDirection;
+};
-// Peer State
-typedef enum {
- /**
- * * IDLE
- * */
+enum class PeerState {
IDLE = 0,
- /**
- * * Socket Established
- * */
ESTABLISHED,
- /**
- * * HandShake Done
- * */
HANDSHAKED,
- /**
- * * After CodeDec Completion
- * */
READY
-} PeerState;
+};
-// Transaction State
-typedef enum {
- /**
- * * Transaction has been started but no data has been sent or received.
- * */
+enum class TransactionState {
TRANSACTION_STARTED,
- /**
- * * Transaction has been started and data has been sent or received.
- * */
DATA_EXCHANGED,
- /**
- * * Data that has been transferred has been confirmed via its CRC.
- * * Transaction is ready to be completed.
- * */
TRANSACTION_CONFIRMED,
- /**
- * * Transaction has been successfully completed.
- * */
TRANSACTION_COMPLETED,
- /**
- * * The Transaction has been canceled.
- * */
TRANSACTION_CANCELED,
-
- /**
- * * Transaction has been successfully closed.
- * */
TRANSACTION_CLOSED,
- /**
- * * The Transaction ended in an error.
- * */
TRANSACTION_ERROR
-} TransactionState;
+};
-// Request Type
-typedef enum {
+enum class RequestType {
NEGOTIATE_FLOWFILE_CODEC = 0,
REQUEST_PEER_LIST,
SEND_FLOWFILES,
RECEIVE_FLOWFILES,
- SHUTDOWN,
- MAX_REQUEST_TYPE
-} RequestType;
-
+ SHUTDOWN
+};
-// Respond Code
-typedef enum {
+enum class ResponseCode : uint8_t {
RESERVED = 0,
// ResponseCode, so that we can indicate a 0 followed by some other bytes
@@ -205,140 +147,184 @@ typedef enum {
ABORT = 250,
UNRECOGNIZED_RESPONSE_CODE = 254,
END_OF_STREAM = 255
-}RespondCode;
-
-// Respond Code Class
-typedef struct {
- RespondCode code;
- const char *description;
- bool hasDescription;
-} RespondCodeContext;
-
-
+};
-// Request Type Str
-class SiteToSiteRequest {
- public:
- MINIFIAPI static const char *RequestTypeStr[MAX_REQUEST_TYPE];
- MINIFIAPI static RespondCodeContext respondCodeContext[21];
+struct ResponseCodeContext {
+ ResponseCode code = ResponseCode::UNRECOGNIZED_RESPONSE_CODE;
+ const std::string_view description;
+ bool has_description = false;
};
+inline constexpr std::array<ResponseCodeContext, 21> response_code_contexts = {{
+ { ResponseCode::RESERVED, "Reserved for Future Use", false },
+ { ResponseCode::PROPERTIES_OK, "Properties OK", false },
+ { ResponseCode::UNKNOWN_PROPERTY_NAME, "Unknown Property Name", true },
+ { ResponseCode::ILLEGAL_PROPERTY_VALUE, "Illegal Property Value", true },
+ { ResponseCode::MISSING_PROPERTY, "Missing Property", true },
+ { ResponseCode::CONTINUE_TRANSACTION, "Continue Transaction", false },
+ { ResponseCode::FINISH_TRANSACTION, "Finish Transaction", false },
+ { ResponseCode::CONFIRM_TRANSACTION, "Confirm Transaction", true },
+ { ResponseCode::TRANSACTION_FINISHED, "Transaction Finished", false },
+ { ResponseCode::TRANSACTION_FINISHED_BUT_DESTINATION_FULL, "Transaction Finished But Destination is Full", false },
+ { ResponseCode::CANCEL_TRANSACTION, "Cancel Transaction", true },
+ { ResponseCode::BAD_CHECKSUM, "Bad Checksum", false },
+ { ResponseCode::MORE_DATA, "More Data Exists", false },
+ { ResponseCode::NO_MORE_DATA, "No More Data Exists", false },
+ { ResponseCode::UNKNOWN_PORT, "Unknown Port", false },
+ { ResponseCode::PORT_NOT_IN_VALID_STATE, "Port Not in a Valid State", true },
+ { ResponseCode::PORTS_DESTINATION_FULL, "Port's Destination is Full", false },
+ { ResponseCode::UNAUTHORIZED, "User Not Authorized", true },
+ { ResponseCode::ABORT, "Abort", true },
+ { ResponseCode::UNRECOGNIZED_RESPONSE_CODE, "Unrecognized Response Code", false },
+ { ResponseCode::END_OF_STREAM, "End of Stream", false }
+}};
-// Transaction Class
class Transaction {
public:
- // Constructor
- /*!
- * Create a new transaction
- */
- explicit Transaction(TransferDirection direction, org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> &&stream)
+ explicit Transaction(TransferDirection direction, io::CRCStream<SiteToSitePeer> &&stream)
: closed_(false),
- crcStream(std::move(stream)),
- uuid_(id_generator_->generate()) {
- _state = TRANSACTION_STARTED;
- _direction = direction;
- _dataAvailable = false;
+ crc_stream_(std::move(stream)),
+ uuid_(utils::IdGenerator::getIdGenerator()->generate()) {
+ state_ = TransactionState::TRANSACTION_STARTED;
+ direction_ = direction;
+ data_available_ = false;
current_transfers_ = 0;
total_transfers_ = 0;
- _bytes = 0;
+ bytes_ = 0;
}
- // Destructor
+
virtual ~Transaction() = default;
- // getUUIDStr
- utils::SmallString<36> getUUIDStr() const {
+
+ [[nodiscard]] utils::SmallString<36> getUUIDStr() const {
return uuid_.to_string();
}
- utils::Identifier getUUID() const {
+ [[nodiscard]] utils::Identifier getUUID() const {
return uuid_;
}
void setTransactionId(const utils::Identifier& id) {
- setUUID(id);
+ uuid_ = id;
}
- void setUUID(const utils::Identifier &id) {
- uuid_ = id;
+ void setState(TransactionState state) {
+ state_ = state;
}
- // getState
- TransactionState getState() {
- return _state;
+ [[nodiscard]] TransactionState getState() const {
+ return state_;
}
- // isDataAvailable
- bool isDataAvailable() {
- return _dataAvailable;
+
+ bool isDataAvailable() const {
+ return data_available_;
}
- // setDataAvailable()
+
void setDataAvailable(bool value) {
- _dataAvailable = value;
+ data_available_ = value;
}
- // getDirection
- TransferDirection getDirection() {
- return _direction;
+
+ [[nodiscard]] TransferDirection getDirection() const {
+ return direction_;
}
- // getCRC
- uint64_t getCRC() {
- return crcStream.getCRC();
+
+ [[nodiscard]] uint64_t getCRC() const {
+ return crc_stream_.getCRC();
}
- // updateCRC
+
void updateCRC(uint8_t *buffer, uint32_t length) {
- crcStream.updateCRC(buffer, length);
+ crc_stream_.updateCRC(buffer, length);
}
- org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> &getStream() {
- return crcStream;
+ [[nodiscard]] io::CRCStream<SiteToSitePeer>& getStream() {
+ return crc_stream_;
}
- Transaction(const Transaction &parent) = delete;
- Transaction &operator=(const Transaction &parent) = delete;
+ [[nodiscard]] uint64_t getCurrentTransfers() const {
+ return current_transfers_;
+ }
- // Number of current transfers
- int current_transfers_;
- // number of total seen transfers
- int total_transfers_;
+ [[nodiscard]] uint64_t getTotalTransfers() const {
+ return total_transfers_;
+ }
+
+ [[nodiscard]] uint64_t getBytes() const {
+ return bytes_;
+ }
- // Number of content bytes
- uint64_t _bytes;
+ void addBytes(uint64_t bytes) {
+ bytes_ += bytes;
+ }
- // Transaction State
- TransactionState _state;
+ void incrementCurrentTransfers() {
+ current_transfers_++;
+ }
- bool closed_;
+ void decrementCurrentTransfers() {
+ if (current_transfers_ > 0) {
+ current_transfers_--;
+ }
+ }
+
+ void incrementTotalTransfers() {
+ total_transfers_++;
+ }
- // Whether received data is available
- bool _dataAvailable;
+ bool isClosed() const {
+ return closed_;
+ }
+
+ void close() {
+ closed_ = true;
+ }
+
+ Transaction(const Transaction &parent) = delete;
+ Transaction &operator=(const Transaction &parent) = delete;
protected:
- org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> crcStream;
+ uint64_t current_transfers_;
+ uint64_t total_transfers_;
+ uint64_t bytes_;
+ TransactionState state_;
+ bool closed_;
+ bool data_available_;
+ io::CRCStream<SiteToSitePeer> crc_stream_;
private:
- // Transaction Direction
- TransferDirection _direction;
-
- // A global unique identifier
+ TransferDirection direction_;
utils::Identifier uuid_;
-
- MINIFIAPI static std::shared_ptr<utils::IdGenerator> id_generator_;
};
class SiteToSiteClientConfiguration {
public:
- SiteToSiteClientConfiguration(const std::shared_ptr<Peer> &peer, const std::string &ifc, CLIENT_TYPE type = RAW)
- : peer_(peer),
+ SiteToSiteClientConfiguration(const utils::Identifier &port_id, std::string host, uint16_t port, const std::string &ifc, ClientType type)
+ : port_id_(port_id),
+ host_(std::move(host)),
+ port_(port),
local_network_interface_(ifc),
ssl_service_(nullptr) {
client_type_ = type;
}
SiteToSiteClientConfiguration(const SiteToSiteClientConfiguration &other) = delete;
+ SiteToSiteClientConfiguration &operator=(const SiteToSiteClientConfiguration &other) = delete;
+ SiteToSiteClientConfiguration(SiteToSiteClientConfiguration &&other) = delete;
+ SiteToSiteClientConfiguration &operator=(SiteToSiteClientConfiguration &&other) = delete;
+ ~SiteToSiteClientConfiguration() = default;
- CLIENT_TYPE getClientType() const {
+ ClientType getClientType() const {
return client_type_;
}
- const std::shared_ptr<Peer> &getPeer() const {
- return peer_;
+ const utils::Identifier& getPortId() const {
+ return port_id_;
+ }
+
+ const std::string& getHost() const {
+ return host_;
+ }
+
+ uint16_t getPort() const {
+ return port_;
}
void setSecurityContext(const std::shared_ptr<controllers::SSLContextServiceInterface> &ssl_service) {
@@ -357,37 +343,76 @@ class SiteToSiteClientConfiguration {
return idle_timeout_;
}
- // setInterface
- void setInterface(std::string &ifc) {
+ void setInterface(const std::string &ifc) {
local_network_interface_ = ifc;
}
+
std::string getInterface() const {
return local_network_interface_;
}
+
void setHTTPProxy(const http::HTTPProxy &proxy) {
proxy_ = proxy;
}
+
http::HTTPProxy getHTTPProxy() const {
- return this->proxy_;
+ return proxy_;
}
- protected:
- std::shared_ptr<Peer> peer_;
+ void setUseCompression(bool use_compression) {
+ use_compression_ = use_compression;
+ }
- CLIENT_TYPE client_type_;
+ bool getUseCompression() const {
+ return use_compression_;
+ }
- std::string local_network_interface_;
+ void setBatchCount(std::optional<uint64_t> count) {
+ batch_count_ = count;
+ }
- std::chrono::milliseconds idle_timeout_{15000};
+ std::optional<uint64_t> getBatchCount() const {
+ return batch_count_;
+ }
- // secore comms
+ void setBatchSize(std::optional<uint64_t> size) {
+ batch_size_ = size;
+ }
- std::shared_ptr<controllers::SSLContextServiceInterface> ssl_service_;
+ std::optional<uint64_t> getBatchSize() const {
+ return batch_size_;
+ }
+ void setBatchDuration(std::optional<std::chrono::milliseconds> duration) {
+ batch_duration_ = duration;
+ }
+
+ std::optional<std::chrono::milliseconds> getBatchDuration() const {
+ return batch_duration_;
+ }
+
+ void setTimeout(std::optional<std::chrono::milliseconds> timeout) {
+ timeout_ = timeout;
+ }
+
+ std::optional<std::chrono::milliseconds> getTimeout() const {
+ return timeout_;
+ }
+
+ private:
+ utils::Identifier port_id_;
+ std::string host_;
+ uint16_t port_;
+ ClientType client_type_;
+ std::string local_network_interface_;
+ std::chrono::milliseconds idle_timeout_{15s};
+ std::shared_ptr<controllers::SSLContextServiceInterface> ssl_service_;
http::HTTPProxy proxy_;
+ bool use_compression_{false};
+ std::optional<uint64_t> batch_count_;
+ std::optional<uint64_t> batch_size_;
+ std::optional<std::chrono::milliseconds> batch_duration_;
+ std::optional<std::chrono::milliseconds> timeout_;
};
-#if defined(__GNUC__) || defined(__GNUG__)
-#pragma GCC diagnostic pop
-#endif
} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/include/sitetosite/SiteToSiteClient.h b/libminifi/include/sitetosite/SiteToSiteClient.h
index 6d4d2e913..cfbb59a26 100644
--- a/libminifi/include/sitetosite/SiteToSiteClient.h
+++ b/libminifi/include/sitetosite/SiteToSiteClient.h
@@ -19,246 +19,180 @@
#pragma once
#include <algorithm>
-#include <array>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
+#include <optional>
#include "Peer.h"
#include "SiteToSite.h"
#include "core/ProcessSession.h"
#include "core/ProcessContext.h"
-#include "core/Connectable.h"
-#include "utils/gsl.h"
-namespace org::apache::nifi::minifi::sitetosite {
+namespace org::apache::nifi::minifi {
-/**
- * Represents a piece of data that is to be sent to or that was received from a
- * NiFi instance.
- */
-class DataPacket {
+namespace test {
+class SiteToSiteClientTestAccessor;
+} // namespace test
+
+namespace sitetosite {
+
+struct DataPacket {
public:
- DataPacket(std::shared_ptr<core::logging::Logger> logger, std::shared_ptr<Transaction> transaction, std::map<std::string, std::string> attributes, const std::string &payload)
- : _attributes{std::move(attributes)},
- transaction_{std::move(transaction)},
- payload_{payload},
- logger_reference_{std::move(logger)} {
+ DataPacket(std::shared_ptr<Transaction> transaction, const std::string &payload)
+ : transaction{std::move(transaction)},
+ payload{payload} {
+ }
+ DataPacket(std::shared_ptr<Transaction> transaction, std::map<std::string, std::string> attributes, const std::string &payload)
+ : attributes{std::move(attributes)},
+ transaction{std::move(transaction)},
+ payload{payload} {
}
- std::map<std::string, std::string> _attributes;
- uint64_t _size{0};
- std::shared_ptr<Transaction> transaction_;
- const std::string & payload_;
- std::shared_ptr<core::logging::Logger> logger_reference_;
+ std::map<std::string, std::string> attributes;
+ std::shared_ptr<Transaction> transaction;
+ const std::string& payload;
};
-class SiteToSiteClient : public core::ConnectableImpl {
+struct SiteToSiteResponse {
+ ResponseCode code = ResponseCode::UNRECOGNIZED_RESPONSE_CODE;
+ std::string message;
+};
+
+class SiteToSiteClient {
public:
- SiteToSiteClient()
- : core::ConnectableImpl("SitetoSiteClient") {
+ explicit SiteToSiteClient(gsl::not_null<std::unique_ptr<SiteToSitePeer>> peer)
+ : peer_(std::move(peer)) {
}
- ~SiteToSiteClient() override = default;
+ SiteToSiteClient(const SiteToSiteClient&) = delete;
+ SiteToSiteClient(SiteToSiteClient&&) = delete;
+ SiteToSiteClient& operator=(const SiteToSiteClient&) = delete;
+ SiteToSiteClient& operator=(SiteToSiteClient&&) = delete;
- void setSSLContextService(const std::shared_ptr<minifi::controllers::SSLContextServiceInterface> &context_service) {
- ssl_context_service_ = context_service;
- }
+ virtual ~SiteToSiteClient() = default;
- /**
- * Creates a transaction using the transaction ID and the direction
- * @param transactionID transaction identifier
- * @param direction direction of transfer
- */
- virtual std::shared_ptr<Transaction> createTransaction(TransferDirection direction) = 0;
+ virtual std::optional<std::vector<PeerStatus>> getPeerList() = 0;
+ virtual bool transmitPayload(core::ProcessContext& context, const std::string &payload, const std::map<std::string, std::string>& attributes) = 0;
- /**
- * Transfers flow files
- * @param direction transfer direction
- * @param context process context
- * @param session process session
- * @returns true if the process succeeded, failure OR exception thrown otherwise
- */
- virtual bool transfer(TransferDirection direction, core::ProcessContext& context, core::ProcessSession& session) {
-#ifndef WIN32
- if (__builtin_expect(direction == SEND, 1)) {
+ bool transfer(TransferDirection direction, core::ProcessContext& context, core::ProcessSession& session) {
+ if (direction == TransferDirection::SEND) {
return transferFlowFiles(context, session);
} else {
return receiveFlowFiles(context, session);
}
-#else
- if (direction == SEND) {
- return transferFlowFiles(context, session);
- } else {
- return receiveFlowFiles(context, session);
- }
-#endif
}
- /**
- * Transfers flow files to server
- * @param context process context
- * @param session process session
- * @returns true if the process succeeded, failure OR exception thrown otherwise
- */
- virtual bool transferFlowFiles(core::ProcessContext& context, core::ProcessSession& session);
-
- /**
- * Receive flow files from server
- * @param context process context
- * @param session process session
- * @returns true if the process succeeded, failure OR exception thrown otherwise
- */
-
- // Confirm the data that was sent or received by comparing CRC32's of the data sent and the data received.
- // Receive flow files for the process session
- bool receiveFlowFiles(core::ProcessContext& context, core::ProcessSession& session);
-
- // Receive the data packet from the transaction
- // Return false when any error occurs
- bool receive(const utils::Identifier &transactionID, DataPacket *packet, bool &eof);
- /**
- * Transfers raw data and attributes to server
- * @param context process context
- * @param session process session
- * @param payload data to transmit
- * @param attributes
- * @returns true if the process succeeded, failure OR exception thrown otherwise
- */
- virtual bool transmitPayload(core::ProcessContext& context, core::ProcessSession& session, const std::string &payload,
- std::map<std::string, std::string> attributes) = 0;
-
- void setPortId(utils::Identifier &id) {
+ void setPortId(const utils::Identifier& id) {
port_id_ = id;
}
- /**
- * Sets the idle timeout.
- */
void setIdleTimeout(std::chrono::milliseconds timeout) {
idle_timeout_ = timeout;
}
- /**
- * Sets the base peer for this interface.
- */
- virtual void setPeer(std::unique_ptr<SiteToSitePeer> peer) {
- peer_ = std::move(peer);
- }
-
- /**
- * Provides a reference to the port identifier
- * @returns port identifier
- */
- utils::Identifier getPortId() const {
+ [[nodiscard]] utils::Identifier getPortId() const {
return port_id_;
}
- /**
- * Obtains the peer list and places them into the provided vector
- * @param peers peer vector.
- * @return true if successful, false otherwise
- */
- virtual bool getPeerList(std::vector<PeerStatus> &peers) = 0;
-
- /**
- * Establishes the interface.
- * @return true if successful, false otherwise
- */
- virtual bool establish() = 0;
-
- const std::shared_ptr<core::logging::Logger> &getLogger() {
+ [[nodiscard]] const std::shared_ptr<core::logging::Logger> &getLogger() {
return logger_;
}
- void yield() override {
+ void setSSLContextService(const std::shared_ptr<minifi::controllers::SSLContextServiceInterface> &context_service) {
+ ssl_context_service_ = context_service;
}
- /**
- * Determines if we are connected and operating
- */
- bool isRunning() const override {
- return running_;
+ void setUseCompression(bool use_compression) {
+ use_compression_ = use_compression;
}
- /**
- * Determines if work is available by this connectable
- * @return boolean if work is available.
- */
- bool isWorkAvailable() override {
- return true;
+ void setBatchSize(uint64_t size) {
+ batch_size_ = size;
}
- virtual bool bootstrap() {
- return true;
+ void setBatchCount(uint64_t count) {
+ batch_count_ = count;
}
- // Return -1 when any error occurs
- virtual int16_t send(const utils::Identifier& transactionID, DataPacket* packet, const std::shared_ptr<core::FlowFile>& flowFile, core::ProcessSession* session);
+ void setBatchDuration(std::chrono::milliseconds duration) {
+ batch_duration_ = duration;
+ }
- protected:
- // Cancel the transaction
- virtual void cancel(const utils::Identifier &transactionID);
- // Complete the transaction
- virtual bool complete(core::ProcessContext& context, const utils::Identifier &transactionID);
- // Error the transaction
- virtual void error(const utils::Identifier &transactionID);
+ virtual void setTimeout(std::chrono::milliseconds timeout) {
+ timeout_ = timeout;
+ }
- virtual bool confirm(const utils::Identifier &transactionID);
- // deleteTransaction
- virtual void deleteTransaction(const utils::Identifier &transactionID);
+ protected:
+ friend class test::SiteToSiteClientTestAccessor;
+ virtual bool bootstrap() = 0;
+ virtual bool establish() = 0;
+ virtual std::shared_ptr<Transaction> createTransaction(TransferDirection direction) = 0;
virtual void tearDown() = 0;
- // read Respond
- virtual int readResponse(const std::shared_ptr<Transaction> &transaction, RespondCode &code, std::string &message);
- // write respond
- virtual int writeResponse(const std::shared_ptr<Transaction> &transaction, RespondCode code, const std::string& message);
- // getRespondCodeContext
- virtual RespondCodeContext *getRespondCodeContext(RespondCode code) {
- for (auto & i : SiteToSiteRequest::respondCodeContext) {
- if (i.code == code) {
- return &i;
- }
- }
- return nullptr;
- }
+ virtual void deleteTransaction(const utils::Identifier &transaction_id);
+ virtual std::optional<SiteToSiteResponse> readResponse(const std::shared_ptr<Transaction> &transaction);
+ virtual bool writeResponse(const std::shared_ptr<Transaction> &transaction, const SiteToSiteResponse& response);
- // Peer State
- PeerState peer_state_{PeerState::IDLE};
+ bool initializeSend(const std::shared_ptr<Transaction>& transaction);
+ bool writeAttributesInSendTransaction(const std::shared_ptr<Transaction>& transaction, const std::map<std::string, std::string>& attributes);
+ void finalizeSendTransaction(const std::shared_ptr<Transaction>& transaction, uint64_t sent_bytes);
+ bool sendPacket(const DataPacket& packet);
+ bool sendFlowFile(const std::shared_ptr<Transaction>& transaction, core::FlowFile& flow_file, core::ProcessSession& session);
- // portId
- utils::Identifier port_id_;
+ void cancel(const utils::Identifier &transaction_id);
+ bool complete(core::ProcessContext& context, const utils::Identifier &transaction_id);
+ void error(const utils::Identifier &transaction_id);
+ bool confirm(const utils::Identifier &transaction_id);
- // idleTimeout
- std::chrono::milliseconds idle_timeout_{15000};
+ void handleTransactionError(const std::shared_ptr<Transaction>& transaction, core::ProcessContext& context, const std::exception& exception);
- // Peer Connection
- std::unique_ptr<SiteToSitePeer> peer_;
-
- std::atomic<bool> running_{false};
-
- // transaction map
+ PeerState peer_state_{PeerState::IDLE};
+ utils::Identifier port_id_;
+ std::chrono::milliseconds idle_timeout_{15s};
+ gsl::not_null<std::unique_ptr<SiteToSitePeer>> peer_;
std::map<utils::Identifier, std::shared_ptr<Transaction>> known_transactions_;
+ std::chrono::nanoseconds batch_send_nanos_{5s};
- // BATCH_SEND_NANOS
- std::chrono::nanoseconds _batchSendNanos = std::chrono::seconds(5);
-
- /***
- * versioning
- */
- uint32_t _supportedVersion[5] = {5, 4, 3, 2, 1};
- int _currentVersionIndex{0};
- uint32_t _currentVersion{_supportedVersion[_currentVersionIndex]};
- uint32_t _supportedCodecVersion[1] = {1};
- int _currentCodecVersionIndex{0};
- uint32_t _currentCodecVersion{_supportedCodecVersion[_currentCodecVersionIndex]};
+ const std::vector<uint32_t> supported_versions_ = {5, 4, 3, 2, 1};
+ uint32_t current_version_index_{0};
+ uint32_t current_version_{supported_versions_[current_version_index_]};
+ const std::vector<uint32_t> supported_codec_versions_ = {1};
+ uint32_t current_codec_version_index_{0};
+ uint32_t current_codec_version_{supported_codec_versions_[current_codec_version_index_]};
std::shared_ptr<minifi::controllers::SSLContextServiceInterface> ssl_context_service_;
+ std::atomic_bool use_compression_{false};
+ std::atomic<uint64_t> batch_count_{0};
+ std::atomic<uint64_t> batch_size_{0};
+ std::atomic<std::chrono::milliseconds> batch_duration_{0s};
+ std::atomic<std::chrono::milliseconds> timeout_{0s};
+
private:
+ struct ReceiveFlowFileHeaderResult {
+ std::map<std::string, std::string> attributes;
+ size_t flow_file_data_size = 0;
+ bool eof{false};
+ };
+
+ static const ResponseCodeContext* getResponseCodeContext(ResponseCode code);
+ bool transferFlowFiles(core::ProcessContext& context, core::ProcessSession& session);
+ bool receiveFlowFiles(core::ProcessContext& context, core::ProcessSession& session);
+
+ bool confirmReceive(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id);
+ bool confirmSend(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id);
+ bool completeReceive(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id);
+ bool completeSend(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id, core::ProcessContext& context);
+
+ bool readFlowFileHeaderData(const std::shared_ptr<Transaction>& transaction, SiteToSiteClient::ReceiveFlowFileHeaderResult& result);
+ std::optional<ReceiveFlowFileHeaderResult> receiveFlowFileHeader(const std::shared_ptr<Transaction>& transaction);
+ std::pair<uint64_t, uint64_t> readFlowFiles(const std::shared_ptr<Transaction>& transaction, core::ProcessSession& session);
+
std::shared_ptr<core::logging::Logger> logger_{core::logging::LoggerFactory<SiteToSiteClient>::getLogger()};
};
-} // namespace org::apache::nifi::minifi::sitetosite
+} // namespace sitetosite
+} // namespace org::apache::nifi::minifi
diff --git a/libminifi/include/sitetosite/SiteToSiteFactory.h b/libminifi/include/sitetosite/SiteToSiteFactory.h
index e766c2efe..f06719173 100644
--- a/libminifi/include/sitetosite/SiteToSiteFactory.h
+++ b/libminifi/include/sitetosite/SiteToSiteFactory.h
@@ -17,73 +17,12 @@
*/
#pragma once
-#include <utility>
-#include <memory>
-
-#include "RawSocketProtocol.h"
#include "SiteToSite.h"
#include "Peer.h"
#include "SiteToSiteClient.h"
-#include "utils/net/AsioSocketUtils.h"
namespace org::apache::nifi::minifi::sitetosite {
-/**
- * Create a streaming peer from the provided client configuration
- * @param client_configuration client configuration reference
- * @returns SiteToSitePeer
- */
-static std::unique_ptr<SiteToSitePeer> createStreamingPeer(const SiteToSiteClientConfiguration &client_configuration) {
- utils::net::SocketData socket_data{client_configuration.getPeer()->getHost(), client_configuration.getPeer()->getPort(), client_configuration.getSecurityContext()};
- auto connection = std::make_unique<utils::net::AsioSocketConnection>(socket_data);
- auto peer = std::make_unique<SiteToSitePeer>(std::move(connection), client_configuration.getPeer()->getHost(), client_configuration.getPeer()->getPort(), client_configuration.getInterface());
- return peer;
-}
-
-/**
- * Creates a raw socket client.
- * RawSiteToSiteClient will be instantiated and returned through a unique ptr.
- */
-static std::unique_ptr<SiteToSiteClient> createRawSocket(const SiteToSiteClientConfiguration &client_configuration) {
- utils::Identifier uuid = client_configuration.getPeer()->getPortId();
- auto rsptr = createStreamingPeer(client_configuration);
- if (nullptr == rsptr) {
- return nullptr;
- }
- auto ptr = std::unique_ptr<SiteToSiteClient>(new RawSiteToSiteClient(std::move(rsptr)));
- ptr->setPortId(uuid);
- ptr->setSSLContextService(client_configuration.getSecurityContext());
- return ptr;
-}
-
-/**
- * Returns a client based on the client configuratin's client type.
- * Currently only HTTP and RAW are supported.
- * @param client_configuration client configuration reference
- * @returns site to site client or nullptr.
- */
-static std::unique_ptr<SiteToSiteClient> createClient(const SiteToSiteClientConfiguration &client_configuration) {
- utils::Identifier uuid = client_configuration.getPeer()->getPortId();
- switch (client_configuration.getClientType()) {
- case RAW:
- return createRawSocket(client_configuration);
- case HTTP:
- auto http_protocol = core::ClassLoader::getDefaultClassLoader().instantiateRaw("HttpProtocol", "HttpProtocol");
- if (nullptr != http_protocol) {
- auto ptr = std::unique_ptr<SiteToSiteClient>(dynamic_cast<SiteToSiteClient*>(http_protocol));
- ptr->setSSLContextService(client_configuration.getSecurityContext());
- auto peer = std::unique_ptr<SiteToSitePeer>(new SiteToSitePeer(client_configuration.getPeer()->getHost(), client_configuration.getPeer()->getPort(),
- client_configuration.getInterface()));
- peer->setHTTPProxy(client_configuration.getHTTPProxy());
-
- ptr->setPortId(uuid);
- ptr->setPeer(std::move(peer));
- ptr->setIdleTimeout(client_configuration.getIdleTimeout());
- return ptr;
- }
- return nullptr;
- }
- return nullptr;
-}
+gsl::not_null<std::unique_ptr<SiteToSiteClient>> createClient(const SiteToSiteClientConfiguration &client_configuration);
} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/RemoteProcessGroupPort.cpp b/libminifi/src/RemoteProcessGroupPort.cpp
new file mode 100644
index 000000000..98fdc08cd
--- /dev/null
+++ b/libminifi/src/RemoteProcessGroupPort.cpp
@@ -0,0 +1,369 @@
+/**
+ * @file RemoteProcessGroupPort.cpp
+ * RemoteProcessGroupPort class implementation
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "RemoteProcessGroupPort.h"
+
+#include <cinttypes>
+#include <iostream>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "Exception.h"
+#include "controllers/SSLContextService.h"
+#include "core/ProcessContext.h"
+#include "core/Processor.h"
+#include "core/logging/Logger.h"
+#include "http/BaseHTTPClient.h"
+#include "rapidjson/document.h"
+#include "sitetosite/Peer.h"
+#include "sitetosite/SiteToSiteFactory.h"
+#include "utils/net/DNS.h"
+
+#undef GetObject // windows.h #defines GetObject = GetObjectA or GetObjectW, which conflicts with rapidjson
+
+using namespace std::literals::chrono_literals;
+
+namespace org::apache::nifi::minifi {
+
+namespace {
+std::string buildFullSiteToSiteUrl(const RPG& nifi) {
+ std::stringstream full_url;
+ full_url << nifi.protocol << nifi.host;
+ // don't append port if it is 0 ( undefined )
+ if (nifi.port > 0) {
+ full_url << ":" << std::to_string(nifi.port);
+ }
+ full_url << "/nifi-api/site-to-site";
+ return full_url.str();
+}
+} // namespace
+
+const char *RemoteProcessGroupPort::RPG_SSL_CONTEXT_SERVICE_NAME = "RemoteProcessGroupPortSSLContextService";
+
+void RemoteProcessGroupPort::setURL(const std::string& val) {
+ auto urls = utils::string::split(val, ",");
+ for (const auto& url : urls) {
+ http::URL parsed_url{utils::string::trim(url)};
+ if (parsed_url.isValid()) {
+ logger_->log_debug("Parsed RPG URL '{}' -> '{}'", url, parsed_url.hostPort());
+ nifi_instances_.push_back({parsed_url.host(), parsed_url.port(), parsed_url.protocol()});
+ } else {
+ logger_->log_error("Could not parse RPG URL '{}'", url);
+ }
+ }
+}
+
+gsl::not_null<std::unique_ptr<sitetosite::SiteToSiteClient>> RemoteProcessGroupPort::initializeProtocol(sitetosite::SiteToSiteClientConfiguration& config) const {
+ config.setSecurityContext(ssl_service_);
+ config.setHTTPProxy(proxy_);
+ config.setIdleTimeout(idle_timeout_);
+ config.setUseCompression(use_compression_);
+ config.setBatchCount(batch_count_);
+ config.setBatchSize(batch_size_);
+ config.setBatchDuration(batch_duration_);
+ config.setTimeout(timeout_);
+
+ return sitetosite::createClient(config);
+}
+
+std::unique_ptr<sitetosite::SiteToSiteClient> RemoteProcessGroupPort::getNextProtocol() {
+ std::unique_ptr<sitetosite::SiteToSiteClient> next_protocol = nullptr;
+ if (!available_protocols_.try_dequeue(next_protocol)) {
+ std::lock_guard<std::mutex> lock(peer_mutex_);
+ if (peer_index_ >= 0) {
+ logger_->log_debug("Creating client from peer {}", peer_index_);
+ auto& peer_status = peers_[peer_index_];
+ sitetosite::SiteToSiteClientConfiguration config(peer_status.getPortId(), peer_status.getHost(), peer_status.getPort(), local_network_interface_, client_type_);
+ peer_index_++;
+ if (peer_index_ >= static_cast<int>(peers_.size())) {
+ peer_index_ = 0;
+ }
+ next_protocol = initializeProtocol(config);
+ } else {
+ logger_->log_debug("Refreshing the peer list since there are none configured.");
+ refreshPeerList();
+ }
+ }
+ logger_->log_debug("Obtained protocol from available_protocols_");
+ return next_protocol;
+}
+
+void RemoteProcessGroupPort::returnProtocol(core::ProcessContext& context, std::unique_ptr<sitetosite::SiteToSiteClient> return_protocol) {
+ auto count = std::max<size_t>(context.getProcessor().getMaxConcurrentTasks(), peers_.size());
+ if (available_protocols_.size_approx() >= count) {
+ logger_->log_debug("not enqueueing protocol {}", getUUIDStr());
+ // let the memory be freed
+ return;
+ }
+ logger_->log_debug("enqueueing protocol {}, have a total of {}", getUUIDStr(), available_protocols_.size_approx());
+ available_protocols_.enqueue(std::move(return_protocol));
+}
+
+void RemoteProcessGroupPort::initialize() {
+ setSupportedProperties(Properties);
+ setSupportedRelationships(Relationships);
+
+ logger_->log_trace("Finished initialization");
+}
+
+void RemoteProcessGroupPort::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory&) {
+ if (auto protocol_uuid = context.getProperty(portUUID)) {
+ protocol_uuid_ = *protocol_uuid;
+ }
+
+ auto context_name = context.getProperty(SSLContext);
+ if (!context_name || IsNullOrEmpty(*context_name)) {
+ context_name = RPG_SSL_CONTEXT_SERVICE_NAME;
+ }
+
+ std::shared_ptr<core::controller::ControllerService> service = context.getControllerService(*context_name, getUUID());
+ if (nullptr != service) {
+ ssl_service_ = std::dynamic_pointer_cast<minifi::controllers::SSLContextServiceInterface>(service);
+ } else {
+ std::string secureStr;
+ if (configure_->get(Configure::nifi_remote_input_secure, secureStr) && utils::string::toBool(secureStr).value_or(false)) {
+ ssl_service_ = std::make_shared<minifi::controllers::SSLContextService>(RPG_SSL_CONTEXT_SERVICE_NAME, configure_);
+ ssl_service_->onEnable();
+ }
+ }
+
+ idle_timeout_ = context.getProperty(idleTimeout) | utils::andThen(parsing::parseDuration<std::chrono::milliseconds>) | utils::orThrow("RemoteProcessGroupPort::idleTimeout is a required Property");
+
+ std::lock_guard<std::mutex> lock(peer_mutex_);
+ if (!nifi_instances_.empty()) {
+ refreshPeerList();
+ if (!peers_.empty())
+ peer_index_ = 0;
+ }
+ // populate the site2site protocol for load balancing between them
+ if (!peers_.empty()) {
+ auto count = std::max<size_t>(context.getProcessor().getMaxConcurrentTasks(), peers_.size());
+ for (uint32_t i = 0; i < count; i++) {
+ auto peer_status = peers_[peer_index_];
+ sitetosite::SiteToSiteClientConfiguration config(peer_status.getPortId(), peer_status.getHost(), peer_status.getPort(), local_network_interface_, client_type_);
+ peer_index_++;
+ if (peer_index_ >= static_cast<int>(peers_.size())) {
+ peer_index_ = 0;
+ }
+ logger_->log_trace("Creating client");
+ auto next_protocol = initializeProtocol(config);
+ logger_->log_trace("Created client, moving into available protocols");
+ returnProtocol(context, std::move(next_protocol));
+ }
+ } else {
+ // we don't have any peers
+ logger_->log_error("No peers selected during scheduling");
+ }
+}
+
+void RemoteProcessGroupPort::notifyStop() {
+ transmitting_ = false;
+ std::unique_ptr<sitetosite::SiteToSiteClient> next_protocol = nullptr;
+ while (available_protocols_.try_dequeue(next_protocol)) {
+ // clear all protocols now
+ }
+}
+
+void RemoteProcessGroupPort::onTrigger(core::ProcessContext& context, core::ProcessSession& session) {
+ logger_->log_trace("On trigger {}", getUUIDStr());
+ if (!transmitting_) {
+ return;
+ }
+
+ try {
+ logger_->log_trace("get protocol in on trigger");
+ auto protocol = getNextProtocol();
+
+ if (!protocol) {
+ logger_->log_info("no protocol, yielding");
+ context.yield();
+ return;
+ }
+
+ if (!protocol->transfer(direction_, context, session)) {
+ logger_->log_warn("protocol transmission failed, yielding");
+ context.yield();
+ }
+
+ returnProtocol(context, std::move(protocol));
+ } catch (const std::exception&) {
+ context.yield();
+ session.rollback();
+ }
+}
+
+std::optional<std::string> RemoteProcessGroupPort::getRestApiToken(const RPG& nifi) const {
+ std::string rest_user_name;
+ configure_->get(Configure::nifi_rest_api_user_name, rest_user_name);
+ if (rest_user_name.empty()) {
+ return std::nullopt;
+ }
+
+ std::string rest_password;
+ configure_->get(Configure::nifi_rest_api_password, rest_password);
+
+ std::stringstream login_url;
+ login_url << nifi.protocol << nifi.host;
+ // don't append port if it is 0 ( undefined )
+ if (nifi.port > 0) {
+ login_url << ":" << std::to_string(nifi.port);
+ }
+ login_url << "/nifi-api/access/token";
+
+ auto client_ptr = core::ClassLoader::getDefaultClassLoader().instantiateRaw("HTTPClient", "HTTPClient");
+ if (nullptr == client_ptr) {
+ logger_->log_error("Could not locate HTTPClient. You do not have cURL support!");
+ return std::nullopt;
+ }
+ auto client = std::unique_ptr<http::BaseHTTPClient>(dynamic_cast<http::BaseHTTPClient*>(client_ptr));
+ client->initialize(http::HttpRequestMethod::GET, login_url.str(), ssl_service_);
+ // use a connection timeout. if this times out we will simply attempt re-connection
+ // so no need for configuration parameter that isn't already defined in Processor
+ client->setConnectionTimeout(10s);
+ client->setReadTimeout(idle_timeout_);
+
+ auto token = http::get_token(client.get(), rest_user_name, rest_password);
+ logger_->log_debug("Got token from NiFi REST Api endpoint {}", login_url.str());
+ return token;
+}
+
+std::optional<std::pair<std::string, uint16_t>> RemoteProcessGroupPort::parseSiteToSiteDataFromControllerConfig(const RPG& nifi, const std::string& controller) const {
+ rapidjson::Document doc;
+ rapidjson::ParseResult ok = doc.Parse(controller.c_str());
+
+ if (!ok || !doc.IsObject() || doc.ObjectEmpty()) {
+ return std::nullopt;
+ }
+
+ rapidjson::Value::MemberIterator itr = doc.FindMember("controller");
+
+ if (itr == doc.MemberEnd() || !itr->value.IsObject()) {
+ return std::nullopt;
+ }
+
+ rapidjson::Value controllerValue = itr->value.GetObject();
+ rapidjson::Value::ConstMemberIterator end_itr = controllerValue.MemberEnd();
+ rapidjson::Value::ConstMemberIterator port_itr = controllerValue.FindMember("remoteSiteListeningPort");
+ rapidjson::Value::ConstMemberIterator secure_itr = controllerValue.FindMember("siteToSiteSecure");
+ bool site_to_site_secure = secure_itr != end_itr && secure_itr->value.IsBool() ? secure_itr->value.GetBool() : false;
+
+ uint16_t site_to_site_port = 0;
+ if (client_type_ == sitetosite::ClientType::RAW && port_itr != end_itr && port_itr->value.IsNumber()) {
+ site_to_site_port = port_itr->value.GetInt();
+ } else {
+ site_to_site_port = nifi.port;
+ }
+
+ logger_->log_debug("process group remote site2site port {}, is secure {}", site_to_site_port, site_to_site_secure);
+ return std::make_pair(nifi.host, site_to_site_port);
+}
+
+std::optional<std::pair<std::string, uint16_t>> RemoteProcessGroupPort::tryRefreshSiteToSiteInstance(RPG nifi) const { // NOLINT(performance-unnecessary-value-param)
+#ifdef WIN32
+ if ("localhost" == nifi.host) {
+ nifi.host = org::apache::nifi::minifi::utils::net::getMyHostName();
+ }
+#endif
+ auto token = getRestApiToken(nifi);
+ if (token && token->empty()) {
+ return std::nullopt;
+ }
+
+ auto client_ptr = core::ClassLoader::getDefaultClassLoader().instantiateRaw("HTTPClient", "HTTPClient");
+ if (nullptr == client_ptr) {
+ logger_->log_error("Could not locate HTTPClient. You do not have cURL support, defaulting to base configuration!");
+ return std::nullopt;
+ }
+
+ auto client = std::unique_ptr<http::BaseHTTPClient>(dynamic_cast<http::BaseHTTPClient*>(client_ptr));
+ auto full_url = buildFullSiteToSiteUrl(nifi);
+ client->initialize(http::HttpRequestMethod::GET, full_url, ssl_service_);
+ // use a connection timeout. if this times out we will simply attempt re-connection
+ // so no need for configuration parameter that isn't already defined in Processor
+ client->setConnectionTimeout(10s);
+ client->setReadTimeout(idle_timeout_);
+ if (!proxy_.host.empty()) {
+ client->setHTTPProxy(proxy_);
+ }
+ if (token) {
+ client->setRequestHeader("Authorization", token);
+ }
+
+ client->setVerbose(false);
+
+ if (!client->submit() || client->getResponseCode() != 200) {
+ logger_->log_error("ProcessGroup::refreshRemoteSiteToSiteInfo -- curl_easy_perform() failed , response code {}\n", client->getResponseCode());
+ return std::nullopt;
+ }
+
+ const std::vector<char> &response_body = client->getResponseBody();
+ if (response_body.empty()) {
+ logger_->log_error("Cannot output body to content for ProcessGroup::refreshRemoteSiteToSiteInfo: received HTTP code {} from {}", client->getResponseCode(), full_url);
+ return std::nullopt;
+ }
+
+ std::string controller = std::string(response_body.begin(), response_body.end());
+ logger_->log_trace("controller config {}", controller);
+ return parseSiteToSiteDataFromControllerConfig(nifi, controller);
+}
+
+std::optional<std::pair<std::string, uint16_t>> RemoteProcessGroupPort::refreshRemoteSiteToSiteInfo() {
+ if (nifi_instances_.empty()) {
+ return std::nullopt;
+ }
+
+ for (const auto& nifi : nifi_instances_) {
+ auto result = tryRefreshSiteToSiteInstance(nifi);
+ if (result) {
+ return result;
+ }
+ }
+ return std::nullopt;
+}
+
+void RemoteProcessGroupPort::refreshPeerList() {
+ auto connection = refreshRemoteSiteToSiteInfo();
+ if (!connection) {
+ logger_->log_warn("No port configured");
+ return;
+ }
+
+ peers_.clear();
+
+ std::unique_ptr<sitetosite::SiteToSiteClient> protocol;
+ sitetosite::SiteToSiteClientConfiguration config(protocol_uuid_, connection->first, connection->second, local_network_interface_, client_type_);
+ protocol = initializeProtocol(config);
+
+ if (protocol) {
+ if (auto peers = protocol->getPeerList()) {
+ peers_ = *peers;
+ }
+ }
+
+ logger_->log_info("Have {} peers", peers_.size());
+
+ if (!peers_.empty()) {
+ peer_index_ = 0;
+ }
+}
+
+} // namespace org::apache::nifi::minifi
diff --git a/libminifi/src/RemoteProcessorGroupPort.cpp b/libminifi/src/RemoteProcessorGroupPort.cpp
deleted file mode 100644
index 3f1b99179..000000000
--- a/libminifi/src/RemoteProcessorGroupPort.cpp
+++ /dev/null
@@ -1,354 +0,0 @@
-/**
- * @file RemoteProcessorGroupPort.cpp
- * RemoteProcessorGroupPort class implementation
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "RemoteProcessorGroupPort.h"
-
-#include <cinttypes>
-#include <iostream>
-#include <memory>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "Exception.h"
-#include "controllers/SSLContextService.h"
-#include "core/ProcessContext.h"
-#include "core/Processor.h"
-#include "core/logging/Logger.h"
-#include "http/BaseHTTPClient.h"
-#include "rapidjson/document.h"
-#include "sitetosite/Peer.h"
-#include "sitetosite/SiteToSiteFactory.h"
-#include "utils/net/DNS.h"
-
-#undef GetObject // windows.h #defines GetObject = GetObjectA or GetObjectW, which conflicts with rapidjson
-
-using namespace std::literals::chrono_literals;
-
-namespace org::apache::nifi::minifi {
-
-const char *RemoteProcessorGroupPort::RPG_SSL_CONTEXT_SERVICE_NAME = "RemoteProcessorGroupPortSSLContextService";
-
-std::unique_ptr<sitetosite::SiteToSiteClient> RemoteProcessorGroupPort::getNextProtocol(bool create = true) {
- std::unique_ptr<sitetosite::SiteToSiteClient> nextProtocol = nullptr;
- if (!available_protocols_.try_dequeue(nextProtocol)) {
- if (create) {
- // create
- if (bypass_rest_api_) {
- if (!nifi_instances_.empty()) {
- auto rpg = nifi_instances_.front();
- auto host = rpg.host_;
-#ifdef WIN32
- if ("localhost" == host) {
- host = org::apache::nifi::minifi::utils::net::getMyHostName();
- }
-#endif
- sitetosite::SiteToSiteClientConfiguration config(std::make_shared<sitetosite::Peer>(protocol_uuid_, host, rpg.port_, ssl_service != nullptr), this->getInterface(),
- client_type_);
- config.setHTTPProxy(this->proxy_);
- config.setIdleTimeout(idle_timeout_);
- nextProtocol = sitetosite::createClient(config);
- }
- } else if (peer_index_ >= 0) {
- std::lock_guard<std::mutex> lock(peer_mutex_);
- logger_->log_debug("Creating client from peer {}", peer_index_.load());
- sitetosite::SiteToSiteClientConfiguration config(peers_[this->peer_index_].getPeer(), local_network_interface_, client_type_);
- config.setSecurityContext(ssl_service);
- peer_index_++;
- if (peer_index_ >= static_cast<int>(peers_.size())) {
- peer_index_ = 0;
- }
- config.setHTTPProxy(this->proxy_);
- config.setIdleTimeout(idle_timeout_);
- nextProtocol = sitetosite::createClient(config);
- } else {
- logger_->log_debug("Refreshing the peer list since there are none configured.");
- refreshPeerList();
- }
- }
- }
- logger_->log_debug("Obtained protocol from available_protocols_");
- return nextProtocol;
-}
-
-void RemoteProcessorGroupPort::returnProtocol(core::ProcessContext& context, std::unique_ptr<sitetosite::SiteToSiteClient> return_protocol) {
- auto count = peers_.size();
- if (context.getProcessor().getMaxConcurrentTasks() > count)
- count = context.getProcessor().getMaxConcurrentTasks();
- if (available_protocols_.size_approx() >= count) {
- logger_->log_debug("not enqueueing protocol {}", getUUIDStr());
- // let the memory be freed
- return;
- }
- logger_->log_debug("enqueueing protocol {}, have a total of {}", getUUIDStr(), available_protocols_.size_approx());
- available_protocols_.enqueue(std::move(return_protocol));
-}
-
-void RemoteProcessorGroupPort::initialize() {
- setSupportedProperties(Properties);
- setSupportedRelationships(Relationships);
-
- logger_->log_trace("Finished initialization");
-}
-
-void RemoteProcessorGroupPort::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory&) {
- if (auto protocol_uuid = context.getProperty(portUUID)) {
- protocol_uuid_ = *protocol_uuid;
- }
-
- auto context_name = context.getProperty(SSLContext);
- if (!context_name || IsNullOrEmpty(*context_name)) {
- context_name = RPG_SSL_CONTEXT_SERVICE_NAME;
- }
-
- std::shared_ptr<core::controller::ControllerService> service = context.getControllerService(*context_name, getUUID());
- if (nullptr != service) {
- ssl_service = std::dynamic_pointer_cast<minifi::controllers::SSLContextServiceInterface>(service);
- } else {
- std::string secureStr;
- if (configure_->get(Configure::nifi_remote_input_secure, secureStr) && utils::string::toBool(secureStr).value_or(false)) {
- ssl_service = std::make_shared<minifi::controllers::SSLContextService>(RPG_SSL_CONTEXT_SERVICE_NAME, configure_);
- ssl_service->onEnable();
- }
- }
-
- idle_timeout_ = context.getProperty(idleTimeout) | utils::andThen(parsing::parseDuration<std::chrono::milliseconds>) | utils::orThrow("RemoteProcessGroupPort::idleTimeout is a required Property");
-
- std::lock_guard<std::mutex> lock(peer_mutex_);
- if (!nifi_instances_.empty()) {
- refreshPeerList();
- if (!peers_.empty())
- peer_index_ = 0;
- }
- // populate the site2site protocol for load balancing between them
- if (!peers_.empty()) {
- auto count = peers_.size();
- if (context.getProcessor().getMaxConcurrentTasks() > count)
- count = context.getProcessor().getMaxConcurrentTasks();
- for (uint32_t i = 0; i < count; i++) {
- std::unique_ptr<sitetosite::SiteToSiteClient> nextProtocol = nullptr;
- sitetosite::SiteToSiteClientConfiguration config(peers_[this->peer_index_].getPeer(), this->getInterface(), client_type_);
- config.setSecurityContext(ssl_service);
- peer_index_++;
- if (peer_index_ >= static_cast<int>(peers_.size())) {
- peer_index_ = 0;
- }
- logger_->log_trace("Creating client");
- config.setHTTPProxy(this->proxy_);
- config.setIdleTimeout(idle_timeout_);
- nextProtocol = sitetosite::createClient(config);
- logger_->log_trace("Created client, moving into available protocols");
- returnProtocol(context, std::move(nextProtocol));
- }
- } else {
- // we don't have any peers
- logger_->log_error("No peers selected during scheduling");
- }
-}
-
-void RemoteProcessorGroupPort::notifyStop() {
- transmitting_ = false;
- RPGLatch count(false); // we're just a monitor
- // we use the latch
- while (count.getCount() > 0) {
- }
- std::unique_ptr<sitetosite::SiteToSiteClient> nextProtocol = nullptr;
- while (available_protocols_.try_dequeue(nextProtocol)) {
- // clear all protocols now
- }
-}
-
-void RemoteProcessorGroupPort::onTrigger(core::ProcessContext& context, core::ProcessSession& session) {
- logger_->log_trace("On trigger {}", getUUIDStr());
- if (!transmitting_) {
- return;
- }
-
- RPGLatch count;
-
- std::string value;
-
- logger_->log_trace("On trigger {}", getUUIDStr());
-
- std::unique_ptr<sitetosite::SiteToSiteClient> protocol_ = nullptr;
- try {
- logger_->log_trace("get protocol in on trigger");
- protocol_ = getNextProtocol();
-
- if (!protocol_) {
- logger_->log_info("no protocol, yielding");
- context.yield();
- return;
- }
-
- if (!protocol_->transfer(direction_, context, session)) {
- logger_->log_warn("protocol transmission failed, yielding");
- context.yield();
- }
-
- returnProtocol(context, std::move(protocol_));
- return;
- } catch (const minifi::Exception &) {
- context.yield();
- session.rollback();
- } catch (...) {
- context.yield();
- session.rollback();
- }
-}
-
-std::pair<std::string, int> RemoteProcessorGroupPort::refreshRemoteSite2SiteInfo() {
- if (nifi_instances_.empty())
- return std::make_pair("", -1);
-
- for (const auto& nifi : nifi_instances_) {
- std::string host = nifi.host_;
-#ifdef WIN32
- if ("localhost" == host) {
- host = org::apache::nifi::minifi::utils::net::getMyHostName();
- }
-#endif
- std::string protocol = nifi.protocol_;
- int nifi_port = nifi.port_;
- std::stringstream fullUrl;
- fullUrl << protocol << host;
- // don't append port if it is 0 ( undefined )
- if (nifi_port > 0) {
- fullUrl << ":" << std::to_string(nifi_port);
- }
- fullUrl << "/nifi-api/site-to-site";
-
- configure_->get(Configure::nifi_rest_api_user_name, this->rest_user_name_);
- configure_->get(Configure::nifi_rest_api_password, this->rest_password_);
-
- std::string token;
- std::unique_ptr<http::BaseHTTPClient> client;
- if (!rest_user_name_.empty()) {
- std::stringstream loginUrl;
- loginUrl << protocol << host;
- // don't append port if it is 0 ( undefined )
- if (nifi_port > 0) {
- loginUrl << ":" << std::to_string(nifi_port);
- }
- loginUrl << "/nifi-api/access/token";
-
- auto client_ptr = core::ClassLoader::getDefaultClassLoader().instantiateRaw("HTTPClient", "HTTPClient");
- if (nullptr == client_ptr) {
- logger_->log_error("Could not locate HTTPClient. You do not have cURL support!");
- return std::make_pair("", -1);
- }
- client = std::unique_ptr<http::BaseHTTPClient>(dynamic_cast<http::BaseHTTPClient*>(client_ptr));
- client->initialize(http::HttpRequestMethod::GET, loginUrl.str(), ssl_service);
- // use a connection timeout. if this times out we will simply attempt re-connection
- // so no need for configuration parameter that isn't already defined in Processor
- client->setConnectionTimeout(10s);
- client->setReadTimeout(idle_timeout_);
-
- token = http::get_token(client.get(), this->rest_user_name_, this->rest_password_);
- logger_->log_debug("Token from NiFi REST Api endpoint {}, {}", loginUrl.str(), token);
- if (token.empty())
- return std::make_pair("", -1);
- }
-
- auto client_ptr = core::ClassLoader::getDefaultClassLoader().instantiateRaw("HTTPClient", "HTTPClient");
- if (nullptr == client_ptr) {
- logger_->log_error("Could not locate HTTPClient. You do not have cURL support, defaulting to base configuration!");
- return std::make_pair("", -1);
- }
- int siteTosite_port_ = -1;
- client = std::unique_ptr<http::BaseHTTPClient>(dynamic_cast<http::BaseHTTPClient*>(client_ptr));
- client->initialize(http::HttpRequestMethod::GET, fullUrl.str(), ssl_service);
- // use a connection timeout. if this times out we will simply attempt re-connection
- // so no need for configuration parameter that isn't already defined in Processor
- client->setConnectionTimeout(10s);
- client->setReadTimeout(idle_timeout_);
- if (!proxy_.host.empty()) {
- client->setHTTPProxy(proxy_);
- }
- if (!token.empty())
- client->setRequestHeader("Authorization", token);
-
- client->setVerbose(false);
-
- if (client->submit() && client->getResponseCode() == 200) {
- const std::vector<char> &response_body = client->getResponseBody();
- if (!response_body.empty()) {
- std::string controller = std::string(response_body.begin(), response_body.end());
- logger_->log_trace("controller config {}", controller);
- rapidjson::Document doc;
- rapidjson::ParseResult ok = doc.Parse(controller.c_str());
-
- if (ok && doc.IsObject() && !doc.ObjectEmpty()) {
- rapidjson::Value::MemberIterator itr = doc.FindMember("controller");
-
- if (itr != doc.MemberEnd() && itr->value.IsObject()) {
- rapidjson::Value controllerValue = itr->value.GetObject();
- rapidjson::Value::ConstMemberIterator end_itr = controllerValue.MemberEnd();
- rapidjson::Value::ConstMemberIterator port_itr = controllerValue.FindMember("remoteSiteListeningPort");
- rapidjson::Value::ConstMemberIterator secure_itr = controllerValue.FindMember("siteToSiteSecure");
-
- if (client_type_ == sitetosite::CLIENT_TYPE::RAW && port_itr != end_itr && port_itr->value.IsNumber())
- siteTosite_port_ = port_itr->value.GetInt();
- else
- siteTosite_port_ = nifi_port;
-
- if (secure_itr != end_itr && secure_itr->value.IsBool())
- this->site2site_secure_ = secure_itr->value.GetBool();
- }
- logger_->log_debug("process group remote site2site port {}, is secure {}", siteTosite_port_, site2site_secure_);
- return std::make_pair(host, siteTosite_port_);
- }
- } else {
- logger_->log_error("Cannot output body to content for ProcessGroup::refreshRemoteSite2SiteInfo: received HTTP code {} from {}", client->getResponseCode(), fullUrl.str());
- }
- } else {
- logger_->log_error("ProcessGroup::refreshRemoteSite2SiteInfo -- curl_easy_perform() failed , response code {}\n", client->getResponseCode());
- }
- }
- return std::make_pair("", -1);
-}
-
-void RemoteProcessorGroupPort::refreshPeerList() {
- auto connection = refreshRemoteSite2SiteInfo();
- if (connection.second == -1) {
- logger_->log_debug("No port configured");
- return;
- }
-
- this->peers_.clear();
-
- std::unique_ptr<sitetosite::SiteToSiteClient> protocol;
- sitetosite::SiteToSiteClientConfiguration config(std::make_shared<sitetosite::Peer>(protocol_uuid_, connection.first, connection.second, ssl_service != nullptr),
- this->getInterface(), client_type_);
- config.setSecurityContext(ssl_service);
- config.setHTTPProxy(this->proxy_);
- config.setIdleTimeout(idle_timeout_);
- protocol = sitetosite::createClient(config);
-
- if (protocol)
- protocol->getPeerList(peers_);
-
- logger_->log_info("Have {} peers", peers_.size());
-
- if (!peers_.empty())
- peer_index_ = 0;
-}
-
-} // namespace org::apache::nifi::minifi
diff --git a/libminifi/src/agent/JsonSchema.cpp b/libminifi/src/agent/JsonSchema.cpp
index 86a30e67a..c053b9b25 100644
--- a/libminifi/src/agent/JsonSchema.cpp
+++ b/libminifi/src/agent/JsonSchema.cpp
@@ -25,7 +25,7 @@
#include "agent/build_description.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
-#include "RemoteProcessorGroupPort.h"
+#include "RemoteProcessGroupPort.h"
#include "utils/gsl.h"
#include "range/v3/view/filter.hpp"
@@ -124,11 +124,11 @@ static std::string buildSchema(const std::unordered_map<std::string, std::string
all_rels << "\"relationships-" << escape(name) << "\": " << rels << ", ";
}
- const auto rpg_property_refs = minifi::RemoteProcessorGroupPort::Properties;
+ const auto rpg_property_refs = minifi::RemoteProcessGroupPort::Properties;
std::vector<core::Property> rpg_properties(rpg_property_refs.begin(), rpg_property_refs.end());
std::stringstream remote_port_props;
- writeProperties(rpg_properties, minifi::RemoteProcessorGroupPort::SupportsDynamicProperties, remote_port_props);
+ writeProperties(rpg_properties, minifi::RemoteProcessGroupPort::SupportsDynamicProperties, remote_port_props);
std::string process_group_properties = R"(
"Processors": {
diff --git a/libminifi/src/core/flow/FlowSchema.cpp b/libminifi/src/core/flow/FlowSchema.cpp
index 7d80603d9..06ad9fe11 100644
--- a/libminifi/src/core/flow/FlowSchema.cpp
+++ b/libminifi/src/core/flow/FlowSchema.cpp
@@ -77,6 +77,11 @@ FlowSchema FlowSchema::getDefault() {
.rpg_output_ports = {"Output Ports"},
.rpg_port_properties = {"Properties"},
.rpg_port_target_id = {},
+ .rpg_port_use_compression = {"use compression"},
+ .rpg_port_batch_size = {"batch size"},
+ .rpg_port_batch_size_count = {"count"},
+ .rpg_port_batch_size_size = {"size"},
+ .rpg_port_batch_size_duration = {"duration"},
.parameter_contexts = {"Parameter Contexts"},
.parameters = {"Parameters"},
@@ -150,6 +155,11 @@ FlowSchema FlowSchema::getNiFiFlowJson() {
.rpg_output_ports = {"outputPorts"},
.rpg_port_properties = {"properties"},
.rpg_port_target_id = {"targetId"},
+ .rpg_port_use_compression = {"useCompression"},
+ .rpg_port_batch_size = {"batchSize"},
+ .rpg_port_batch_size_count = {"count"},
+ .rpg_port_batch_size_size = {"size"},
+ .rpg_port_batch_size_duration = {"duration"},
.parameter_contexts = {"parameterContexts"},
.parameters = {"parameters"},
diff --git a/libminifi/src/core/flow/StructuredConfiguration.cpp b/libminifi/src/core/flow/StructuredConfiguration.cpp
index 82b045196..aa5e9cf64 100644
--- a/libminifi/src/core/flow/StructuredConfiguration.cpp
+++ b/libminifi/src/core/flow/StructuredConfiguration.cpp
@@ -550,11 +550,13 @@ void StructuredConfiguration::parseRemoteProcessGroup(const Node& rpg_node_seq,
group->setTransmitting(true);
group->setURL(url);
- checkRequiredField(currRpgNode, schema_.rpg_input_ports);
+ std::vector<std::string> port_nodes(std::begin(schema_.rpg_input_ports), std::end(schema_.rpg_input_ports));
+ port_nodes.insert(std::end(port_nodes), std::begin(schema_.rpg_output_ports), std::end(schema_.rpg_output_ports));
+ checkRequiredField(currRpgNode, port_nodes);
auto inputPorts = currRpgNode[schema_.rpg_input_ports];
if (inputPorts && inputPorts.isSequence()) {
for (const auto& currPort : inputPorts) {
- parseRPGPort(currPort, group.get(), sitetosite::SEND);
+ parseRPGPort(currPort, group.get(), sitetosite::TransferDirection::SEND);
} // for node
}
auto outputPorts = currRpgNode[schema_.rpg_output_ports];
@@ -562,7 +564,7 @@ void StructuredConfiguration::parseRemoteProcessGroup(const Node& rpg_node_seq,
for (const auto& currPort : outputPorts) {
logger_->log_debug("Got a current port, iterating...");
- parseRPGPort(currPort, group.get(), sitetosite::RECEIVE);
+ parseRPGPort(currPort, group.get(), sitetosite::TransferDirection::RECEIVE);
} // for node
}
parentGroup->addProcessGroup(std::move(group));
@@ -740,14 +742,47 @@ void StructuredConfiguration::parseRPGPort(const Node& port_node, core::ProcessG
"This is a UUID of the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.");
uuid = portId;
- auto port_impl = std::make_unique<minifi::RemoteProcessorGroupPort>(
+ auto port_impl = std::make_unique<minifi::RemoteProcessGroupPort>(
nameStr, parent->getURL(), this->configuration_, uuid);
auto* port = port_impl.get();
auto port_wrapper = std::make_unique<core::Processor>(nameStr, uuid, std::move(port_impl));
port->setDirection(direction);
- port->setTimeout(parent->getTimeout());
+ port->setTimeout(std::chrono::milliseconds(parent->getTimeout()));
port->setTransmitting(true);
port_wrapper->setYieldPeriodMsec(parent->getYieldPeriodMsec());
+
+ if (isFieldPresent(port_node, schema_.rpg_port_use_compression[0])) {
+ auto use_compression = port_node[schema_.rpg_port_use_compression].getBool().value_or(false);
+ logger_->log_debug("parseRPGPort: use compression => [{}]", use_compression);
+ port->setUseCompression(use_compression);
+ }
+
+ if (isFieldPresent(port_node, schema_.rpg_port_batch_size[0])) {
+ if (isFieldPresent(port_node[schema_.rpg_port_batch_size[0]], schema_.rpg_port_batch_size_count[0])) {
+ auto batch_count_str = port_node[schema_.rpg_port_batch_size[0]][schema_.rpg_port_batch_size_count[0]].getIntegerAsString().value();
+ if (auto batch_count = parsing::parseIntegral<uint64_t>(batch_count_str); batch_count) {
+ logger_->log_debug("parseRPGPort: batch count => [{}]", *batch_count);
+ port->setBatchCount(*batch_count);
+ }
+ }
+
+ if (isFieldPresent(port_node[schema_.rpg_port_batch_size[0]], schema_.rpg_port_batch_size_size[0])) {
+ auto batch_size_str = port_node[schema_.rpg_port_batch_size[0]][schema_.rpg_port_batch_size_size[0]].getIntegerAsString().value();
+ if (auto batch_size = parsing::parseDataSize(batch_size_str); batch_size) {
+ logger_->log_debug("parseRPGPort: batch size => [{}]", *batch_size);
+ port->setBatchSize(*batch_size);
+ }
+ }
+
+ if (isFieldPresent(port_node[schema_.rpg_port_batch_size[0]], schema_.rpg_port_batch_size_duration[0])) {
+ auto batch_duration_str = port_node[schema_.rpg_port_batch_size[0]][schema_.rpg_port_batch_size_duration[0]].getIntegerAsString().value();
+ if (auto batch_duration = parsing::parseDuration(batch_duration_str); batch_duration) {
+ logger_->log_debug("parseRPGPort: batch size => [{}]", *batch_duration);
+ port->setBatchDuration(*batch_duration);
+ }
+ }
+ }
+
port_wrapper->initialize();
if (!parent->getInterface().empty())
port->setInterface(parent->getInterface());
@@ -762,7 +797,7 @@ void StructuredConfiguration::parseRPGPort(const Node& port_node, core::ProcessG
if (const Node propertiesNode = port_node[schema_.rpg_port_properties]) {
parsePropertiesNode(propertiesNode, *port_wrapper, nameStr, nullptr);
} else {
- parsePropertyNodeElement(std::string(minifi::RemoteProcessorGroupPort::portUUID.name), port_node[schema_.rpg_port_target_id], *port_wrapper, nullptr);
+ parsePropertyNodeElement(std::string(minifi::RemoteProcessGroupPort::portUUID.name), port_node[schema_.rpg_port_target_id], *port_wrapper, nullptr);
validateComponentProperties(*port_wrapper, nameStr, port_node.getPath());
}
diff --git a/libminifi/src/core/flow/StructuredConnectionParser.cpp b/libminifi/src/core/flow/StructuredConnectionParser.cpp
index 870911580..fdfbcd58c 100644
--- a/libminifi/src/core/flow/StructuredConnectionParser.cpp
+++ b/libminifi/src/core/flow/StructuredConnectionParser.cpp
@@ -19,6 +19,7 @@
#include "core/flow/StructuredConnectionParser.h"
#include "core/flow/CheckRequiredField.h"
#include "Funnel.h"
+#include "RemoteProcessGroupPort.h"
namespace org::apache::nifi::minifi::core::flow {
@@ -28,7 +29,7 @@ void StructuredConnectionParser::addNewRelationshipToConnection(std::string_view
connection.addRelationship(relationship);
}
-void StructuredConnectionParser::addFunnelRelationshipToConnection(minifi::Connection& connection) const {
+void StructuredConnectionParser::addFunnelOrPortRelationshipToConnection(minifi::Connection& connection) const {
utils::Identifier srcUUID;
try {
srcUUID = getSourceUUID();
@@ -37,13 +38,17 @@ void StructuredConnectionParser::addFunnelRelationshipToConnection(minifi::Conne
}
auto processor = parent_->findProcessorById(srcUUID);
if (!processor) {
- logger_->log_error("Could not find processor with id {}", srcUUID.to_string());
+ logger_->log_error("Could not find funnel or port with id {}", srcUUID.to_string());
return;
}
auto& impl = processor->getImpl();
if (typeid(minifi::Funnel) == typeid(impl)) {
addNewRelationshipToConnection(minifi::Funnel::Success.name, connection);
+ } else if (typeid(minifi::RemoteProcessGroupPort) == typeid(impl)) {
+ addNewRelationshipToConnection(minifi::RemoteProcessGroupPort::DefaultRelationship.name, connection);
+ } else {
+ logger_->log_error("Component with id {} is neither funnel nor port", srcUUID.to_string());
}
}
@@ -59,10 +64,10 @@ void StructuredConnectionParser::configureConnectionSourceRelationships(minifi::
} else if (!relList.isSequence() && !relList.getString().value().empty()) {
addNewRelationshipToConnection(relList.getString().value(), connection);
} else {
- addFunnelRelationshipToConnection(connection);
+ addFunnelOrPortRelationshipToConnection(connection);
}
} else {
- addFunnelRelationshipToConnection(connection);
+ addFunnelOrPortRelationshipToConnection(connection);
}
}
diff --git a/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp b/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp
index 5e030fc46..c20c11f73 100644
--- a/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp
+++ b/libminifi/src/core/reporting/SiteToSiteProvenanceReportingTask.cpp
@@ -47,7 +47,7 @@ namespace org::apache::nifi::minifi::core::reporting {
const char *SiteToSiteProvenanceReportingTask::ProvenanceAppStr = "MiNiFi Flow";
void SiteToSiteProvenanceReportingTask::initialize() {
- RemoteProcessorGroupPort::initialize();
+ RemoteProcessGroupPort::initialize();
}
void setJsonStr(const std::string& key, const std::string& value, rapidjson::Value& parent, rapidjson::Document::AllocatorType& alloc) { // NOLINT
@@ -166,11 +166,11 @@ void SiteToSiteProvenanceReportingTask::onTrigger(core::ProcessContext& context,
logger_->log_debug("Captured {} records", deserialized);
std::string jsonStr;
this->getJsonReport(context, session, records, jsonStr);
- if (jsonStr.length() <= 0) {
+ if (jsonStr.empty()) {
return;
}
- auto protocol_ = getNextProtocol(true);
+ auto protocol_ = getNextProtocol();
if (!protocol_) {
context.yield();
@@ -179,7 +179,7 @@ void SiteToSiteProvenanceReportingTask::onTrigger(core::ProcessContext& context,
try {
std::map<std::string, std::string> attributes;
- if (!protocol_->transmitPayload(context, session, jsonStr, attributes)) {
+ if (!protocol_->transmitPayload(context, jsonStr, attributes)) {
context.yield();
}
} catch (...) {
diff --git a/libminifi/src/sitetosite/HTTPProtocol.cpp b/libminifi/src/sitetosite/HTTPProtocol.cpp
deleted file mode 100644
index df3fc4ff0..000000000
--- a/libminifi/src/sitetosite/HTTPProtocol.cpp
+++ /dev/null
@@ -1,304 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "sitetosite/HTTPProtocol.h"
-
-#include <chrono>
-#include <map>
-#include <string>
-#include <memory>
-#include <thread>
-#include <iostream>
-#include <vector>
-
-#include "sitetosite/PeersEntity.h"
-#include "io/CRCStream.h"
-#include "sitetosite/Peer.h"
-#include "io/validation.h"
-#include "core/Resource.h"
-#include "utils/StringUtils.h"
-
-#undef DELETE // macro on windows
-
-namespace org::apache::nifi::minifi::sitetosite {
-
-std::shared_ptr<utils::IdGenerator> HttpSiteToSiteClient::id_generator_ = utils::IdGenerator::getIdGenerator();
-
-std::optional<utils::Identifier> HttpSiteToSiteClient::parseTransactionId(const std::string &uri) {
- return utils::Identifier::parse(utils::string::partAfterLastOccurrenceOf(uri, '/'));
-}
-
-std::shared_ptr<sitetosite::Transaction> HttpSiteToSiteClient::createTransaction(sitetosite::TransferDirection direction) {
- std::string dir_str = direction == sitetosite::SEND ? "input-ports" : "output-ports";
- std::stringstream uri;
- uri << getBaseURI() << "data-transfer/" << dir_str << "/" << getPortId().to_string() << "/transactions";
- auto client = create_http_client(uri.str(), http::HttpRequestMethod::POST);
- client->setRequestHeader(PROTOCOL_VERSION_HEADER, "1");
- client->setConnectionTimeout(std::chrono::milliseconds(5000));
- client->setContentType("application/json");
- client->setRequestHeader("Accept", "application/json");
- client->setRequestHeader("Transfer-Encoding", "chunked");
- client->setPostFields("");
- client->submit();
- auto http_stream = dynamic_cast<http::HttpStream*>(peer_->getStream());
- if (peer_->getStream() != nullptr)
- logger_->log_debug("Closing {}", http_stream->getClientRef()->getURL());
- if (client->getResponseCode() == 201) {
- // parse the headers
- auto intent_name = client->getHeaderValue("x-location-uri-intent");
- if (utils::string::equalsIgnoreCase(intent_name, "transaction-url")) {
- auto url = client->getHeaderValue("Location");
-
- if (IsNullOrEmpty(url)) {
- logger_->log_debug("Location is empty");
- } else {
- org::apache::nifi::minifi::io::CRCStream<sitetosite::SiteToSitePeer> crcstream(gsl::make_not_null(peer_.get()));
- auto transaction = std::make_shared<HttpTransaction>(direction, std::move(crcstream));
- transaction->initialize(this, url);
- auto transactionId = parseTransactionId(url);
- if (!transactionId)
- return nullptr;
- transaction->setTransactionId(transactionId.value());
- std::shared_ptr<minifi::http::HTTPClient> transaction_client;
- if (transaction->getDirection() == sitetosite::SEND) {
- transaction_client = openConnectionForSending(transaction);
- } else {
- transaction_client = openConnectionForReceive(transaction);
- transaction->setDataAvailable(true);
- // 201 tells us that data is available. 200 would mean that nothing is available.
- }
-
- transaction_client->setRequestHeader(PROTOCOL_VERSION_HEADER, "1");
- peer_->setStream(std::unique_ptr<io::BaseStream>(new http::HttpStream(transaction_client)));
- logger_->log_debug("Created transaction id -{}-", transaction->getUUID().to_string());
- known_transactions_[transaction->getUUID()] = transaction;
- return transaction;
- }
- } else {
- logger_->log_debug("Could not create transaction, intent is {}", intent_name);
- }
- } else {
- peer_->setStream(nullptr);
- logger_->log_debug("Could not create transaction, received {}", client->getResponseCode());
- }
- return nullptr;
-}
-
-int HttpSiteToSiteClient::readResponse(const std::shared_ptr<sitetosite::Transaction> &transaction, sitetosite::RespondCode &code, std::string &message) {
- if (current_code == sitetosite::FINISH_TRANSACTION) {
- if (transaction->getDirection() == sitetosite::SEND) {
- auto stream = dynamic_cast<http::HttpStream*>(peer_->getStream());
- if (!stream)
- throw std::runtime_error("Invalid HTTPStream");
- stream->close();
- auto client = stream->getClient();
- if (client->getResponseCode() == 202) {
- code = sitetosite::CONFIRM_TRANSACTION;
- message = std::string(client->getResponseBody().data(), client->getResponseBody().size());
- } else {
- logger_->log_debug("Received response code {}", client->getResponseCode());
- code = sitetosite::UNRECOGNIZED_RESPONSE_CODE;
- }
- return 1;
- } else {
- return 1;
- }
- } else if (transaction->getDirection() == sitetosite::RECEIVE) {
- if (transaction->getState() == sitetosite::TRANSACTION_STARTED || transaction->getState() == sitetosite::DATA_EXCHANGED) {
- if (current_code == sitetosite::CONFIRM_TRANSACTION && transaction->getState() == sitetosite::DATA_EXCHANGED) {
- auto stream = dynamic_cast<http::HttpStream*>(peer_->getStream());
- if (!stream->isFinished()) {
- logger_->log_debug("confirm read for {}, but not finished ", transaction->getUUIDStr());
- if (stream->waitForDataAvailable()) {
- code = sitetosite::CONTINUE_TRANSACTION;
- return 1;
- }
- }
-
- code = sitetosite::CONFIRM_TRANSACTION;
- } else {
- auto stream = dynamic_cast<http::HttpStream*>(peer_->getStream());
- if (stream->isFinished()) {
- logger_->log_debug("Finished {} ", transaction->getUUIDStr());
- code = sitetosite::FINISH_TRANSACTION;
- current_code = sitetosite::FINISH_TRANSACTION;
- } else {
- if (stream->waitForDataAvailable()) {
- logger_->log_debug("data is available, so continuing transaction {} ", transaction->getUUIDStr());
- code = sitetosite::CONTINUE_TRANSACTION;
- } else {
- logger_->log_debug("No data available for transaction {} ", transaction->getUUIDStr());
- code = sitetosite::FINISH_TRANSACTION;
- current_code = sitetosite::FINISH_TRANSACTION;
- }
- }
- }
- } else if (transaction->getState() == sitetosite::TRANSACTION_CONFIRMED) {
- closeTransaction(transaction->getUUID());
- code = sitetosite::CONFIRM_TRANSACTION;
- }
-
- return 1;
- } else if (transaction->getState() == sitetosite::TRANSACTION_CONFIRMED) {
- closeTransaction(transaction->getUUID());
- code = sitetosite::TRANSACTION_FINISHED;
-
- return 1;
- }
- return SiteToSiteClient::readResponse(transaction, code, message);
-}
-// write respond
-int HttpSiteToSiteClient::writeResponse(const std::shared_ptr<sitetosite::Transaction> &transaction, sitetosite::RespondCode code, const std::string& message) {
- current_code = code;
- if (code == sitetosite::CONFIRM_TRANSACTION || code == sitetosite::FINISH_TRANSACTION) {
- return 1;
-
- } else if (code == sitetosite::CONTINUE_TRANSACTION) {
- logger_->log_debug("Continuing HTTP transaction");
- return 1;
- }
- return SiteToSiteClient::writeResponse(transaction, code, message);
-}
-
-bool HttpSiteToSiteClient::getPeerList(std::vector<sitetosite::PeerStatus> &peers) {
- std::stringstream uri;
- uri << getBaseURI() << "site-to-site/peers";
-
- auto client = create_http_client(uri.str(), http::HttpRequestMethod::GET);
-
- client->setRequestHeader(PROTOCOL_VERSION_HEADER, "1");
-
- client->submit();
-
- if (client->getResponseCode() == 200) {
- if (sitetosite::PeersEntity::parse(logger_, std::string(client->getResponseBody().data(), client->getResponseBody().size()), port_id_, peers)) {
- return true;
- }
- }
- return false;
-}
-
-std::shared_ptr<minifi::http::HTTPClient> HttpSiteToSiteClient::openConnectionForSending(const std::shared_ptr<HttpTransaction> &transaction) {
- std::stringstream uri;
- uri << transaction->getTransactionUrl() << "/flow-files";
- std::shared_ptr<minifi::http::HTTPClient> client = create_http_client(uri.str(), http::HttpRequestMethod::POST);
- client->setContentType("application/octet-stream");
- client->setRequestHeader("Accept", "text/plain");
- client->setRequestHeader("Transfer-Encoding", "chunked");
- return client;
-}
-
-std::shared_ptr<minifi::http::HTTPClient> HttpSiteToSiteClient::openConnectionForReceive(const std::shared_ptr<HttpTransaction> &transaction) {
- std::stringstream uri;
- uri << transaction->getTransactionUrl() << "/flow-files";
- std::shared_ptr<minifi::http::HTTPClient> client = create_http_client(uri.str(), http::HttpRequestMethod::GET);
- return client;
-}
-
-//! Transfer string for the process session
-bool HttpSiteToSiteClient::transmitPayload(core::ProcessContext&, core::ProcessSession&, const std::string& /*payload*/,
- std::map<std::string, std::string> /*attributes*/) {
- return false;
-}
-
-void HttpSiteToSiteClient::tearDown() {
- if (peer_state_ >= sitetosite::ESTABLISHED) {
- logger_->log_debug("Site2Site Protocol tearDown");
- }
- known_transactions_.clear();
- peer_->Close();
- peer_state_ = sitetosite::IDLE;
-}
-
-void HttpSiteToSiteClient::closeTransaction(const utils::Identifier &transactionID) {
- std::shared_ptr<sitetosite::Transaction> transaction;
-
- auto it = this->known_transactions_.find(transactionID);
-
- if (it == known_transactions_.end()) {
- return;
- }
-
- transaction = it->second;
- if (transaction->closed_) {
- return;
- }
-
- std::string append_str;
- logger_->log_trace("Site to Site closing transaction {}", transaction->getUUIDStr());
-
-
- bool data_received = transaction->getDirection() == sitetosite::RECEIVE && (current_code == sitetosite::CONFIRM_TRANSACTION || current_code == sitetosite::TRANSACTION_FINISHED);
-
- int code = sitetosite::UNRECOGNIZED_RESPONSE_CODE;
- // In case transaction was used to actually transmit data (conditions are a bit different for send and receive to detect this),
- // it has to be confirmed before closing.
- // In case no data was transmitted, there is nothing to confirm, so the transaction can be cancelled without confirming it.
- // Confirm means matching CRC checksum of data at both sides.
- if (transaction->getState() == sitetosite::TRANSACTION_CONFIRMED || data_received) {
- code = sitetosite::CONFIRM_TRANSACTION;
- } else if (transaction->current_transfers_ == 0 && !transaction->isDataAvailable()) {
- code = sitetosite::CANCEL_TRANSACTION;
- } else {
- std::string directon = transaction->getDirection() == sitetosite::RECEIVE ? "Receive" : "Send";
- logger_->log_error("Transaction {} to be closed is in unexpected state. Direction: {}, tranfers: {}, bytes: {}, state: {}",
- transactionID.to_string(), directon, transaction->total_transfers_, transaction->_bytes, magic_enum::enum_underlying(transaction->getState()));
- }
-
- std::stringstream uri;
- std::string dir_str = transaction->getDirection() == sitetosite::SEND ? "input-ports" : "output-ports";
-
- uri << getBaseURI() << "data-transfer/" << dir_str << "/" << getPortId().to_string() << "/transactions/" << transactionID.to_string() << "?responseCode=" << code;
-
- if (code == sitetosite::CONFIRM_TRANSACTION && data_received) {
- uri << "&checksum=" << transaction->getCRC();
- }
-
- auto client = create_http_client(uri.str(), http::HttpRequestMethod::DELETE);
-
- client->setRequestHeader(PROTOCOL_VERSION_HEADER, "1");
-
- client->setConnectionTimeout(std::chrono::milliseconds(5000));
-
- client->setRequestHeader("Accept", "application/json");
-
- client->submit();
-
- logger_->log_debug("Received {} response code from delete", client->getResponseCode());
-
- if (client->getResponseCode() == 400) {
- std::string error(client->getResponseBody().data(), client->getResponseBody().size());
-
- logger_->log_warn("400 received: {}", error);
- std::stringstream message;
- message << "Received " << client->getResponseCode() << " from " << uri.str();
- throw Exception(SITE2SITE_EXCEPTION, message.str());
- }
-
- transaction->closed_ = true;
-
- transaction->current_transfers_--;
-}
-
-void HttpSiteToSiteClient::deleteTransaction(const utils::Identifier& transactionID) {
- closeTransaction(transactionID);
-
- SiteToSiteClient::deleteTransaction(transactionID);
-}
-
-REGISTER_RESOURCE_AS(HttpSiteToSiteClient, InternalResource, ("HttpSiteToSiteClient", "HttpProtocol"));
-
-} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/sitetosite/HttpSiteToSiteClient.cpp b/libminifi/src/sitetosite/HttpSiteToSiteClient.cpp
new file mode 100644
index 000000000..8cd99377f
--- /dev/null
+++ b/libminifi/src/sitetosite/HttpSiteToSiteClient.cpp
@@ -0,0 +1,394 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "sitetosite/HttpSiteToSiteClient.h"
+
+#include <chrono>
+#include <map>
+#include <string>
+#include <memory>
+#include <thread>
+#include <iostream>
+#include <vector>
+#include <optional>
+
+#include "io/CRCStream.h"
+#include "sitetosite/Peer.h"
+#include "io/validation.h"
+#include "core/Resource.h"
+#include "utils/StringUtils.h"
+#include "Exception.h"
+
+#include "rapidjson/document.h"
+#include "rapidjson/error/en.h"
+
+#undef DELETE // macro on windows
+
+namespace org::apache::nifi::minifi::sitetosite {
+
+namespace {
+std::optional<utils::Identifier> parseTransactionId(const std::string &uri) {
+ return utils::Identifier::parse(utils::string::partAfterLastOccurrenceOf(uri, '/'));
+}
+
+std::optional<std::vector<PeerStatus>> parsePeerStatuses(const std::shared_ptr<core::logging::Logger> &logger, const std::string &entity, const utils::Identifier &id) {
+ try {
+ rapidjson::Document root;
+ rapidjson::ParseResult ok = root.Parse(entity.c_str());
+ if (!ok) {
+ throw Exception(ExceptionType::GENERAL_EXCEPTION, fmt::format("Failed to parse peer status json response: {} at {}", rapidjson::GetParseError_En(ok.Code()), ok.Offset()));
+ }
+
+ std::vector<PeerStatus> peer_statuses;
+ if (!root.HasMember("peers") || !root["peers"].IsArray() || root["peers"].Size() <= 0) {
+ logger->log_warn("Peers is either not a member or is empty. String to analyze: {}", entity);
+ return peer_statuses;
+ }
+
+ for (const auto &peer : root["peers"].GetArray()) {
+ std::string hostname;
+ int port = 0;
+ int flow_file_count = 0;
+
+ if (peer.HasMember("hostname") && peer["hostname"].IsString() &&
+ peer.HasMember("port") && peer["port"].IsNumber()) {
+ hostname = peer["hostname"].GetString();
+ port = peer["port"].GetInt();
+ }
+
+ if (peer.HasMember("flowFileCount")) {
+ if (peer["flowFileCount"].IsNumber()) {
+ flow_file_count = gsl::narrow<int>(peer["flowFileCount"].GetInt64());
+ } else {
+ logger->log_debug("Could not parse flowFileCount, so we're going to continue without it");
+ }
+ }
+
+ // host name and port are required.
+ if (!IsNullOrEmpty(hostname) && port > 0) {
+ PeerStatus status(id, hostname, port, flow_file_count, true);
+ peer_statuses.push_back(std::move(status));
+ } else {
+ logger->log_debug("hostname empty or port is zero. hostname: {}, port: {}", hostname, port);
+ }
+ }
+ return peer_statuses;
+ } catch (const Exception &exception) {
+ logger->log_debug("Caught Exception {}", exception.what());
+ return std::nullopt;
+ }
+}
+} // namespace
+
+std::shared_ptr<Transaction> HttpSiteToSiteClient::createTransaction(TransferDirection direction) {
+ std::string dir_str = direction == TransferDirection::SEND ? "input-ports" : "output-ports";
+ std::stringstream uri;
+ uri << getBaseURI() << "data-transfer/" << dir_str << "/" << getPortId().to_string() << "/transactions";
+ auto client = createHttpClient(uri.str(), http::HttpRequestMethod::POST);
+ setSiteToSiteHeaders(*client);
+ client->setConnectionTimeout(std::chrono::milliseconds(5000));
+ client->setContentType("application/json");
+ client->setRequestHeader("Accept", "application/json");
+ client->setRequestHeader("Transfer-Encoding", "chunked");
+ client->setPostFields("");
+ client->submit();
+
+ if (auto http_stream = dynamic_cast<http::HttpStream*>(peer_->getStream())) {
+ logger_->log_debug("Closing {}", http_stream->getClientRef()->getURL());
+ }
+
+ if (client->getResponseCode() != 201) {
+ peer_->setStream(nullptr);
+ logger_->log_debug("Could not create transaction, received {}", client->getResponseCode());
+ return nullptr;
+ }
+ // parse the headers
+ auto intent_name = client->getHeaderValue("x-location-uri-intent");
+ if (!utils::string::equalsIgnoreCase(intent_name, "transaction-url")) {
+ logger_->log_debug("Could not create transaction, intent is {}", intent_name);
+ return nullptr;
+ }
+
+ auto url = client->getHeaderValue("Location");
+ if (IsNullOrEmpty(url)) {
+ logger_->log_debug("Location is empty");
+ return nullptr;
+ }
+
+ org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> crcstream(gsl::make_not_null(peer_.get()));
+ auto transaction = std::make_shared<HttpTransaction>(direction, std::move(crcstream));
+ transaction->initialize(this, url);
+ auto transaction_id = parseTransactionId(url);
+ if (!transaction_id) {
+ logger_->log_debug("Transaction ID is empty");
+ return nullptr;
+ }
+ transaction->setTransactionId(transaction_id.value());
+ std::shared_ptr<minifi::http::HTTPClient> transaction_client;
+ if (transaction->getDirection() == TransferDirection::SEND) {
+ transaction_client = openConnectionForSending(transaction);
+ } else {
+ transaction_client = openConnectionForReceive(transaction);
+ transaction->setDataAvailable(true);
+ // 201 tells us that data is available. 200 would mean that nothing is available.
+ }
+ gsl_Assert(transaction_client);
+
+ setSiteToSiteHeaders(*transaction_client);
+ peer_->setStream(std::make_unique<http::HttpStream>(transaction_client));
+ logger_->log_debug("Created transaction id -{}-", transaction->getUUID().to_string());
+ known_transactions_[transaction->getUUID()] = transaction;
+ return transaction;
+}
+
+std::optional<SiteToSiteResponse> HttpSiteToSiteClient::readResponseForReceiveTransfer(const std::shared_ptr<Transaction>& transaction) {
+ if (transaction->getState() == TransactionState::TRANSACTION_STARTED || transaction->getState() == TransactionState::DATA_EXCHANGED) {
+ if (current_code_ == ResponseCode::CONFIRM_TRANSACTION && transaction->getState() == TransactionState::DATA_EXCHANGED) {
+ auto stream = dynamic_cast<http::HttpStream*>(peer_->getStream());
+ if (!stream->isFinished()) {
+ logger_->log_debug("confirm read for {}, but not finished ", transaction->getUUIDStr());
+ if (stream->waitForDataAvailable()) {
+ return SiteToSiteResponse{.code = ResponseCode::CONTINUE_TRANSACTION, .message = ""};
+ }
+ }
+
+ return SiteToSiteResponse{.code = ResponseCode::CONFIRM_TRANSACTION, .message = ""};
+ }
+
+ auto stream = dynamic_cast<http::HttpStream*>(peer_->getStream());
+ if (stream->isFinished()) {
+ logger_->log_debug("Finished {} ", transaction->getUUIDStr());
+ current_code_ = ResponseCode::FINISH_TRANSACTION;
+ return SiteToSiteResponse{.code = ResponseCode::FINISH_TRANSACTION, .message = ""};
+ }
+
+ if (stream->waitForDataAvailable()) {
+ logger_->log_debug("data is available, so continuing transaction {} ", transaction->getUUIDStr());
+ return SiteToSiteResponse{.code = ResponseCode::CONTINUE_TRANSACTION, .message = ""};
+ }
+
+ logger_->log_debug("No data available for transaction {} ", transaction->getUUIDStr());
+ current_code_ = ResponseCode::FINISH_TRANSACTION;
+ return SiteToSiteResponse{.code = ResponseCode::FINISH_TRANSACTION, .message = ""};
+ }
+
+ if (transaction->getState() == TransactionState::TRANSACTION_CONFIRMED) {
+ closeTransaction(transaction->getUUID());
+ return SiteToSiteResponse{.code = ResponseCode::CONFIRM_TRANSACTION, .message = ""};
+ }
+
+ return SiteToSiteResponse{.code = ResponseCode::UNRECOGNIZED_RESPONSE_CODE, .message = ""};
+}
+
+std::optional<SiteToSiteResponse> HttpSiteToSiteClient::readResponseForSendTransfer(const std::shared_ptr<Transaction>& transaction) {
+ if (current_code_ == ResponseCode::FINISH_TRANSACTION) {
+ auto stream = dynamic_cast<http::HttpStream*>(peer_->getStream());
+ if (!stream) {
+ throw std::runtime_error("Invalid HTTPStream");
+ }
+
+ stream->close();
+ auto client = stream->getClient();
+ if (client->getResponseCode() == 202) {
+ return SiteToSiteResponse{.code = ResponseCode::CONFIRM_TRANSACTION, .message = std::string(client->getResponseBody().data(), client->getResponseBody().size())};
+ }
+
+ logger_->log_debug("Received response code {}", client->getResponseCode());
+ return SiteToSiteResponse{.code = ResponseCode::UNRECOGNIZED_RESPONSE_CODE, .message = ""};
+ }
+
+ if (transaction->getState() == TransactionState::TRANSACTION_CONFIRMED) {
+ closeTransaction(transaction->getUUID());
+ return SiteToSiteResponse{.code = ResponseCode::TRANSACTION_FINISHED, .message = ""};
+ }
+
+ return SiteToSiteClient::readResponse(transaction);
+}
+
+std::optional<SiteToSiteResponse> HttpSiteToSiteClient::readResponse(const std::shared_ptr<Transaction>& transaction) {
+ if (transaction->getDirection() == TransferDirection::RECEIVE) {
+ return readResponseForReceiveTransfer(transaction);
+ }
+
+ return readResponseForSendTransfer(transaction);
+}
+
+bool HttpSiteToSiteClient::writeResponse(const std::shared_ptr<Transaction> &transaction, const SiteToSiteResponse& response) {
+ current_code_ = response.code;
+ if (response.code == ResponseCode::CONFIRM_TRANSACTION || response.code == ResponseCode::FINISH_TRANSACTION) {
+ return true;
+ } else if (response.code == ResponseCode::CONTINUE_TRANSACTION) {
+ logger_->log_debug("Continuing HTTP transaction");
+ return true;
+ }
+ return SiteToSiteClient::writeResponse(transaction, response);
+}
+
+std::optional<std::vector<PeerStatus>> HttpSiteToSiteClient::getPeerList() {
+ std::stringstream uri;
+ uri << getBaseURI() << "site-to-site/peers";
+
+ auto client = createHttpClient(uri.str(), http::HttpRequestMethod::GET);
+
+ setSiteToSiteHeaders(*client);
+
+ client->submit();
+
+ if (client->getResponseCode() == 200) {
+ return parsePeerStatuses(logger_, std::string(client->getResponseBody().data(), client->getResponseBody().size()), port_id_);
+ }
+ return std::nullopt;
+}
+
+std::shared_ptr<minifi::http::HTTPClient> HttpSiteToSiteClient::openConnectionForSending(const std::shared_ptr<HttpTransaction> &transaction) {
+ std::stringstream uri;
+ uri << transaction->getTransactionUrl() << "/flow-files";
+ std::shared_ptr<minifi::http::HTTPClient> client = createHttpClient(uri.str(), http::HttpRequestMethod::POST);
+ client->setContentType("application/octet-stream");
+ client->setRequestHeader("Accept", "text/plain");
+ client->setRequestHeader("Transfer-Encoding", "chunked");
+ return client;
+}
+
+std::shared_ptr<minifi::http::HTTPClient> HttpSiteToSiteClient::openConnectionForReceive(const std::shared_ptr<HttpTransaction> &transaction) {
+ std::stringstream uri;
+ uri << transaction->getTransactionUrl() << "/flow-files";
+ return createHttpClient(uri.str(), http::HttpRequestMethod::GET);
+}
+
+std::string HttpSiteToSiteClient::getBaseURI() {
+ std::string uri = ssl_context_service_ != nullptr ? "https://" : "http://";
+ uri.append(peer_->getHostName());
+ uri.append(":");
+ uri.append(std::to_string(peer_->getPort()));
+ uri.append("/nifi-api/");
+ return uri;
+}
+
+std::unique_ptr<minifi::http::HTTPClient> HttpSiteToSiteClient::createHttpClient(const std::string &uri, http::HttpRequestMethod method) {
+ auto http_client_ = std::make_unique<minifi::http::HTTPClient>(uri, ssl_context_service_);
+ http_client_->initialize(method, uri, ssl_context_service_);
+ if (!peer_->getInterface().empty()) {
+ logger_->log_info("HTTP Site2Site bind local network interface {}", peer_->getInterface());
+ http_client_->setInterface(peer_->getInterface());
+ }
+ if (!peer_->getHTTPProxy().host.empty()) {
+ logger_->log_info("HTTP Site2Site setup http proxy host {}", peer_->getHTTPProxy().host);
+ http_client_->setHTTPProxy(peer_->getHTTPProxy());
+ }
+ http_client_->setReadTimeout(idle_timeout_);
+ return http_client_;
+}
+
+bool HttpSiteToSiteClient::transmitPayload(core::ProcessContext&, const std::string& /*payload*/, const std::map<std::string, std::string>& /*attributes*/) {
+ return false;
+}
+
+void HttpSiteToSiteClient::tearDown() {
+ if (magic_enum::enum_underlying(peer_state_) >= magic_enum::enum_underlying(PeerState::ESTABLISHED)) {
+ logger_->log_debug("Site2Site Protocol tearDown");
+ }
+ known_transactions_.clear();
+ peer_->close();
+ peer_state_ = PeerState::IDLE;
+}
+
+void HttpSiteToSiteClient::closeTransaction(const utils::Identifier &transaction_id) {
+ auto it = known_transactions_.find(transaction_id);
+ if (it == known_transactions_.end()) {
+ return;
+ }
+
+ auto transaction = it->second;
+ if (transaction->isClosed()) {
+ return;
+ }
+
+ logger_->log_trace("Site to Site closing transaction {}", transaction->getUUIDStr());
+
+ bool data_received = transaction->getDirection() == TransferDirection::RECEIVE && (current_code_ == ResponseCode::CONFIRM_TRANSACTION || current_code_ == ResponseCode::TRANSACTION_FINISHED);
+
+ auto code = ResponseCode::UNRECOGNIZED_RESPONSE_CODE;
+ // In case transaction was used to actually transmit data (conditions are a bit different for send and receive to detect this),
+ // it has to be confirmed before closing.
+ // In case no data was transmitted, there is nothing to confirm, so the transaction can be cancelled without confirming it.
+ // Confirm means matching CRC checksum of data at both sides.
+ if (transaction->getState() == TransactionState::TRANSACTION_CONFIRMED || data_received) {
+ code = ResponseCode::CONFIRM_TRANSACTION;
+ } else if (transaction->getCurrentTransfers() == 0 && !transaction->isDataAvailable()) {
+ code = ResponseCode::CANCEL_TRANSACTION;
+ } else {
+ std::string directon = transaction->getDirection() == TransferDirection::RECEIVE ? "Receive" : "Send";
+ logger_->log_error("Transaction {} to be closed is in unexpected state. Direction: {}, transfers: {}, bytes: {}, state: {}",
+ transaction_id.to_string(), directon, transaction->getTotalTransfers(), transaction->getBytes(), magic_enum::enum_underlying(transaction->getState()));
+ }
+
+ std::stringstream uri;
+ std::string dir_str = transaction->getDirection() == TransferDirection::SEND ? "input-ports" : "output-ports";
+
+ uri << getBaseURI() << "data-transfer/" << dir_str << "/" << getPortId().to_string() << "/transactions/" << transaction_id.to_string() <<
+ "?responseCode=" << std::to_string(magic_enum::enum_underlying(code));
+
+ if (code == ResponseCode::CONFIRM_TRANSACTION && data_received) {
+ uri << "&checksum=" << transaction->getCRC();
+ }
+
+ auto client = createHttpClient(uri.str(), http::HttpRequestMethod::DELETE);
+ setSiteToSiteHeaders(*client);
+ client->setConnectionTimeout(std::chrono::milliseconds(5000));
+ client->setRequestHeader("Accept", "application/json");
+ client->submit();
+
+ logger_->log_debug("Received {} response code from delete", client->getResponseCode());
+
+ if (client->getResponseCode() == 400) {
+ std::string error(client->getResponseBody().data(), client->getResponseBody().size());
+
+ logger_->log_warn("400 received: {}", error);
+ std::stringstream message;
+ message << "Received " << client->getResponseCode() << " from " << uri.str();
+ throw Exception(SITE2SITE_EXCEPTION, message.str());
+ }
+
+ transaction->close();
+ transaction->decrementCurrentTransfers();
+}
+
+void HttpSiteToSiteClient::deleteTransaction(const utils::Identifier& transaction_id) {
+ closeTransaction(transaction_id);
+
+ SiteToSiteClient::deleteTransaction(transaction_id);
+}
+
+void HttpSiteToSiteClient::setSiteToSiteHeaders(minifi::http::HTTPClient& client) {
+ client.setRequestHeader(PROTOCOL_VERSION_HEADER, "1");
+ // TODO(lordgamez): send use_compression_ boolean value when compression support is added
+ client.setRequestHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION, "false");
+ if (timeout_.load() > 0ms) {
+ client.setRequestHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION, std::to_string(timeout_.load().count()));
+ }
+ if (batch_count_ > 0) {
+ client.setRequestHeader(HANDSHAKE_PROPERTY_BATCH_COUNT, std::to_string(batch_count_));
+ }
+ if (batch_size_ > 0) {
+ client.setRequestHeader(HANDSHAKE_PROPERTY_BATCH_SIZE, std::to_string(batch_size_));
+ }
+ if (batch_duration_.load() > std::chrono::milliseconds(0)) {
+ client.setRequestHeader(HANDSHAKE_PROPERTY_BATCH_DURATION, std::to_string(batch_duration_.load().count()));
+ }
+}
+
+} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/sitetosite/Peer.cpp b/libminifi/src/sitetosite/Peer.cpp
index f325df2f8..f357d0f7b 100644
--- a/libminifi/src/sitetosite/Peer.cpp
+++ b/libminifi/src/sitetosite/Peer.cpp
@@ -17,46 +17,40 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-#include <cstdio>
-#include <chrono>
-#include <thread>
-#include <random>
-#include <memory>
-#include <iostream>
-
#include "sitetosite/Peer.h"
+
#include "io/validation.h"
-#include "FlowController.h"
#include "utils/net/AsioSocketUtils.h"
namespace org::apache::nifi::minifi::sitetosite {
-bool SiteToSitePeer::Open() {
- if (IsNullOrEmpty(host_))
+bool SiteToSitePeer::open() {
+ if (IsNullOrEmpty(host_)) {
return false;
+ }
/**
* We may override the interface provided to us within the socket in this step; however, this is a
* known configuration path, and thus we will allow the RPG configuration to override anything provided to us
* previously by the socket preference.
*/
- if (!this->local_network_interface_.getInterface().empty()) {
- auto* socket = dynamic_cast<utils::net::AsioSocketConnection*>(stream_.get());
- if (nullptr != socket) {
+ if (!local_network_interface_.getInterface().empty()) {
+ if (auto socket = dynamic_cast<utils::net::AsioSocketConnection*>(stream_.get())) {
socket->setInterface(local_network_interface_.getInterface());
}
}
- if (stream_->initialize() < 0)
+ if (stream_->initialize() < 0) {
return false;
+ }
- const auto data_size = sizeof MAGIC_BYTES;
- return stream_->write(reinterpret_cast<const uint8_t *>(MAGIC_BYTES), data_size) == data_size;
+ return stream_->write(reinterpret_cast<const uint8_t *>(MAGIC_BYTES.data()), MAGIC_BYTES.size()) == MAGIC_BYTES.size();
}
-void SiteToSitePeer::Close() {
- if (stream_ != nullptr)
+void SiteToSitePeer::close() {
+ if (stream_) {
stream_->close();
+ }
}
} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/sitetosite/RawSiteToSiteClient.cpp b/libminifi/src/sitetosite/RawSiteToSiteClient.cpp
new file mode 100644
index 000000000..41ed72cdc
--- /dev/null
+++ b/libminifi/src/sitetosite/RawSiteToSiteClient.cpp
@@ -0,0 +1,430 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <chrono>
+#include <utility>
+#include <map>
+#include <string>
+#include <memory>
+#include <vector>
+
+#include "sitetosite/RawSiteToSiteClient.h"
+#include "io/CRCStream.h"
+#include "sitetosite/Peer.h"
+#include "utils/gsl.h"
+#include "utils/Enum.h"
+
+using namespace std::literals::chrono_literals;
+
+namespace org::apache::nifi::minifi::sitetosite {
+
+namespace {
+bool negotiateVersion(SiteToSitePeer& peer, const std::string& resource_name, const std::string& negotiation_type, uint32_t& current_version, uint32_t& current_version_index,
+ const std::vector<uint32_t>& supported_versions, const std::shared_ptr<core::logging::Logger>& logger) {
+ if (const auto ret = peer.write(resource_name); ret == 0 || io::isError(ret)) {
+ logger->log_debug("result of writing {} resource name is {}", negotiation_type, ret);
+ return false;
+ }
+
+ if (const auto ret = peer.write(current_version); ret == 0 || io::isError(ret)) {
+ logger->log_debug("result of {} version is {}", negotiation_type, ret);
+ return false;
+ }
+
+ uint8_t status_code_byte = 0;
+ if (const auto ret = peer.read(status_code_byte); ret == 0 || io::isError(ret)) {
+ logger->log_debug("result of writing {} version status code {}", negotiation_type, ret);
+ return false;
+ }
+
+ auto status_code = magic_enum::enum_cast<ResourceNegotiationStatusCode>(status_code_byte);
+ if (!status_code) {
+ logger->log_error("Negotiate {} response unknown code {}", negotiation_type, status_code_byte);
+ return false;
+ }
+
+ switch (*status_code) {
+ case ResourceNegotiationStatusCode::RESOURCE_OK: {
+ logger->log_debug("Site2Site {} Negotiate version OK", negotiation_type);
+ return true;
+ }
+ case ResourceNegotiationStatusCode::DIFFERENT_RESOURCE_VERSION: {
+ uint32_t server_version = 0;
+ if (const auto ret = peer.read(server_version); ret == 0 || io::isError(ret)) {
+ return false;
+ }
+
+ logger->log_info("Site2Site Server Response asked for a different protocol version ", server_version);
+
+ for (uint32_t i = (current_version_index + 1); i < supported_versions.size(); i++) {
+ if (server_version >= supported_versions.at(i)) {
+ current_version = supported_versions.at(i);
+ current_version_index = i;
+ return negotiateVersion(peer, resource_name, negotiation_type, current_version, current_version_index, supported_versions, logger);
+ }
+ }
+ logger->log_error("Site2Site Negotiate {} failed to find a common version with server", negotiation_type);
+ return false;
+ }
+ case ResourceNegotiationStatusCode::NEGOTIATED_ABORT: {
+ logger->log_error("Site2Site Negotiate {} response ABORT", negotiation_type);
+ return false;
+ }
+ default: {
+ logger->log_error("Negotiate {} response unhandled code {}", negotiation_type, magic_enum::enum_name(*status_code));
+ return false;
+ }
+ }
+}
+} // namespace
+
+bool RawSiteToSiteClient::establish() {
+ if (peer_state_ != PeerState::IDLE) {
+ logger_->log_error("Site2Site peer state is not idle while try to establish");
+ return false;
+ }
+
+ if (auto ret = peer_->open(); !ret) {
+ logger_->log_error("Site2Site peer socket open failed");
+ return false;
+ }
+
+ if (auto ret = initiateResourceNegotiation(); !ret) {
+ logger_->log_error("Site2Site Protocol Version Negotiation failed");
+ return false;
+ }
+
+ logger_->log_debug("Site2Site socket established");
+ peer_state_ = PeerState::ESTABLISHED;
+
+ return true;
+}
+
+bool RawSiteToSiteClient::initiateResourceNegotiation() {
+ if (peer_state_ != PeerState::IDLE) {
+ logger_->log_error("Site2Site peer state is not idle while initiateResourceNegotiation");
+ return false;
+ }
+
+ logger_->log_debug("Negotiate protocol version with destination port {} current version {}", port_id_.to_string(), current_version_);
+ return negotiateVersion(*peer_, std::string{PROTOCOL_RESOURCE_NAME}, "protocol", current_version_, current_version_index_, supported_versions_, logger_);
+}
+
+bool RawSiteToSiteClient::initiateCodecResourceNegotiation() {
+ if (peer_state_ != PeerState::HANDSHAKED) {
+ logger_->log_error("Site2Site peer state is not handshaked while initiateCodecResourceNegotiation");
+ return false;
+ }
+
+ logger_->log_trace("Negotiate Codec version with destination port {} current version {}", port_id_.to_string(), current_codec_version_);
+ return negotiateVersion(*peer_, std::string{CODEC_RESOURCE_NAME}, "codec", current_codec_version_, current_codec_version_index_, supported_codec_versions_, logger_);
+}
+
+bool RawSiteToSiteClient::handShake() {
+ if (peer_state_ != PeerState::ESTABLISHED) {
+ logger_->log_error("Site2Site peer state is not established while handshake");
+ return false;
+ }
+ logger_->log_debug("Site2Site Protocol Perform hand shake with destination port {}", port_id_.to_string());
+ comms_identifier_ = utils::IdGenerator::getIdGenerator()->generate();
+
+ if (const auto ret = peer_->write(comms_identifier_); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Failed to write comms identifier {}", ret);
+ return false;
+ }
+
+ std::map<std::string, std::string> properties;
+ // TODO(lordgamez): send use_compression_ boolean value when compression support is added
+ properties[std::string(magic_enum::enum_name(HandshakeProperty::GZIP))] = "false";
+ properties[std::string(magic_enum::enum_name(HandshakeProperty::PORT_IDENTIFIER))] = port_id_.to_string();
+ properties[std::string(magic_enum::enum_name(HandshakeProperty::REQUEST_EXPIRATION_MILLIS))] = std::to_string(timeout_.load().count());
+ if (current_version_ >= 5) {
+ if (batch_count_ > 0) {
+ properties[std::string(magic_enum::enum_name(HandshakeProperty::BATCH_COUNT))] = std::to_string(batch_count_);
+ }
+ if (batch_size_ > 0) {
+ properties[std::string(magic_enum::enum_name(HandshakeProperty::BATCH_SIZE))] = std::to_string(batch_size_);
+ }
+ if (batch_duration_.load() > 0ms) {
+ properties[std::string(magic_enum::enum_name(HandshakeProperty::BATCH_DURATION))] = std::to_string(batch_duration_.load().count());
+ }
+ }
+
+ if (current_version_ >= 3) {
+ if (const auto ret = peer_->write(peer_->getURL()); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Failed to write peer URL {}", ret);
+ return false;
+ }
+ }
+
+ if (const auto ret = peer_->write(gsl::narrow<uint32_t>(properties.size())); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Failed to write properties size {}", ret);
+ return false;
+ }
+
+ for (const auto& property : properties) {
+ if (const auto ret = peer_->write(property.first); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Failed to write property key {}", ret);
+ return false;
+ }
+
+ if (const auto ret = peer_->write(property.second); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Failed to write property value {}", ret);
+ return false;
+ }
+ logger_->log_debug("Site2Site Protocol Send handshake properties {} {}", property.first, property.second);
+ }
+
+ const auto response = readResponse(nullptr);
+ if (!response) {
+ return false;
+ }
+
+ auto logPortStateError = [this](const std::string& error) {
+ logger_->log_error("Site2Site HandShake Failed because destination port, {}, is {}", port_id_.to_string(), error);
+ };
+
+ switch (response->code) {
+ case ResponseCode::PROPERTIES_OK:
+ logger_->log_debug("Site2Site HandShake Completed");
+ peer_state_ = PeerState::HANDSHAKED;
+ return true;
+ case ResponseCode::PORT_NOT_IN_VALID_STATE:
+ logPortStateError("in invalid state");
+ return false;
+ case ResponseCode::UNKNOWN_PORT:
+ logPortStateError("an unknown port");
+ return false;
+ case ResponseCode::PORTS_DESTINATION_FULL:
+ logPortStateError("full");
+ return false;
+ case ResponseCode::UNAUTHORIZED:
+ logger_->log_error("Site2Site HandShake on port {} failed: UNAUTHORIZED", port_id_.to_string());
+ return false;
+ default:
+ logger_->log_error("Site2Site HandShake on port {} failed: unknown response code {}", port_id_.to_string(), magic_enum::enum_underlying(response->code));
+ return false;
+ }
+}
+
+void RawSiteToSiteClient::tearDown() {
+ if (magic_enum::enum_underlying(peer_state_) >= magic_enum::enum_underlying(PeerState::ESTABLISHED)) {
+ logger_->log_trace("Site2Site Protocol tearDown");
+ writeRequestType(RequestType::SHUTDOWN);
+ }
+
+ known_transactions_.clear();
+ peer_->close();
+ peer_state_ = PeerState::IDLE;
+}
+
+std::optional<std::vector<PeerStatus>> RawSiteToSiteClient::getPeerList() {
+ if (!establish() || !handShake()) {
+ tearDown();
+ return std::nullopt;
+ }
+
+ if (writeRequestType(RequestType::REQUEST_PEER_LIST) <= 0) {
+ tearDown();
+ return std::nullopt;
+ }
+
+ uint32_t number_of_peers = 0;
+ std::vector<PeerStatus> peers;
+ if (const auto ret = peer_->read(number_of_peers); ret == 0 || io::isError(ret)) {
+ tearDown();
+ return std::nullopt;
+ }
+
+ for (uint32_t i = 0; i < number_of_peers; i++) {
+ std::string host;
+ if (const auto ret = peer_->read(host); ret == 0 || io::isError(ret)) {
+ tearDown();
+ return std::nullopt;
+ }
+
+ uint32_t port = 0;
+ if (const auto ret = peer_->read(port); ret == 0 || io::isError(ret)) {
+ tearDown();
+ return std::nullopt;
+ }
+
+ uint8_t secure = 0;
+ if (const auto ret = peer_->read(secure); ret == 0 || io::isError(ret)) {
+ tearDown();
+ return std::nullopt;
+ }
+
+ uint32_t count = 0;
+ if (const auto ret = peer_->read(count); ret == 0 || io::isError(ret)) {
+ tearDown();
+ return std::nullopt;
+ }
+
+ peers.push_back(PeerStatus(port_id_, host, gsl::narrow<uint16_t>(port), count, true));
+ logger_->log_trace("Site2Site Peer host {} port {} Secure {}", host, port, std::to_string(secure));
+ }
+
+ tearDown();
+ return peers;
+}
+
+int64_t RawSiteToSiteClient::writeRequestType(RequestType type) {
+ const auto write_result = peer_->write(std::string{magic_enum::enum_name(type)});
+ return io::isError(write_result) ? -1 : gsl::narrow<int64_t>(write_result);
+}
+
+bool RawSiteToSiteClient::negotiateCodec() {
+ if (peer_state_ != PeerState::HANDSHAKED) {
+ logger_->log_error("Site2Site peer state is not handshaked while negotiate codec");
+ return false;
+ }
+
+ logger_->log_trace("Site2Site Protocol Negotiate Codec with destination port {}", port_id_.to_string());
+
+ if (writeRequestType(RequestType::NEGOTIATE_FLOWFILE_CODEC) <= 0) {
+ return false;
+ }
+
+ if (!initiateCodecResourceNegotiation()) {
+ logger_->log_error("Site2Site Codec Version Negotiation failed");
+ return false;
+ }
+
+ logger_->log_trace("Site2Site Codec Completed and move to READY state for data transfer");
+ peer_state_ = PeerState::READY;
+
+ return true;
+}
+
+bool RawSiteToSiteClient::bootstrap() {
+ if (peer_state_ == PeerState::READY) {
+ return true;
+ }
+
+ tearDown();
+
+ if (!establish() || !handShake() || !negotiateCodec()) {
+ tearDown();
+ return false;
+ }
+
+ logger_->log_debug("Site to Site ready for data transaction");
+ return true;
+}
+
+std::shared_ptr<Transaction> RawSiteToSiteClient::createTransaction(TransferDirection direction) {
+ if (peer_state_ != PeerState::READY) {
+ bootstrap();
+ }
+
+ std::shared_ptr<Transaction> transaction = nullptr;
+ if (peer_state_ != PeerState::READY) {
+ return transaction;
+ }
+
+ if (direction == TransferDirection::RECEIVE) {
+ if (writeRequestType(RequestType::RECEIVE_FLOWFILES) <= 0) {
+ return transaction;
+ }
+
+ auto response = readResponse(nullptr);
+ if (!response) {
+ return transaction;
+ }
+
+ org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> crcstream(gsl::make_not_null(peer_.get()));
+ switch (response->code) {
+ case ResponseCode::MORE_DATA:
+ logger_->log_trace("Site2Site peer indicates that data is available");
+ transaction = std::make_shared<Transaction>(direction, std::move(crcstream));
+ known_transactions_[transaction->getUUID()] = transaction;
+ transaction->setDataAvailable(true);
+ logger_->log_trace("Site2Site create transaction {}", transaction->getUUIDStr());
+ return transaction;
+ case ResponseCode::NO_MORE_DATA:
+ logger_->log_trace("Site2Site peer indicates that no data is available");
+ transaction = std::make_shared<Transaction>(direction, std::move(crcstream));
+ known_transactions_[transaction->getUUID()] = transaction;
+ transaction->setDataAvailable(false);
+ logger_->log_trace("Site2Site create transaction {}", transaction->getUUIDStr());
+ return transaction;
+ default:
+ logger_->log_warn("Site2Site got unexpected response {} when asking for data", magic_enum::enum_underlying(response->code));
+ return nullptr;
+ }
+ } else {
+ if (writeRequestType(RequestType::SEND_FLOWFILES) <= 0) {
+ return nullptr;
+ }
+
+ org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> crcstream(gsl::make_not_null(peer_.get()));
+ transaction = std::make_shared<Transaction>(direction, std::move(crcstream));
+ known_transactions_[transaction->getUUID()] = transaction;
+ logger_->log_trace("Site2Site create transaction {}", transaction->getUUIDStr());
+ return transaction;
+ }
+}
+
+bool RawSiteToSiteClient::transmitPayload(core::ProcessContext& context, const std::string &payload, const std::map<std::string, std::string>& attributes) {
+ if (payload.empty()) {
+ return false;
+ }
+
+ if (peer_state_ != PeerState::READY && !bootstrap()) {
+ return false;
+ }
+
+ if (peer_state_ != PeerState::READY) {
+ context.yield();
+ tearDown();
+ throw Exception(SITE2SITE_EXCEPTION, "Can not establish handshake with peer");
+ }
+
+ auto transaction = createTransaction(TransferDirection::SEND);
+ if (transaction == nullptr) {
+ context.yield();
+ tearDown();
+ throw Exception(SITE2SITE_EXCEPTION, "Can not create transaction");
+ }
+
+ utils::Identifier transaction_id = transaction->getUUID();
+ try {
+ DataPacket packet(transaction, attributes, payload);
+ if (!sendPacket(packet)) {
+ throw Exception(SITE2SITE_EXCEPTION, "Send Failed in transaction " + transaction_id.to_string());
+ }
+ logger_->log_info("Site2Site transaction {} sent bytes length", transaction_id.to_string(), payload.length());
+
+ if (!confirm(transaction_id)) {
+ throw Exception(SITE2SITE_EXCEPTION, "Confirm Failed in transaction " + transaction_id.to_string());
+ }
+ if (!complete(context, transaction_id)) {
+ throw Exception(SITE2SITE_EXCEPTION, "Complete Failed in transaction " + transaction_id.to_string());
+ }
+ logger_->log_info("Site2Site transaction {} successfully send flow record {} content bytes {}", transaction_id.to_string(), transaction->getCurrentTransfers(), transaction->getBytes());
+ } catch (const std::exception &exception) {
+ handleTransactionError(transaction, context, exception);
+ throw;
+ }
+
+ deleteTransaction(transaction_id);
+
+ return true;
+}
+
+} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/sitetosite/RawSocketProtocol.cpp b/libminifi/src/sitetosite/RawSocketProtocol.cpp
deleted file mode 100644
index 1a28cfc35..000000000
--- a/libminifi/src/sitetosite/RawSocketProtocol.cpp
+++ /dev/null
@@ -1,623 +0,0 @@
-/**
- * Site2SiteProtocol class implementation
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <chrono>
-#include <utility>
-#include <map>
-#include <string>
-#include <memory>
-#include <vector>
-
-#include "sitetosite/RawSocketProtocol.h"
-#include "io/CRCStream.h"
-#include "sitetosite/Peer.h"
-#include "utils/gsl.h"
-#include "utils/Enum.h"
-
-using namespace std::literals::chrono_literals;
-
-namespace org::apache::nifi::minifi::sitetosite {
-
-std::shared_ptr<utils::IdGenerator> RawSiteToSiteClient::id_generator_ = utils::IdGenerator::getIdGenerator();
-std::shared_ptr<utils::IdGenerator> Transaction::id_generator_ = utils::IdGenerator::getIdGenerator();
-
-const char *RawSiteToSiteClient::HandShakePropertyStr[MAX_HANDSHAKE_PROPERTY] = { // NOLINT(cppcoreguidelines-avoid-c-arrays)
-/**
- * Boolean value indicating whether or not the contents of a FlowFile should
- * be GZipped when transferred.
- */
-"GZIP",
-/**
- * The unique identifier of the port to communicate with
- */
-"PORT_IDENTIFIER",
-/**
- * Indicates the number of milliseconds after the request was made that the
- * client will wait for a response. If no response has been received by the
- * time this value expires, the server can move on without attempting to
- * service the request because the client will have already disconnected.
- */
-"REQUEST_EXPIRATION_MILLIS",
-/**
- * The preferred number of FlowFiles that the server should send to the
- * client when pulling data. This property was introduced in version 5 of
- * the protocol.
- */
-"BATCH_COUNT",
-/**
- * The preferred number of bytes that the server should send to the client
- * when pulling data. This property was introduced in version 5 of the
- * protocol.
- */
-"BATCH_SIZE",
-/**
- * The preferred amount of time that the server should send data to the
- * client when pulling data. This property was introduced in version 5 of
- * the protocol. Value is in milliseconds.
- */
-"BATCH_DURATION" };
-
-bool RawSiteToSiteClient::establish() {
- if (peer_state_ != IDLE) {
- logger_->log_error("Site2Site peer state is not idle while try to establish");
- return false;
- }
-
- bool ret = peer_->Open();
-
- if (!ret) {
- logger_->log_error("Site2Site peer socket open failed");
- return false;
- }
-
- // Negotiate the version
- ret = initiateResourceNegotiation();
-
- if (!ret) {
- logger_->log_error("Site2Site Protocol Version Negotiation failed");
- return false;
- }
-
- logger_->log_debug("Site2Site socket established");
- peer_state_ = ESTABLISHED;
-
- return true;
-}
-
-bool RawSiteToSiteClient::initiateResourceNegotiation() {
- // Negotiate the version
- if (peer_state_ != IDLE) {
- logger_->log_error("Site2Site peer state is not idle while initiateResourceNegotiation");
- return false;
- }
-
- logger_->log_debug("Negotiate protocol version with destination port {} current version {}", port_id_.to_string(), _currentVersion);
-
- {
- const auto ret = peer_->write(getResourceName());
- logger_->log_trace("result of writing resource name is {}", ret);
- if (ret == 0 || io::isError(ret)) {
- logger_->log_debug("result of writing resource name is {}", ret);
- // tearDown();
- return false;
- }
- }
-
- {
- const auto ret = peer_->write(_currentVersion);
- if (ret == 0 || io::isError(ret)) {
- logger_->log_debug("result of writing version is {}", ret);
- return false;
- }
- }
-
- uint8_t statusCode = 0;
- {
- const auto ret = peer_->read(statusCode);
- if (ret == 0 || io::isError(ret)) {
- logger_->log_debug("result of writing version status code {}", ret);
- return false;
- }
- }
- logger_->log_debug("status code is {}", statusCode);
- switch (statusCode) {
- case RESOURCE_OK: {
- logger_->log_debug("Site2Site Protocol Negotiate protocol version OK");
- return true;
- }
- case DIFFERENT_RESOURCE_VERSION: {
- uint32_t serverVersion = 0;
- {
- const auto ret = peer_->read(serverVersion);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
-
- logger_->log_info("Site2Site Server Response asked for a different protocol version {}", serverVersion);
-
- for (unsigned int i = (_currentVersionIndex + 1); i < sizeof(_supportedVersion) / sizeof(uint32_t); i++) {
- if (serverVersion >= _supportedVersion[i]) {
- _currentVersion = _supportedVersion[i];
- _currentVersionIndex = gsl::narrow<int>(i);
- return initiateResourceNegotiation();
- }
- }
- logger_->log_error("Site2Site Negotiate protocol failed to find a common version with server");
- return false;
- }
- case NEGOTIATED_ABORT: {
- logger_->log_error("Site2Site Negotiate protocol response ABORT");
- return false;
- }
- default: {
- logger_->log_error("Negotiate protocol response unknown code {}", statusCode);
- return false;
- }
- }
-}
-
-bool RawSiteToSiteClient::initiateCodecResourceNegotiation() {
- // Negotiate the version
- if (peer_state_ != HANDSHAKED) {
- logger_->log_error("Site2Site peer state is not handshaked while initiateCodecResourceNegotiation");
- return false;
- }
-
- logger_->log_trace("Negotiate Codec version with destination port {} current version {}", port_id_.to_string(), _currentCodecVersion);
-
- {
- const auto ret = peer_->write(getCodecResourceName());
- if (ret == 0 || io::isError(ret)) {
- logger_->log_debug("result of getCodecResourceName is {}", ret);
- return false;
- }
- }
-
- {
- const auto ret = peer_->write(_currentCodecVersion);
- if (ret == 0 || io::isError(ret)) {
- logger_->log_debug("result of _currentCodecVersion is {}", ret);
- return false;
- }
- }
-
- uint8_t statusCode = 0;
- {
- const auto ret = peer_->read(statusCode);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
- switch (statusCode) {
- case RESOURCE_OK: {
- logger_->log_trace("Site2Site Codec Negotiate version OK");
- return true;
- }
- case DIFFERENT_RESOURCE_VERSION: {
- uint32_t serverVersion = 0;
- {
- const auto ret = peer_->read(serverVersion);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
- logger_->log_info("Site2Site Server Response asked for a different protocol version ", serverVersion);
-
- for (unsigned int i = (_currentCodecVersionIndex + 1); i < sizeof(_supportedCodecVersion) / sizeof(uint32_t); i++) {
- if (serverVersion >= _supportedCodecVersion[i]) {
- _currentCodecVersion = _supportedCodecVersion[i];
- _currentCodecVersionIndex = gsl::narrow<int>(i);
- return initiateCodecResourceNegotiation();
- }
- }
- logger_->log_error("Site2Site Negotiate codec failed to find a common version with server");
- return false;
- }
- case NEGOTIATED_ABORT: {
- logger_->log_error("Site2Site Codec Negotiate response ABORT");
- return false;
- }
- default: {
- logger_->log_error("Negotiate Codec response unknown code {}", statusCode);
- return false;
- }
- }
-}
-
-bool RawSiteToSiteClient::handShake() {
- if (peer_state_ != ESTABLISHED) {
- logger_->log_error("Site2Site peer state is not established while handshake");
- return false;
- }
- logger_->log_debug("Site2Site Protocol Perform hand shake with destination port {}", port_id_.to_string());
- _commsIdentifier = id_generator_->generate();
-
- {
- const auto ret = peer_->write(_commsIdentifier);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
-
- std::map<std::string, std::string> properties;
- properties[HandShakePropertyStr[GZIP]] = "false";
- properties[HandShakePropertyStr[PORT_IDENTIFIER]] = port_id_.to_string();
- properties[HandShakePropertyStr[REQUEST_EXPIRATION_MILLIS]] = std::to_string(_timeout.load().count());
- if (_currentVersion >= 5) {
- if (_batchCount > 0)
- properties[HandShakePropertyStr[BATCH_COUNT]] = std::to_string(_batchCount);
- if (_batchSize > 0)
- properties[HandShakePropertyStr[BATCH_SIZE]] = std::to_string(_batchSize);
- if (_batchDuration.load() > 0ms)
- properties[HandShakePropertyStr[BATCH_DURATION]] = std::to_string(_batchDuration.load().count());
- }
-
- if (_currentVersion >= 3) {
- const auto ret = peer_->write(peer_->getURL());
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
-
- {
- const auto size = gsl::narrow<uint32_t>(properties.size());
- const auto ret = peer_->write(size);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
-
- std::map<std::string, std::string>::iterator it;
- for (it = properties.begin(); it != properties.end(); it++) {
- {
- const auto ret = peer_->write(it->first);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
- {
- const auto ret = peer_->write(it->second);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
- logger_->log_debug("Site2Site Protocol Send handshake properties {} {}", it->first, it->second);
- }
-
- RespondCode code = RESERVED;
- std::string message;
-
- {
- const auto ret = readRespond(nullptr, code, message);
- if (ret <= 0) {
- return false;
- }
- }
-
- auto logPortStateError = [this](const std::string& error) {
- logger_->log_error("Site2Site HandShake Failed because destination port, {}, is {}", port_id_.to_string(), error);
- };
-
- switch (code) {
- case PROPERTIES_OK:
- logger_->log_debug("Site2Site HandShake Completed");
- peer_state_ = HANDSHAKED;
- return true;
- case PORT_NOT_IN_VALID_STATE:
- logPortStateError("in invalid state");
- return false;
- case UNKNOWN_PORT:
- logPortStateError("an unknown port");
- return false;
- case PORTS_DESTINATION_FULL:
- logPortStateError("full");
- return false;
- case UNAUTHORIZED:
- logger_->log_error("Site2Site HandShake on port {} failed: UNAUTHORIZED", port_id_.to_string());
- return false;
- default:
- logger_->log_error("Site2Site HandShake on port {} failed: unknown respond code {}", port_id_.to_string(), magic_enum::enum_underlying(code));
- return false;
- }
-}
-
-void RawSiteToSiteClient::tearDown() {
- if (peer_state_ >= ESTABLISHED) {
- logger_->log_trace("Site2Site Protocol tearDown");
- // need to write shutdown request
- writeRequestType(SHUTDOWN);
- }
-
- known_transactions_.clear();
- peer_->Close();
- peer_state_ = IDLE;
-}
-
-bool RawSiteToSiteClient::getPeerList(std::vector<PeerStatus> &peers) {
- if (establish() && handShake()) {
- if (writeRequestType(REQUEST_PEER_LIST) <= 0) {
- tearDown();
- return false;
- }
-
- uint32_t number_of_peers = 0;
- {
- const auto ret = peer_->read(number_of_peers);
- if (ret == 0 || io::isError(ret)) {
- tearDown();
- return false;
- }
- }
-
- for (uint32_t i = 0; i < number_of_peers; i++) {
- std::string host;
- {
- const auto ret = peer_->read(host);
- if (ret == 0 || io::isError(ret)) {
- tearDown();
- return false;
- }
- }
- uint32_t port = 0;
- {
- const auto ret = peer_->read(port);
- if (ret == 0 || io::isError(ret)) {
- tearDown();
- return false;
- }
- }
- uint8_t secure = 0;
- {
- const auto ret = peer_->read(secure);
- if (ret == 0 || io::isError(ret)) {
- tearDown();
- return false;
- }
- }
- uint32_t count = 0;
- {
- const auto ret = peer_->read(count);
- if (ret == 0 || io::isError(ret)) {
- tearDown();
- return false;
- }
- }
- peers.push_back(PeerStatus{std::make_shared<Peer>(port_id_, host, gsl::narrow<uint16_t>(port), secure != 0), count, true});
- logger_->log_trace("Site2Site Peer host {} port {} Secure {}", host, port, std::to_string(secure));
- }
-
- tearDown();
- return true;
- } else {
- tearDown();
- return false;
- }
-}
-
- int RawSiteToSiteClient::writeRequestType(RequestType type) {
- if (type >= MAX_REQUEST_TYPE)
- return -1;
-
- const auto write_result = peer_->write(SiteToSiteRequest::RequestTypeStr[type]);
- return io::isError(write_result) ? -1 : gsl::narrow<int>(write_result);
- }
-
- int RawSiteToSiteClient::readRequestType(RequestType &type) {
- std::string requestTypeStr;
-
- const auto ret = peer_->read(requestTypeStr);
- if (ret == 0 || io::isError(ret))
- return static_cast<int>(ret);
-
- for (int i = NEGOTIATE_FLOWFILE_CODEC; i <= SHUTDOWN; i++) {
- if (SiteToSiteRequest::RequestTypeStr[i] == requestTypeStr) {
- type = static_cast<RequestType>(i);
- return static_cast<int>(ret);
- }
- }
-
- return -1;
- }
-
-int RawSiteToSiteClient::readRespond(const std::shared_ptr<Transaction> &transaction, RespondCode &code, std::string &message) {
- return readResponse(transaction, code, message);
-}
-
-int RawSiteToSiteClient::writeRespond(const std::shared_ptr<Transaction> &transaction, RespondCode code, const std::string& message) {
- return writeResponse(transaction, code, message);
-}
-
-bool RawSiteToSiteClient::negotiateCodec() {
- if (peer_state_ != HANDSHAKED) {
- logger_->log_error("Site2Site peer state is not handshaked while negotiate codec");
- return false;
- }
-
- logger_->log_trace("Site2Site Protocol Negotiate Codec with destination port {}", port_id_.to_string());
-
- int status = writeRequestType(NEGOTIATE_FLOWFILE_CODEC);
-
- if (status <= 0) {
- return false;
- }
-
- // Negotiate the codec version
- bool ret = initiateCodecResourceNegotiation();
-
- if (!ret) {
- logger_->log_error("Site2Site Codec Version Negotiation failed");
- return false;
- }
-
- logger_->log_trace("Site2Site Codec Completed and move to READY state for data transfer");
- peer_state_ = READY;
-
- return true;
-}
-
-bool RawSiteToSiteClient::bootstrap() {
- if (peer_state_ == READY)
- return true;
-
- tearDown();
-
- if (establish() && handShake() && negotiateCodec()) {
- logger_->log_debug("Site to Site ready for data transaction");
- return true;
- } else {
- peer_->yield();
- tearDown();
- return false;
- }
-}
-
-std::shared_ptr<Transaction> RawSiteToSiteClient::createTransaction(TransferDirection direction) {
- int ret = 0;
- bool dataAvailable = false;
- std::shared_ptr<Transaction> transaction = nullptr;
-
- if (peer_state_ != READY) {
- bootstrap();
- }
-
- if (peer_state_ != READY) {
- return transaction;
- }
-
- if (direction == RECEIVE) {
- ret = writeRequestType(RECEIVE_FLOWFILES);
-
- if (ret <= 0) {
- return transaction;
- }
-
- RespondCode code = RESERVED;
- std::string message;
-
- ret = readRespond(nullptr, code, message);
-
- if (ret <= 0) {
- return transaction;
- }
-
- org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> crcstream(gsl::make_not_null(peer_.get()));
- switch (code) {
- case MORE_DATA:
- dataAvailable = true;
- logger_->log_trace("Site2Site peer indicates that data is available");
- transaction = std::make_shared<Transaction>(direction, std::move(crcstream));
- known_transactions_[transaction->getUUID()] = transaction;
- transaction->setDataAvailable(dataAvailable);
- logger_->log_trace("Site2Site create transaction {}", transaction->getUUIDStr());
- return transaction;
- case NO_MORE_DATA:
- dataAvailable = false;
- logger_->log_trace("Site2Site peer indicates that no data is available");
- transaction = std::make_shared<Transaction>(direction, std::move(crcstream));
- known_transactions_[transaction->getUUID()] = transaction;
- transaction->setDataAvailable(dataAvailable);
- logger_->log_trace("Site2Site create transaction {}", transaction->getUUIDStr());
- return transaction;
- default:
- logger_->log_warn("Site2Site got unexpected response {} when asking for data", magic_enum::enum_underlying(code));
- return nullptr;
- }
- } else {
- ret = writeRequestType(SEND_FLOWFILES);
-
- if (ret <= 0) {
- return nullptr;
- } else {
- org::apache::nifi::minifi::io::CRCStream<SiteToSitePeer> crcstream(gsl::make_not_null(peer_.get()));
- transaction = std::make_shared<Transaction>(direction, std::move(crcstream));
- known_transactions_[transaction->getUUID()] = transaction;
- logger_->log_trace("Site2Site create transaction {}", transaction->getUUIDStr());
- return transaction;
- }
- }
-}
-
-bool RawSiteToSiteClient::transmitPayload(core::ProcessContext& context, core::ProcessSession& session, const std::string &payload,
- std::map<std::string, std::string> attributes) {
- std::shared_ptr<Transaction> transaction;
-
- if (payload.length() <= 0)
- return false;
-
- if (peer_state_ != READY) {
- if (!bootstrap()) {
- return false;
- }
- }
-
- if (peer_state_ != READY) {
- context.yield();
- tearDown();
- throw Exception(SITE2SITE_EXCEPTION, "Can not establish handshake with peer");
- }
-
- // Create the transaction
- transaction = createTransaction(SEND);
-
- if (transaction == nullptr) {
- context.yield();
- tearDown();
- throw Exception(SITE2SITE_EXCEPTION, "Can not create transaction");
- }
-
- utils::Identifier transactionID = transaction->getUUID();
-
- try {
- DataPacket packet(getLogger(), transaction, attributes, payload);
-
- int16_t resp = send(transactionID, &packet, nullptr, &session);
- if (resp == -1) {
- throw Exception(SITE2SITE_EXCEPTION, "Send Failed in transaction " + transactionID.to_string());
- }
- logger_->log_info("Site2Site transaction {} sent bytes length", transactionID.to_string(), payload.length());
-
- if (!confirm(transactionID)) {
- throw Exception(SITE2SITE_EXCEPTION, "Confirm Failed in transaction " + transactionID.to_string());
- }
- if (!complete(context, transactionID)) {
- throw Exception(SITE2SITE_EXCEPTION, "Complete Failed in transaction " + transactionID.to_string());
- }
- logger_->log_info("Site2Site transaction {} successfully send flow record {} content bytes {}", transactionID.to_string(), transaction->current_transfers_, transaction->_bytes);
- } catch (std::exception &exception) {
- if (transaction)
- deleteTransaction(transactionID);
- context.yield();
- tearDown();
- logger_->log_debug("Caught Exception during RawSiteToSiteClient::transmitPayload, type: {}, what: {}", typeid(exception).name(), exception.what());
- throw;
- } catch (...) {
- if (transaction)
- deleteTransaction(transactionID);
- context.yield();
- tearDown();
- logger_->log_debug("Caught Exception during RawSiteToSiteClient::transmitPayload, type: {}", getCurrentExceptionTypeName());
- throw;
- }
-
- deleteTransaction(transactionID);
-
- return true;
-}
-
-} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/sitetosite/SiteToSite.cpp b/libminifi/src/sitetosite/SiteToSite.cpp
deleted file mode 100644
index 190f9c61e..000000000
--- a/libminifi/src/sitetosite/SiteToSite.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "sitetosite/SiteToSite.h"
-
-namespace org::apache::nifi::minifi::sitetosite {
-
-const char *SiteToSiteRequest::RequestTypeStr[MAX_REQUEST_TYPE] = { "NEGOTIATE_FLOWFILE_CODEC", "REQUEST_PEER_LIST", "SEND_FLOWFILES", "RECEIVE_FLOWFILES", "SHUTDOWN" };
-
-// Respond Code Context
-RespondCodeContext SiteToSiteRequest::respondCodeContext[21] = { //NOLINT
- { RESERVED, "Reserved for Future Use", false }, //NOLINT
- { PROPERTIES_OK, "Properties OK", false }, //NOLINT
- { UNKNOWN_PROPERTY_NAME, "Unknown Property Name", true }, //NOLINT
- { ILLEGAL_PROPERTY_VALUE, "Illegal Property Value", true }, //NOLINT
- { MISSING_PROPERTY, "Missing Property", true }, //NOLINT
- { CONTINUE_TRANSACTION, "Continue Transaction", false }, //NOLINT
- { FINISH_TRANSACTION, "Finish Transaction", false }, //NOLINT
- { CONFIRM_TRANSACTION, "Confirm Transaction", true }, //NOLINT
- { TRANSACTION_FINISHED, "Transaction Finished", false }, //NOLINT
- { TRANSACTION_FINISHED_BUT_DESTINATION_FULL, "Transaction Finished But Destination is Full", false }, //NOLINT
- { CANCEL_TRANSACTION, "Cancel Transaction", true }, //NOLINT
- { BAD_CHECKSUM, "Bad Checksum", false }, //NOLINT
- { MORE_DATA, "More Data Exists", false }, //NOLINT
- { NO_MORE_DATA, "No More Data Exists", false }, //NOLINT
- { UNKNOWN_PORT, "Unknown Port", false }, //NOLINT
- { PORT_NOT_IN_VALID_STATE, "Port Not in a Valid State", true }, //NOLINT
- { PORTS_DESTINATION_FULL, "Port's Destination is Full", false }, //NOLINT
- { UNAUTHORIZED, "User Not Authorized", true }, //NOLINT
- { ABORT, "Abort", true }, //NOLINT
- { UNRECOGNIZED_RESPONSE_CODE, "Unrecognized Response Code", false }, //NOLINT
- { END_OF_STREAM, "End of Stream", false } };
-
-} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/sitetosite/SiteToSiteClient.cpp b/libminifi/src/sitetosite/SiteToSiteClient.cpp
index 6b5be1af1..eb68b9636 100644
--- a/libminifi/src/sitetosite/SiteToSiteClient.cpp
+++ b/libminifi/src/sitetosite/SiteToSiteClient.cpp
@@ -20,735 +20,740 @@
#include <map>
#include <string>
#include <memory>
+#include <ranges>
#include "utils/gsl.h"
#include "utils/Enum.h"
namespace org::apache::nifi::minifi::sitetosite {
-int SiteToSiteClient::readResponse(const std::shared_ptr<Transaction>& /*transaction*/, RespondCode &code, std::string &message) {
- uint8_t firstByte = 0;
- {
- const auto ret = peer_->read(firstByte);
- if (ret == 0 || io::isError(ret) || firstByte != CODE_SEQUENCE_VALUE_1)
- return -1;
+std::optional<SiteToSiteResponse> SiteToSiteClient::readResponse(const std::shared_ptr<Transaction>& /*transaction*/) {
+ uint8_t result_byte = 0;
+ if (const auto ret = peer_->read(result_byte); ret == 0 || io::isError(ret) || result_byte != CODE_SEQUENCE_VALUE_1) {
+ logger_->log_error("Site2Site read response failed: invalid code sequence 1 value");
+ return std::nullopt;
}
- uint8_t secondByte = 0;
- {
- const auto ret = peer_->read(secondByte);
- if (ret == 0 || io::isError(ret) || secondByte != CODE_SEQUENCE_VALUE_2)
- return -1;
+ if (const auto ret = peer_->read(result_byte); ret == 0 || io::isError(ret) || result_byte != CODE_SEQUENCE_VALUE_2) {
+ logger_->log_error("Site2Site read response failed: invalid code sequence 2 value");
+ return std::nullopt;
}
- uint8_t thirdByte = 0;
- {
- const auto ret = peer_->read(thirdByte);
- if (ret == 0 || io::isError(ret))
- return static_cast<int>(ret);
+ if (const auto ret = peer_->read(result_byte); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Site2Site read response failed: failed to read response code");
+ return std::nullopt;
}
- code = static_cast<RespondCode>(thirdByte);
- RespondCodeContext *resCode = this->getRespondCodeContext(code);
- if (!resCode) {
- return -1;
+ SiteToSiteResponse response;
+ if (auto code = magic_enum::enum_cast<ResponseCode>(result_byte)) {
+ response.code = *code;
+ } else {
+ logger_->log_error("Site2Site read response failed: invalid response code");
+ return std::nullopt;
}
- if (resCode->hasDescription) {
- const auto ret = peer_->read(message);
- if (ret == 0 || io::isError(ret))
- return -1;
+
+ const ResponseCodeContext* response_code_context = getResponseCodeContext(response.code);
+ if (!response_code_context) {
+ logger_->log_error("Site2Site read response failed: invalid response code context");
+ return std::nullopt;
}
- return gsl::narrow<int>(3 + message.size());
+ if (response_code_context->has_description) {
+ if (const auto ret = peer_->read(response.message); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Site2Site read response failed: failed to read response message");
+ return std::nullopt;
+ }
+ }
+ return response;
}
-void SiteToSiteClient::deleteTransaction(const utils::Identifier& transactionID) {
+void SiteToSiteClient::handleTransactionError(const std::shared_ptr<Transaction>& transaction, core::ProcessContext& context, const std::exception& exception) {
+ if (transaction) {
+ deleteTransaction(transaction->getUUID());
+ }
+ context.yield();
+ tearDown();
+ logger_->log_warn("Caught Exception, type: {}, what: {}", typeid(exception).name(), exception.what());
+}
+
+void SiteToSiteClient::deleteTransaction(const utils::Identifier& transaction_id) {
std::shared_ptr<Transaction> transaction;
- auto it = this->known_transactions_.find(transactionID);
+ auto it = known_transactions_.find(transaction_id);
if (it == known_transactions_.end()) {
+ logger_->log_warn("Site2Site transaction id '{}' not found for delete", transaction_id.to_string());
return;
} else {
transaction = it->second;
}
logger_->log_debug("Site2Site delete transaction {}", transaction->getUUIDStr());
- known_transactions_.erase(transactionID);
+ known_transactions_.erase(transaction_id);
}
-int SiteToSiteClient::writeResponse(const std::shared_ptr<Transaction>& /*transaction*/, RespondCode code, const std::string& message) {
- RespondCodeContext *resCode = this->getRespondCodeContext(code);
- if (!resCode) {
- return -1;
+bool SiteToSiteClient::writeResponse(const std::shared_ptr<Transaction>& /*transaction*/, const SiteToSiteResponse& response) {
+ const ResponseCodeContext* response_code_context = getResponseCodeContext(response.code);
+ if (!response_code_context) {
+ return false;
}
- {
- const std::array<uint8_t, 3> codeSeq = { CODE_SEQUENCE_VALUE_1, CODE_SEQUENCE_VALUE_2, static_cast<uint8_t>(code) };
- const auto ret = peer_->write(codeSeq.data(), 3);
- if (ret != 3)
- return -1;
+ const std::array<uint8_t, 3> code_sequence = { CODE_SEQUENCE_VALUE_1, CODE_SEQUENCE_VALUE_2, magic_enum::enum_underlying(response.code) };
+ const auto ret = peer_->write(code_sequence.data(), 3);
+ if (ret != 3) {
+ return false;
}
- if (resCode->hasDescription) {
- const auto ret = peer_->write(message);
- if (io::isError(ret)) return -1;
- if (ret == 0) return 0;
- return 3 + gsl::narrow<int>(ret);
- } else {
- return 3;
+ if (response_code_context->has_description) {
+ return !(io::isError(peer_->write(response.message)));
}
+ return true;
}
bool SiteToSiteClient::transferFlowFiles(core::ProcessContext& context, core::ProcessSession& session) {
auto flow = session.get();
-
- std::shared_ptr<Transaction> transaction = nullptr;
-
if (!flow) {
return false;
}
- if (peer_state_ != READY) {
- if (!bootstrap())
+ if (peer_state_ != PeerState::READY) {
+ if (!bootstrap()) {
return false;
+ }
}
- if (peer_state_ != READY) {
+ if (peer_state_ != PeerState::READY) {
context.yield();
tearDown();
throw Exception(SITE2SITE_EXCEPTION, "Can not establish handshake with peer");
}
- // Create the transaction
- transaction = createTransaction(SEND);
+ auto transaction = createTransaction(TransferDirection::SEND);
if (transaction == nullptr) {
context.yield();
tearDown();
throw Exception(SITE2SITE_EXCEPTION, "Can not create transaction");
}
- utils::Identifier transactionID = transaction->getUUID();
-
- bool continueTransaction = true;
+ utils::Identifier transaction_id = transaction->getUUID();
std::chrono::high_resolution_clock::time_point transaction_started_at = std::chrono::high_resolution_clock::now();
try {
- while (continueTransaction) {
+ while (true) {
auto start_time = std::chrono::steady_clock::now();
- std::string payload;
- DataPacket packet(getLogger(), transaction, flow->getAttributes(), payload);
- int16_t resp = send(transactionID, &packet, flow, &session);
- if (resp == -1) {
+ if (!sendFlowFile(transaction, *flow, session)) {
throw Exception(SITE2SITE_EXCEPTION, "Send Failed");
}
- logger_->log_debug("Site2Site transaction {} send flow record {}", transactionID.to_string(), flow->getUUIDStr());
- if (resp == 0) {
- auto end_time = std::chrono::steady_clock::now();
- std::string transitUri = peer_->getURL() + "/" + flow->getUUIDStr();
- std::string details = "urn:nifi:" + flow->getUUIDStr() + "Remote Host=" + peer_->getHostName();
- session.getProvenanceReporter()->send(*flow, transitUri, details, std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time), false);
- }
+ logger_->log_debug("Site2Site transaction {} send flow record {}", transaction_id.to_string(), flow->getUUIDStr());
+ auto end_time = std::chrono::steady_clock::now();
+ std::string transit_uri = peer_->getURL() + "/" + flow->getUUIDStr();
+ std::string details = "urn:nifi:" + flow->getUUIDStr() + "Remote Host=" + peer_->getHostName();
+ session.getProvenanceReporter()->send(*flow, transit_uri, details, std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time), false);
session.remove(flow);
std::chrono::nanoseconds transfer_duration = std::chrono::high_resolution_clock::now() - transaction_started_at;
- if (transfer_duration > _batchSendNanos)
+ if (transfer_duration > batch_send_nanos_) {
break;
+ }
flow = session.get();
-
if (!flow) {
- continueTransaction = false;
+ break;
}
- } // while true
+ }
- if (!confirm(transactionID)) {
- throw Exception(SITE2SITE_EXCEPTION, "Confirm Failed for " + transactionID.to_string());
+ if (!confirm(transaction_id)) {
+ throw Exception(SITE2SITE_EXCEPTION, "Confirm Failed for " + transaction_id.to_string());
}
- if (!complete(context, transactionID)) {
- throw Exception(SITE2SITE_EXCEPTION, "Complete Failed for " + transactionID.to_string());
+ if (!complete(context, transaction_id)) {
+ throw Exception(SITE2SITE_EXCEPTION, "Complete Failed for " + transaction_id.to_string());
}
- logger_->log_debug("Site2Site transaction {} successfully sent flow record {}, content bytes {}", transactionID.to_string(), transaction->total_transfers_, transaction->_bytes);
- } catch (std::exception &exception) {
- if (transaction)
- deleteTransaction(transactionID);
- context.yield();
- tearDown();
- logger_->log_debug("Caught Exception during SiteToSiteClient::transferFlowFiles, type: {}, what: {}", typeid(exception).name(), exception.what());
- throw;
- } catch (...) {
- if (transaction)
- deleteTransaction(transactionID);
- context.yield();
- tearDown();
- logger_->log_debug("Caught Exception during SiteToSiteClient::transferFlowFiles, type: {}", getCurrentExceptionTypeName());
+ logger_->log_debug("Site2Site transaction {} successfully sent flow record {}, content bytes {}", transaction_id.to_string(), transaction->getCurrentTransfers(), transaction->getBytes());
+ } catch (const std::exception& exception) {
+ handleTransactionError(transaction, context, exception);
throw;
}
- deleteTransaction(transactionID);
-
+ deleteTransaction(transaction_id);
return true;
}
-bool SiteToSiteClient::confirm(const utils::Identifier& transactionID) {
- int ret = 0;
- std::shared_ptr<Transaction> transaction;
-
- if (peer_state_ != READY) {
- bootstrap();
+bool SiteToSiteClient::confirmReceive(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id) {
+ if (transaction->isDataAvailable()) {
+ return false;
}
-
- if (peer_state_ != READY) {
+ // we received a FINISH_TRANSACTION indicator. Send back a CONFIRM_TRANSACTION message
+ // to peer so that we can verify that the connection is still open. This is a two-phase commit,
+ // which helps to prevent the chances of data duplication. Without doing this, we may commit the
+ // session and then when we send the response back to the peer, the peer may have timed out and may not
+ // be listening. As a result, it will re-send the data. By doing this two-phase commit, we narrow the
+ // Critical Section involved in this transaction so that rather than the Critical Section being the
+ // time window involved in the entire transaction, it is reduced to a simple round-trip conversation.
+ uint64_t crcValue = transaction->getCRC();
+ std::string crc = std::to_string(crcValue);
+ logger_->log_debug("Site2Site Receive confirm with CRC {} to transaction {}", crcValue, transaction_id.to_string());
+ if (!writeResponse(transaction, {ResponseCode::CONFIRM_TRANSACTION, crc})) {
return false;
}
- auto it = this->known_transactions_.find(transactionID);
+ auto response = readResponse(transaction);
+ if (!response) {
+ return false;
+ }
- if (it == known_transactions_.end()) {
+ if (response->code == ResponseCode::CONFIRM_TRANSACTION) {
+ logger_->log_debug("Site2Site transaction {} peer confirm transaction", transaction_id.to_string());
+ transaction->setState(TransactionState::TRANSACTION_CONFIRMED);
+ return true;
+ } else if (response->code == ResponseCode::BAD_CHECKSUM) {
+ logger_->log_debug("Site2Site transaction {} peer indicate bad checksum", transaction_id.to_string());
return false;
}
- transaction = it->second;
+ logger_->log_debug("Site2Site transaction {} peer unknown response code {}", transaction_id.to_string(), magic_enum::enum_underlying(response->code));
+ return false;
+}
- if (transaction->getState() == TRANSACTION_STARTED && !transaction->isDataAvailable() &&
- transaction->getDirection() == RECEIVE) {
- transaction->_state = TRANSACTION_CONFIRMED;
- return true;
+bool SiteToSiteClient::confirmSend(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id) {
+ logger_->log_debug("Site2Site Send FINISH TRANSACTION for transaction {}", transaction_id.to_string());
+ if (!writeResponse(transaction, {ResponseCode::FINISH_TRANSACTION, "FINISH_TRANSACTION"})) {
+ return false;
}
- if (transaction->getState() != DATA_EXCHANGED) {
+ auto response = readResponse(transaction);
+ if (!response) {
return false;
}
- if (transaction->getDirection() == RECEIVE) {
- if (transaction->isDataAvailable()) {
- return false;
- }
- // we received a FINISH_TRANSACTION indicator. Send back a CONFIRM_TRANSACTION message
- // to peer so that we can verify that the connection is still open. This is a two-phase commit,
- // which helps to prevent the chances of data duplication. Without doing this, we may commit the
- // session and then when we send the response back to the peer, the peer may have timed out and may not
- // be listening. As a result, it will re-send the data. By doing this two-phase commit, we narrow the
- // Critical Section involved in this transaction so that rather than the Critical Section being the
- // time window involved in the entire transaction, it is reduced to a simple round-trip conversation.
- uint64_t crcValue = transaction->getCRC();
- std::string crc = std::to_string(crcValue);
- logger_->log_debug("Site2Site Receive confirm with CRC {} to transaction {}", crcValue, transactionID.to_string());
- ret = writeResponse(transaction, CONFIRM_TRANSACTION, crc);
- if (ret <= 0)
- return false;
- RespondCode code = RESERVED;
- std::string message;
- readResponse(transaction, code, message);
- if (ret <= 0)
- return false;
+ if (response->code != ResponseCode::CONFIRM_TRANSACTION) {
+ logger_->log_debug("Site2Site transaction {} peer unknown response code {}", transaction_id.to_string(), magic_enum::enum_underlying(response->code));
+ return false;
+ }
- if (code == CONFIRM_TRANSACTION) {
- logger_->log_debug("Site2Site transaction {} peer confirm transaction", transactionID.to_string());
- transaction->_state = TRANSACTION_CONFIRMED;
+ // we've sent a FINISH_TRANSACTION. Now we'll wait for the peer to send a 'Confirm Transaction' response
+ logger_->log_debug("Site2Site transaction {} peer confirm transaction with CRC {}", transaction_id.to_string(), response->message);
+ if (current_version_ > 3) {
+ std::string crc = std::to_string(transaction->getCRC());
+ if (response->message == crc) {
+ logger_->log_debug("Site2Site transaction {} CRC matched", transaction_id.to_string());
+ if (!writeResponse(transaction, {ResponseCode::CONFIRM_TRANSACTION, "CONFIRM_TRANSACTION"})) {
+ return false;
+ }
+ transaction->setState(TransactionState::TRANSACTION_CONFIRMED);
return true;
- } else if (code == BAD_CHECKSUM) {
- logger_->log_debug("Site2Site transaction {} peer indicate bad checksum", transactionID.to_string());
- return false;
} else {
- logger_->log_debug("Site2Site transaction {} peer unknown response code {}", transactionID.to_string(), magic_enum::enum_underlying(code));
+ logger_->log_debug("Site2Site transaction {} CRC not matched {}", transaction_id.to_string(), crc);
+ writeResponse(transaction, {ResponseCode::BAD_CHECKSUM, "BAD_CHECKSUM"});
return false;
}
} else {
- logger_->log_debug("Site2Site Send FINISH TRANSACTION for transaction {}", transactionID.to_string());
- ret = writeResponse(transaction, FINISH_TRANSACTION, "FINISH_TRANSACTION");
- if (ret <= 0) {
+ if (!writeResponse(transaction, {ResponseCode::CONFIRM_TRANSACTION, "CONFIRM_TRANSACTION"})) {
return false;
}
- RespondCode code = RESERVED;
- std::string message;
- readResponse(transaction, code, message);
-
- // we've sent a FINISH_TRANSACTION. Now we'll wait for the peer to send a 'Confirm Transaction' response
- if (code == CONFIRM_TRANSACTION) {
- logger_->log_debug("Site2Site transaction {} peer confirm transaction with CRC {}", transactionID.to_string(), message);
- if (this->_currentVersion > 3) {
- uint64_t crcValue = transaction->getCRC();
- std::string crc = std::to_string(crcValue);
- if (message == crc) {
- logger_->log_debug("Site2Site transaction {} CRC matched", transactionID.to_string());
- ret = writeResponse(transaction, CONFIRM_TRANSACTION, "CONFIRM_TRANSACTION");
- if (ret <= 0)
- return false;
- transaction->_state = TRANSACTION_CONFIRMED;
- return true;
- } else {
- logger_->log_debug("Site2Site transaction {} CRC not matched {}", transactionID.to_string(), crc);
- writeResponse(transaction, BAD_CHECKSUM, "BAD_CHECKSUM");
- return false;
- }
- }
- ret = writeResponse(transaction, CONFIRM_TRANSACTION, "CONFIRM_TRANSACTION");
- if (ret <= 0)
- return false;
- transaction->_state = TRANSACTION_CONFIRMED;
- return true;
- } else {
- logger_->log_debug("Site2Site transaction {} peer unknown respond code {}", transactionID.to_string(), magic_enum::enum_underlying(code));
- return false;
- }
- return false;
+ transaction->setState(TransactionState::TRANSACTION_CONFIRMED);
+ return true;
}
}
-void SiteToSiteClient::cancel(const utils::Identifier& transactionID) {
- std::shared_ptr<Transaction> transaction = nullptr;
+bool SiteToSiteClient::confirm(const utils::Identifier& transaction_id) {
+ if (peer_state_ != PeerState::READY) {
+ bootstrap();
+ }
- if (peer_state_ != READY) {
- return;
+ if (peer_state_ != PeerState::READY) {
+ return false;
+ }
+
+ auto it = known_transactions_.find(transaction_id);
+ if (it == known_transactions_.end()) {
+ return false;
}
- auto it = this->known_transactions_.find(transactionID);
+ auto transaction = it->second;
+ if (transaction->getState() == TransactionState::TRANSACTION_STARTED && !transaction->isDataAvailable() &&
+ transaction->getDirection() == TransferDirection::RECEIVE) {
+ transaction->setState(TransactionState::TRANSACTION_CONFIRMED);
+ return true;
+ }
+ if (transaction->getState() != TransactionState::DATA_EXCHANGED) {
+ return false;
+ }
+
+ if (transaction->getDirection() == TransferDirection::RECEIVE) {
+ return confirmReceive(transaction, transaction_id);
+ }
+
+ return confirmSend(transaction, transaction_id);
+}
+
+void SiteToSiteClient::cancel(const utils::Identifier& transaction_id) {
+ if (peer_state_ != PeerState::READY) {
+ return;
+ }
+
+ auto it = known_transactions_.find(transaction_id);
if (it == known_transactions_.end()) {
+ logger_->log_warn("Site2Site transaction id '{}' not found for cancel", transaction_id.to_string());
return;
- } else {
- transaction = it->second;
}
- if (transaction->getState() == TRANSACTION_CANCELED || transaction->getState() == TRANSACTION_COMPLETED || transaction->getState() == TRANSACTION_ERROR) {
+ auto transaction = it->second;
+ if (transaction->getState() == TransactionState::TRANSACTION_CANCELED || transaction->getState() == TransactionState::TRANSACTION_COMPLETED ||
+ transaction->getState() == TransactionState::TRANSACTION_ERROR) {
+ logger_->log_debug("Site2Site transaction {} already canceled or completed or in error state", transaction_id.to_string());
return;
}
- this->writeResponse(transaction, CANCEL_TRANSACTION, "Cancel");
- transaction->_state = TRANSACTION_CANCELED;
+ writeResponse(transaction, {ResponseCode::CANCEL_TRANSACTION, "Cancel"});
+ transaction->setState(TransactionState::TRANSACTION_CANCELED);
tearDown();
}
-void SiteToSiteClient::error(const utils::Identifier& transactionID) {
- std::shared_ptr<Transaction> transaction = nullptr;
-
- auto it = this->known_transactions_.find(transactionID);
-
+void SiteToSiteClient::error(const utils::Identifier& transaction_id) {
+ auto it = known_transactions_.find(transaction_id);
if (it == known_transactions_.end()) {
+ logger_->log_warn("Site2Site transaction id '{}' not found for error", transaction_id.to_string());
return;
- } else {
- transaction = it->second;
}
- transaction->_state = TRANSACTION_ERROR;
+ auto transaction = it->second;
+ transaction->setState(TransactionState::TRANSACTION_ERROR);
tearDown();
}
-// Complete the transaction
-bool SiteToSiteClient::complete(core::ProcessContext& context, const utils::Identifier& transactionID) {
- int ret = 0;
- std::shared_ptr<Transaction> transaction = nullptr;
-
- if (peer_state_ != READY) {
- bootstrap();
+bool SiteToSiteClient::completeReceive(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id) {
+ if (transaction->getCurrentTransfers() == 0) {
+ transaction->setState(TransactionState::TRANSACTION_COMPLETED);
+ return true;
}
- if (peer_state_ != READY) {
+ logger_->log_debug("Site2Site transaction {} receive finished", transaction_id.to_string());
+ if (!writeResponse(transaction, {ResponseCode::TRANSACTION_FINISHED, "Finished"})) {
return false;
}
- auto it = this->known_transactions_.find(transactionID);
+ transaction->setState(TransactionState::TRANSACTION_COMPLETED);
+ return true;
+}
- if (it == known_transactions_.end()) {
+bool SiteToSiteClient::completeSend(const std::shared_ptr<Transaction>& transaction, const utils::Identifier& transaction_id, core::ProcessContext& context) {
+ auto response = readResponse(transaction);
+ if (!response) {
return false;
- } else {
- transaction = it->second;
}
- if (transaction->total_transfers_ > 0 && transaction->getState() != TRANSACTION_CONFIRMED) {
- return false;
- }
- if (transaction->getDirection() == RECEIVE) {
- if (transaction->current_transfers_ == 0) {
- transaction->_state = TRANSACTION_COMPLETED;
- return true;
- } else {
- logger_->log_debug("Site2Site transaction {} receive finished", transactionID.to_string());
- ret = this->writeResponse(transaction, TRANSACTION_FINISHED, "Finished");
- if (ret <= 0) {
- return false;
- } else {
- transaction->_state = TRANSACTION_COMPLETED;
- return true;
- }
+ if (response->code == ResponseCode::TRANSACTION_FINISHED || response->code == ResponseCode::TRANSACTION_FINISHED_BUT_DESTINATION_FULL) {
+ logger_->log_info("Site2Site transaction {} peer finished transaction", transaction_id.to_string());
+ transaction->setState(TransactionState::TRANSACTION_COMPLETED);
+
+ if (response->code == ResponseCode::TRANSACTION_FINISHED_BUT_DESTINATION_FULL) {
+ logger_->log_info("Site2Site transaction {} reported destination full, yielding", transaction_id.to_string());
+ context.yield();
}
- } else {
- RespondCode code = RESERVED;
- std::string message;
+ return true;
+ }
- ret = readResponse(transaction, code, message);
+ logger_->log_warn("Site2Site transaction {} peer unexpected response code {}: {}", transaction_id.to_string(), magic_enum::enum_underlying(response->code), magic_enum::enum_name(response->code));
+ return false;
+}
- if (ret <= 0)
- return false;
+bool SiteToSiteClient::complete(core::ProcessContext& context, const utils::Identifier& transaction_id) {
+ if (peer_state_ != PeerState::READY) {
+ bootstrap();
+ }
- if (code == TRANSACTION_FINISHED || code == TRANSACTION_FINISHED_BUT_DESTINATION_FULL) {
- logger_->log_info("Site2Site transaction {} peer finished transaction", transactionID.to_string());
- transaction->_state = TRANSACTION_COMPLETED;
+ if (peer_state_ != PeerState::READY) {
+ return false;
+ }
- if (code == TRANSACTION_FINISHED_BUT_DESTINATION_FULL) {
- logger_->log_info("Site2Site transaction {} reported destination full, yielding", transactionID.to_string());
- context.yield();
- }
- return true;
- } else {
- logger_->log_warn("Site2Site transaction {} peer unexpected respond code {}: {}", transactionID.to_string(), magic_enum::enum_underlying(code), magic_enum::enum_name(code));
- return false;
- }
+ auto it = known_transactions_.find(transaction_id);
+ if (it == known_transactions_.end()) {
+ logger_->log_warn("Site2Site transaction id '{}' not found for complete", transaction_id.to_string());
+ return false;
}
+
+ auto transaction = it->second;
+ if (transaction->getTotalTransfers() > 0 && transaction->getState() != TransactionState::TRANSACTION_CONFIRMED) {
+ logger_->log_warn("Site2Site transaction {} not confirmed", transaction_id.to_string());
+ return false;
+ }
+
+ if (transaction->getDirection() == TransferDirection::RECEIVE) {
+ return completeReceive(transaction, transaction_id);
+ }
+
+ return completeSend(transaction, transaction_id, context);
}
-int16_t SiteToSiteClient::send(const utils::Identifier& transactionID, DataPacket* packet, const std::shared_ptr<core::FlowFile> &flowFile, core::ProcessSession* session) {
- if (peer_state_ != READY) {
+bool SiteToSiteClient::initializeSend(const std::shared_ptr<Transaction>& transaction) {
+ if (peer_state_ != PeerState::READY) {
bootstrap();
}
- if (peer_state_ != READY) {
- return -1;
+ if (peer_state_ != PeerState::READY) {
+ return false;
}
- auto it = this->known_transactions_.find(transactionID);
- if (it == known_transactions_.end()) {
- return -1;
+ if (!transaction) {
+ logger_->log_error("Site2Site transaction is null");
+ return false;
}
- std::shared_ptr<Transaction> transaction = it->second;
- if (transaction->getState() != TRANSACTION_STARTED && transaction->getState() != DATA_EXCHANGED) {
- logger_->log_warn("Site2Site transaction {} is not at started or exchanged state", transactionID.to_string());
- return -1;
+ auto transaction_id = transaction->getUUID();
+ if (transaction->getState() != TransactionState::TRANSACTION_STARTED && transaction->getState() != TransactionState::DATA_EXCHANGED) {
+ logger_->log_warn("Site2Site transaction {} is not at started or exchanged state", transaction_id.to_string());
+ return false;
}
- if (transaction->getDirection() != SEND) {
- logger_->log_warn("Site2Site transaction {} direction is wrong", transactionID.to_string());
- return -1;
+ if (transaction->getDirection() != TransferDirection::SEND) {
+ logger_->log_warn("Site2Site transaction {} direction is wrong", transaction_id.to_string());
+ return false;
}
- if (transaction->current_transfers_ > 0) {
- const auto ret = writeResponse(transaction, CONTINUE_TRANSACTION, "CONTINUE_TRANSACTION");
- if (ret <= 0) {
- return -1;
+ if (transaction->getCurrentTransfers() > 0) {
+ if (!writeResponse(transaction, {ResponseCode::CONTINUE_TRANSACTION, "CONTINUE_TRANSACTION"})) {
+ return false;
}
}
- // start to read the packet
- {
- const auto numAttributes = gsl::narrow<uint32_t>(packet->_attributes.size());
- const auto ret = transaction->getStream().write(numAttributes);
- if (ret != 4) {
- return -1;
- }
+
+ return true;
+}
+
+bool SiteToSiteClient::writeAttributesInSendTransaction(const std::shared_ptr<Transaction>& transaction, const std::map<std::string, std::string>& attributes) {
+ auto transaction_id = transaction->getUUID();
+ if (const auto ret = transaction->getStream().write(gsl::narrow<uint32_t>(attributes.size())); ret != 4) {
+ logger_->log_error("Failed to write number of attributes!");
+ return false;
}
- for (const auto& attribute : packet->_attributes) {
- {
- const auto ret = transaction->getStream().write(attribute.first, true);
- if (ret == 0 || io::isError(ret)) {
- return -1;
- }
+ return std::ranges::all_of(attributes, [&](const auto& attribute) {
+ if (const auto ret = transaction->getStream().write(attribute.first, true); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Failed to write attribute key {}!", attribute.first);
+ return false;
}
- {
- const auto ret = transaction->getStream().write(attribute.second, true);
- if (ret == 0 || io::isError(ret)) {
- return -1;
- }
+ if (const auto ret = transaction->getStream().write(attribute.second, true); ret == 0 || io::isError(ret)) {
+ logger_->log_error("Failed to write attribute value {}!", attribute.second);
+ return false;
}
- logger_->log_debug("Site2Site transaction {} send attribute key {} value {}", transactionID.to_string(), attribute.first, attribute.second);
- }
+ logger_->log_debug("Site2Site transaction {} send attribute key {} value {}", transaction_id.to_string(), attribute.first, attribute.second);
+ return true;
+ });
+}
- bool flowfile_has_content = (flowFile != nullptr);
+void SiteToSiteClient::finalizeSendTransaction(const std::shared_ptr<Transaction>& transaction, uint64_t sent_bytes) {
+ transaction->incrementCurrentTransfers();
+ transaction->incrementTotalTransfers();
+ transaction->setState(TransactionState::DATA_EXCHANGED);
+ transaction->addBytes(sent_bytes);
- if (flowFile && (flowFile->getResourceClaim() == nullptr || !flowFile->getResourceClaim()->exists())) {
- auto path = flowFile->getResourceClaim() != nullptr ? flowFile->getResourceClaim()->getContentFullPath() : "nullclaim";
- logger_->log_debug("Claim {} does not exist for FlowFile {}", path, flowFile->getUUIDStr());
- flowfile_has_content = false;
+ logger_->log_info("Site to Site transaction {} sent flow {} flow records, with total size {}", transaction->getUUID().to_string(), transaction->getTotalTransfers(), transaction->getBytes());
+}
+
+bool SiteToSiteClient::sendFlowFile(const std::shared_ptr<Transaction>& transaction, core::FlowFile& flow_file, core::ProcessSession& session) {
+ if (!initializeSend(transaction)) {
+ return false;
+ }
+
+ auto attributes = flow_file.getAttributes();
+ if (!writeAttributesInSendTransaction(transaction, attributes)) {
+ return false;
}
+ bool flowfile_has_content = [&]() {
+ if (flow_file.getResourceClaim() == nullptr || !flow_file.getResourceClaim()->exists()) {
+ auto path = flow_file.getResourceClaim() != nullptr ? flow_file.getResourceClaim()->getContentFullPath() : "nullclaim";
+ logger_->log_debug("Claim {} does not exist for FlowFile {}", path, flow_file.getUUIDStr());
+ return false;
+ }
+ return true;
+ }();
+
uint64_t len = 0;
- if (flowFile && flowfile_has_content && session) {
- len = flowFile->getSize();
+ if (flowfile_has_content) {
+ len = flow_file.getSize();
const auto ret = transaction->getStream().write(len);
if (ret != 8) {
logger_->log_debug("Failed to write content size!");
- return -1;
+ return false;
}
- if (flowFile->getSize() > 0) {
- session->read(flowFile, [packet](const std::shared_ptr<io::InputStream>& input_stream) -> int64_t {
- const auto result = internal::pipe(*input_stream, packet->transaction_->getStream());
- if (result == -1) return -1;
- packet->_size = gsl::narrow<size_t>(result);
- return result;
+ if (flow_file.getSize() > 0) {
+ auto read_result = session.read(flow_file, [&transaction](const std::shared_ptr<io::InputStream>& input_stream) -> int64_t {
+ return internal::pipe(*input_stream, transaction->getStream());
});
- if (flowFile->getSize() != packet->_size) {
- logger_->log_debug("Mismatched sizes {} {}", flowFile->getSize(), packet->_size);
- return -2;
- }
- }
- if (packet->payload_.length() == 0 && len == 0) {
- if (flowFile->getResourceClaim() == nullptr)
- logger_->log_trace("no claim");
- else
- logger_->log_trace("Flowfile empty {}", flowFile->getResourceClaim()->getContentFullPath());
- }
- } else if (packet->payload_.length() > 0) {
- len = packet->payload_.length();
- {
- const auto ret = transaction->getStream().write(len);
- if (ret != 8) {
- return -1;
- }
- }
- {
- const auto ret = transaction->getStream().write(reinterpret_cast<const uint8_t*>(packet->payload_.c_str()), gsl::narrow<size_t>(len));
- if (ret != gsl::narrow<size_t>(len)) {
- logger_->log_debug("Failed to write payload size!");
- return -1;
+ if (flow_file.getSize() != gsl::narrow<uint64_t>(read_result)) {
+ logger_->log_debug("Mismatched sizes {} {}", flow_file.getSize(), read_result);
+ return false;
}
+ } else {
+ logger_->log_trace("Flowfile empty {}", flow_file.getResourceClaim()->getContentFullPath());
}
- packet->_size += len;
- } else if (flowFile && !flowfile_has_content) {
+ } else {
const auto ret = transaction->getStream().write(len); // Indicate zero length
if (ret != 8) {
logger_->log_debug("Failed to write content size (0)!");
- return -1;
+ return false;
}
}
- transaction->current_transfers_++;
- transaction->total_transfers_++;
- transaction->_state = DATA_EXCHANGED;
- transaction->_bytes += len;
+ finalizeSendTransaction(transaction, len);
+ return true;
+}
- logger_->log_info("Site to Site transaction {} sent flow {} flow records, with total size {}", transactionID.to_string(), transaction->total_transfers_, transaction->_bytes);
+bool SiteToSiteClient::sendPacket(const DataPacket& packet) {
+ if (!initializeSend(packet.transaction)) {
+ return false;
+ }
- return 0;
+ auto transaction = packet.transaction;
+ if (!writeAttributesInSendTransaction(transaction, packet.attributes)) {
+ return false;
+ }
+
+ uint64_t len = 0;
+ if (!packet.payload.empty()) {
+ len = packet.payload.length();
+ if (const auto ret = transaction->getStream().write(len); ret != 8) {
+ logger_->log_debug("Failed to write payload size!");
+ return false;
+ }
+ if (const auto ret = transaction->getStream().write(reinterpret_cast<const uint8_t*>(packet.payload.c_str()), gsl::narrow<size_t>(len)); ret != gsl::narrow<size_t>(len)) {
+ logger_->log_debug("Failed to write payload!");
+ return false;
+ }
+ }
+
+ finalizeSendTransaction(transaction, len);
+ return true;
}
-bool SiteToSiteClient::receive(const utils::Identifier& transactionID, DataPacket *packet, bool &eof) {
- std::shared_ptr<Transaction> transaction;
+bool SiteToSiteClient::readFlowFileHeaderData(const std::shared_ptr<Transaction>& transaction, SiteToSiteClient::ReceiveFlowFileHeaderResult& result) {
+ uint32_t num_attributes = 0;
+ if (const auto ret = transaction->getStream().read(num_attributes); ret == 0 || io::isError(ret) || num_attributes > MAX_NUM_ATTRIBUTES) {
+ return false;
+ }
- if (peer_state_ != READY) {
- bootstrap();
+ const auto transaction_id_str = transaction->getUUID().to_string();
+ logger_->log_debug("Site2Site transaction {} receives {} attributes", transaction_id_str, num_attributes);
+ for (uint64_t i = 0; i < num_attributes; i++) {
+ std::string key;
+ std::string value;
+ if (const auto ret = transaction->getStream().read(key, true); ret == 0 || io::isError(ret)) {
+ return false;
+ }
+
+ if (const auto ret = transaction->getStream().read(value, true); ret == 0 || io::isError(ret)) {
+ return false;
+ }
+
+ result.attributes[key] = value;
+ logger_->log_debug("Site2Site transaction {} receives attribute key {} value {}", transaction_id_str, key, value);
}
- if (peer_state_ != READY) {
+ uint64_t len = 0;
+ if (const auto ret = transaction->getStream().read(len); ret == 0 || io::isError(ret)) {
return false;
}
- auto it = this->known_transactions_.find(transactionID);
+ result.flow_file_data_size = len;
+ return true;
+}
- if (it == known_transactions_.end()) {
- return false;
+std::optional<SiteToSiteClient::ReceiveFlowFileHeaderResult> SiteToSiteClient::receiveFlowFileHeader(const std::shared_ptr<Transaction>& transaction) {
+ if (peer_state_ != PeerState::READY) {
+ bootstrap();
}
- transaction = it->second;
+ if (peer_state_ != PeerState::READY) {
+ return std::nullopt;
+ }
- if (transaction->getState() != TRANSACTION_STARTED && transaction->getState() != DATA_EXCHANGED) {
- logger_->log_warn("Site2Site transaction {} is not at started or exchanged state", transactionID.to_string());
- return false;
+ const auto transaction_id_str = transaction->getUUID().to_string();
+ if (transaction->getState() != TransactionState::TRANSACTION_STARTED && transaction->getState() != TransactionState::DATA_EXCHANGED) {
+ logger_->log_warn("Site2Site transaction {} is not at started or exchanged state", transaction_id_str);
+ return std::nullopt;
}
- if (transaction->getDirection() != RECEIVE) {
- logger_->log_warn("Site2Site transaction {} direction is wrong", transactionID.to_string());
- return false;
+ if (transaction->getDirection() != TransferDirection::RECEIVE) {
+ logger_->log_warn("Site2Site transaction {} direction is wrong", transaction_id_str);
+ return std::nullopt;
}
+ ReceiveFlowFileHeaderResult result;
if (!transaction->isDataAvailable()) {
- eof = true;
- return true;
+ result.eof = true;
+ return result;
}
- if (transaction->current_transfers_ > 0) {
+ if (transaction->getCurrentTransfers() > 0) {
// if we already has transfer before, check to see whether another one is available
- RespondCode code = RESERVED;
- std::string message;
-
- if (readResponse(transaction, code, message) <= 0) {
- return false;
+ auto response = readResponse(transaction);
+ if (!response) {
+ return std::nullopt;
}
- if (code == CONTINUE_TRANSACTION) {
- logger_->log_debug("Site2Site transaction {} peer indicate continue transaction", transactionID.to_string());
- transaction->_dataAvailable = true;
- } else if (code == FINISH_TRANSACTION) {
- logger_->log_debug("Site2Site transaction {} peer indicate finish transaction", transactionID.to_string());
- transaction->_dataAvailable = false;
- eof = true;
- return true;
+ if (response->code == ResponseCode::CONTINUE_TRANSACTION) {
+ logger_->log_debug("Site2Site transaction {} peer indicate continue transaction", transaction_id_str);
+ transaction->setDataAvailable(true);
+ } else if (response->code == ResponseCode::FINISH_TRANSACTION) {
+ logger_->log_debug("Site2Site transaction {} peer indicate finish transaction", transaction_id_str);
+ transaction->setDataAvailable(false);
+ result.eof = true;
+ return result;
} else {
- logger_->log_debug("Site2Site transaction {} peer indicate wrong respond code {}", transactionID.to_string(), magic_enum::enum_underlying(code));
- return false;
+ logger_->log_debug("Site2Site transaction {} peer indicate wrong response code {}", transaction_id_str, magic_enum::enum_underlying(response->code));
+ return std::nullopt;
}
}
if (!transaction->isDataAvailable()) {
logger_->log_debug("No data is available");
- eof = true;
- return true;
+ result.eof = true;
+ return result;
}
- // start to read the packet
- uint32_t numAttributes = 0;
- {
- const auto ret = transaction->getStream().read(numAttributes);
- if (ret == 0 || io::isError(ret) || numAttributes > MAX_NUM_ATTRIBUTES) {
- return false;
- }
+ if (!readFlowFileHeaderData(transaction, result)) {
+ logger_->log_error("Site2Site transaction {} failed to read flow file header data", transaction_id_str);
+ return std::nullopt;
}
- // read the attributes
- logger_->log_debug("Site2Site transaction {} receives attribute key {}", transactionID.to_string(), numAttributes);
- for (unsigned int i = 0; i < numAttributes; i++) {
- std::string key;
- std::string value;
- {
- const auto ret = transaction->getStream().read(key, true);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
- {
- const auto ret = transaction->getStream().read(value, true);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
- packet->_attributes[key] = value;
- logger_->log_debug("Site2Site transaction {} receives attribute key {} value {}", transactionID.to_string(), key, value);
- }
-
- uint64_t len = 0;
- {
- const auto ret = transaction->getStream().read(len);
- if (ret == 0 || io::isError(ret)) {
- return false;
- }
- }
-
- packet->_size = len;
- if (len > 0 || numAttributes > 0) {
- transaction->current_transfers_++;
- transaction->total_transfers_++;
+ if (result.flow_file_data_size > 0 || !result.attributes.empty()) {
+ transaction->incrementCurrentTransfers();
+ transaction->incrementTotalTransfers();
} else {
- logger_->log_warn("Site2Site transaction {} empty flow file without attribute", transactionID.to_string());
- transaction->_dataAvailable = false;
- eof = true;
- return true;
+ logger_->log_warn("Site2Site transaction {} empty flow file without attribute", transaction_id_str);
+ transaction->setDataAvailable(false);
+ result.eof = true;
+ return result;
}
- transaction->_state = DATA_EXCHANGED;
- transaction->_bytes += len;
+ transaction->setState(TransactionState::DATA_EXCHANGED);
+ transaction->addBytes(result.flow_file_data_size);
logger_->log_info("Site to Site transaction {} received flow record {}, total length {}, added {}",
- transactionID.to_string(), transaction->total_transfers_, transaction->_bytes, len);
+ transaction_id_str, transaction->getTotalTransfers(), transaction->getBytes(), result.flow_file_data_size);
- return true;
+ return result;
}
-bool SiteToSiteClient::receiveFlowFiles(core::ProcessContext& context, core::ProcessSession& session) {
+std::pair<uint64_t, uint64_t> SiteToSiteClient::readFlowFiles(const std::shared_ptr<Transaction>& transaction, core::ProcessSession& session) {
+ uint64_t transfers = 0;
uint64_t bytes = 0;
- int transfers = 0;
- std::shared_ptr<Transaction> transaction = nullptr;
+ while (true) {
+ auto start_time = std::chrono::steady_clock::now();
+
+ auto receive_header_result = receiveFlowFileHeader(transaction);
+ if (!receive_header_result) {
+ throw Exception(SITE2SITE_EXCEPTION, "Receive Failed " + transaction->getUUID().to_string());
+ }
+
+ if (receive_header_result->eof) {
+ // transaction done
+ break;
+ }
+
+ auto flow_file = session.create();
+ if (!flow_file) {
+ throw Exception(SITE2SITE_EXCEPTION, "Flow File Creation Failed");
+ }
+
+ std::string source_identifier;
+ for (const auto& [key, value] : receive_header_result->attributes) {
+ if (key == core::SpecialFlowAttribute::UUID) {
+ source_identifier = value;
+ }
+ flow_file->addAttribute(key, value);
+ }
- if (peer_state_ != READY) {
+ if (receive_header_result->flow_file_data_size > 0) {
+ session.write(flow_file, [&receive_header_result, &transaction](const std::shared_ptr<io::OutputStream>& output_stream) -> int64_t {
+ uint64_t len = receive_header_result->flow_file_data_size;
+ std::array<std::byte, utils::configuration::DEFAULT_BUFFER_SIZE> buffer{};
+ while (len > 0) {
+ const auto size = std::min(len, uint64_t{utils::configuration::DEFAULT_BUFFER_SIZE});
+ const auto ret = transaction->getStream().read(std::as_writable_bytes(std::span(buffer).subspan(0, size)));
+ if (ret != size) {
+ return -1;
+ }
+ output_stream->write(std::span(buffer).subspan(0, size));
+ len -= size;
+ }
+ return gsl::narrow<int64_t>(receive_header_result->flow_file_data_size);
+ });
+ if (flow_file->getSize() != receive_header_result->flow_file_data_size) {
+ std::stringstream message;
+ message << "Receive size not correct, expected to send " << flow_file->getSize() << " bytes, but actually sent " << receive_header_result->flow_file_data_size;
+ throw Exception(SITE2SITE_EXCEPTION, message.str());
+ }
+ }
+ core::Relationship relation{"undefined", ""};
+ auto end_time = std::chrono::steady_clock::now();
+ std::string transitUri = peer_->getURL() + "/" + source_identifier;
+ std::string details = "urn:nifi:" + source_identifier + "Remote Host=" + peer_->getHostName();
+ session.getProvenanceReporter()->receive(*flow_file, transitUri, source_identifier, details, std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time));
+ session.transfer(flow_file, relation);
+ // receive the transfer for the flow record
+ bytes += receive_header_result->flow_file_data_size;
+ transfers++;
+ }
+
+ return {transfers, bytes};
+}
+
+bool SiteToSiteClient::receiveFlowFiles(core::ProcessContext& context, core::ProcessSession& session) {
+ if (peer_state_ != PeerState::READY) {
if (!bootstrap()) {
return false;
}
}
- if (peer_state_ != READY) {
+ if (peer_state_ != PeerState::READY) {
context.yield();
tearDown();
throw Exception(SITE2SITE_EXCEPTION, "Can not establish handshake with peer");
}
- // Create the transaction
- transaction = createTransaction(RECEIVE);
-
+ auto transaction = createTransaction(TransferDirection::RECEIVE);
if (transaction == nullptr) {
context.yield();
tearDown();
throw Exception(SITE2SITE_EXCEPTION, "Can not create transaction");
}
- utils::Identifier transactionID = transaction->getUUID();
-
+ utils::Identifier transaction_id = transaction->getUUID();
try {
- while (true) {
- std::map<std::string, std::string> empty;
- auto start_time = std::chrono::steady_clock::now();
- std::string payload;
- DataPacket packet(getLogger(), transaction, empty, payload);
- bool eof = false;
-
- if (!receive(transactionID, &packet, eof)) {
- throw Exception(SITE2SITE_EXCEPTION, "Receive Failed " + transactionID.to_string());
- }
- if (eof) {
- // transaction done
- break;
- }
- auto flowFile = session.create();
+ auto [transfers, bytes] = readFlowFiles(transaction, session);
- if (!flowFile) {
- throw Exception(SITE2SITE_EXCEPTION, "Flow File Creation Failed");
- }
- std::map<std::string, std::string>::iterator it;
- std::string sourceIdentifier;
- for (it = packet._attributes.begin(); it != packet._attributes.end(); it++) {
- if (it->first == core::SpecialFlowAttribute::UUID)
- sourceIdentifier = it->second;
- flowFile->addAttribute(it->first, it->second);
- }
-
- if (packet._size > 0) {
- session.write(flowFile, [&packet](const std::shared_ptr<io::OutputStream>& output_stream) -> int64_t {
- return internal::pipe(packet.transaction_->getStream(), *output_stream);
- });
- if (flowFile->getSize() != packet._size) {
- std::stringstream message;
- message << "Receive size not correct, expected to send " << flowFile->getSize() << " bytes, but actually sent " << packet._size;
- throw Exception(SITE2SITE_EXCEPTION, message.str());
- } else {
- logger_->log_debug("received {} with expected {}", flowFile->getSize(), packet._size);
- }
- }
- core::Relationship relation; // undefined relationship
- auto end_time = std::chrono::steady_clock::now();
- std::string transitUri = peer_->getURL() + "/" + sourceIdentifier;
- std::string details = "urn:nifi:" + sourceIdentifier + "Remote Host=" + peer_->getHostName();
- session.getProvenanceReporter()->receive(*flowFile, transitUri, sourceIdentifier, details, std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time));
- session.transfer(flowFile, relation);
- // receive the transfer for the flow record
- bytes += packet._size;
- transfers++;
- } // while true
-
- if (transfers > 0 && !confirm(transactionID)) {
+ if (transfers > 0 && !confirm(transaction_id)) {
throw Exception(SITE2SITE_EXCEPTION, "Confirm Transaction Failed");
}
- if (!complete(context, transactionID)) {
+
+ if (!complete(context, transaction_id)) {
std::stringstream transaction_str;
- transaction_str << "Complete Transaction " << transactionID.to_string() << " Failed";
+ transaction_str << "Complete Transaction " << transaction_id.to_string() << " Failed";
throw Exception(SITE2SITE_EXCEPTION, transaction_str.str());
}
- logger_->log_info("Site to Site transaction {} received flow record {}, with content size {} bytes", transactionID.to_string(), transfers, bytes);
+
+ logger_->log_info("Site to Site transaction {} received flow record {}, with content size {} bytes", transaction_id.to_string(), transfers, bytes);
// we yield the receive if we did not get anything
- if (transfers == 0)
+ if (transfers == 0) {
context.yield();
- } catch (std::exception &exception) {
- if (transaction)
- deleteTransaction(transactionID);
- context.yield();
- tearDown();
- logger_->log_warn("Caught Exception during RawSiteToSiteClient::receiveFlowFiles, type: {}, what: {}", typeid(exception).name(), exception.what());
- throw;
- } catch (...) {
- if (transaction)
- deleteTransaction(transactionID);
- context.yield();
- tearDown();
- logger_->log_warn("Caught Exception during RawSiteToSiteClient::receiveFlowFiles, type: {}", getCurrentExceptionTypeName());
+ }
+ } catch (const std::exception& exception) {
+ handleTransactionError(transaction, context, exception);
throw;
}
- deleteTransaction(transactionID);
+ deleteTransaction(transaction_id);
return true;
}
+
+const ResponseCodeContext* SiteToSiteClient::getResponseCodeContext(ResponseCode code) {
+ auto it = std::find_if(response_code_contexts.begin(), response_code_contexts.end(), [code](const ResponseCodeContext& context) {
+ return context.code == code;
+ });
+ if (it != response_code_contexts.end()) {
+ return &(*it);
+ }
+ return nullptr;
+}
+
} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/src/sitetosite/SiteToSiteFactory.cpp b/libminifi/src/sitetosite/SiteToSiteFactory.cpp
new file mode 100644
index 000000000..8f05f9b6d
--- /dev/null
+++ b/libminifi/src/sitetosite/SiteToSiteFactory.cpp
@@ -0,0 +1,83 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "sitetosite/SiteToSiteFactory.h"
+
+#include <utility>
+#include <memory>
+
+#include "sitetosite/RawSiteToSiteClient.h"
+#include "sitetosite/HttpSiteToSiteClient.h"
+#include "utils/net/AsioSocketUtils.h"
+#include "core/ClassLoader.h"
+
+namespace org::apache::nifi::minifi::sitetosite {
+
+namespace {
+gsl::not_null<std::unique_ptr<SiteToSitePeer>> createStreamingPeer(const SiteToSiteClientConfiguration &client_configuration) {
+ utils::net::SocketData socket_data{client_configuration.getHost(), client_configuration.getPort(), client_configuration.getSecurityContext()};
+ auto connection = std::make_unique<utils::net::AsioSocketConnection>(socket_data);
+ return gsl::make_not_null(std::make_unique<SiteToSitePeer>(std::move(connection), client_configuration.getHost(), client_configuration.getPort(), client_configuration.getInterface()));
+}
+
+void setCommonConfigurationOptions(SiteToSiteClient& client, const SiteToSiteClientConfiguration &client_configuration) {
+ client.setSSLContextService(client_configuration.getSecurityContext());
+ client.setUseCompression(client_configuration.getUseCompression());
+ if (client_configuration.getBatchCount()) {
+ client.setBatchCount(client_configuration.getBatchCount().value());
+ }
+ if (client_configuration.getBatchSize()) {
+ client.setBatchSize(client_configuration.getBatchSize().value());
+ }
+ if (client_configuration.getBatchDuration()) {
+ client.setBatchDuration(client_configuration.getBatchDuration().value());
+ }
+ if (client_configuration.getTimeout()) {
+ client.setTimeout(client_configuration.getTimeout().value());
+ }
+}
+
+gsl::not_null<std::unique_ptr<SiteToSiteClient>> createRawSocketSiteToSiteClient(const SiteToSiteClientConfiguration &client_configuration) {
+ auto raw_site_to_site_client = gsl::make_not_null(std::make_unique<RawSiteToSiteClient>(createStreamingPeer(client_configuration)));
+ raw_site_to_site_client->setPortId(client_configuration.getPortId());
+ setCommonConfigurationOptions(*raw_site_to_site_client, client_configuration);
+ return raw_site_to_site_client;
+}
+
+gsl::not_null<std::unique_ptr<SiteToSiteClient>> createHttpSiteToSiteClient(const SiteToSiteClientConfiguration &client_configuration) {
+ auto peer = gsl::make_not_null(std::make_unique<SiteToSitePeer>(client_configuration.getHost(), client_configuration.getPort(), client_configuration.getInterface()));
+ peer->setHTTPProxy(client_configuration.getHTTPProxy());
+
+ auto http_site_to_site_client = gsl::make_not_null(std::make_unique<HttpSiteToSiteClient>(std::move(peer)));
+ http_site_to_site_client->setPortId(client_configuration.getPortId());
+ http_site_to_site_client->setIdleTimeout(client_configuration.getIdleTimeout());
+ setCommonConfigurationOptions(*http_site_to_site_client, client_configuration);
+ return http_site_to_site_client;
+}
+} // namespace
+
+gsl::not_null<std::unique_ptr<SiteToSiteClient>> createClient(const SiteToSiteClientConfiguration &client_configuration) {
+ switch (client_configuration.getClientType()) {
+ case ClientType::RAW:
+ return createRawSocketSiteToSiteClient(client_configuration);
+ case ClientType::HTTP:
+ return createHttpSiteToSiteClient(client_configuration);
+ }
+ std::terminate();
+}
+
+} // namespace org::apache::nifi::minifi::sitetosite
diff --git a/libminifi/test/integration/HTTPSiteToSiteTests.cpp b/libminifi/test/integration/HTTPSiteToSiteTests.cpp
index 14391bb74..c7da04333 100644
--- a/libminifi/test/integration/HTTPSiteToSiteTests.cpp
+++ b/libminifi/test/integration/HTTPSiteToSiteTests.cpp
@@ -20,11 +20,11 @@
#include <vector>
#include <iostream>
#include <memory>
-#include "sitetosite/HTTPProtocol.h"
+#include "sitetosite/HttpSiteToSiteClient.h"
#include "processors/InvokeHTTP.h"
#include "unit/TestBase.h"
#include "FlowController.h"
-#include "RemoteProcessorGroupPort.h"
+#include "RemoteProcessGroupPort.h"
#include "core/ConfigurableComponentImpl.h"
#include "integration/HTTPIntegrationBase.h"
#include "integration/HTTPHandlers.h"
@@ -44,7 +44,7 @@ class SiteToSiteTestHarness : public HTTPIntegrationBase {
}
void testSetup() override {
- LogTestController::getInstance().setTrace<minifi::RemoteProcessorGroupPort>();
+ LogTestController::getInstance().setTrace<minifi::RemoteProcessGroupPort>();
LogTestController::getInstance().setTrace<minifi::sitetosite::HttpSiteToSiteClient>();
LogTestController::getInstance().setTrace<minifi::sitetosite::SiteToSiteClient>();
LogTestController::getInstance().setTrace<minifi::http::HTTPClient>();
@@ -174,7 +174,7 @@ void run_variance(const std::filesystem::path& test_file_location, const std::st
assertStr << "Site2Site delete transaction " << transaction_id;
REQUIRE(LogTestController::getInstance().contains(assertStr.str()));
} else {
- assertStr << "Site2Site transaction " << transaction_id << " peer unknown respond code 254";
+ assertStr << "Site2Site transaction " << transaction_id << " peer unknown response code 254";
REQUIRE(LogTestController::getInstance().contains(assertStr.str()));
}
LogTestController::getInstance().reset();
diff --git a/libminifi/test/integration/SiteToSiteRestTest.cpp b/libminifi/test/integration/SiteToSiteRestTest.cpp
index 185b2ad5f..74b5f364c 100644
--- a/libminifi/test/integration/SiteToSiteRestTest.cpp
+++ b/libminifi/test/integration/SiteToSiteRestTest.cpp
@@ -21,13 +21,13 @@
#include "CivetServer.h"
#include "FlowController.h"
-#include "RemoteProcessorGroupPort.h"
#include "controllers/SSLContextService.h"
#include "core/ConfigurableComponentImpl.h"
#include "core/logging/Logger.h"
#include "integration/HTTPIntegrationBase.h"
#include "processors/InvokeHTTP.h"
#include "unit/TestBase.h"
+#include "RemoteProcessGroupPort.h"
#include "unit/TestUtils.h"
namespace org::apache::nifi::minifi::test {
@@ -69,7 +69,7 @@ class SiteToSiteTestHarness : public HTTPIntegrationBase {
}
void testSetup() override {
- LogTestController::getInstance().setTrace<minifi::RemoteProcessorGroupPort>();
+ LogTestController::getInstance().setTrace<minifi::RemoteProcessGroupPort>();
LogTestController::getInstance().setDebug<minifi::http::HTTPClient>();
LogTestController::getInstance().setTrace<minifi::controllers::SSLContextServiceInterface>();
LogTestController::getInstance().setInfo<minifi::FlowController>();
@@ -94,7 +94,7 @@ class SiteToSiteTestHarness : public HTTPIntegrationBase {
} else {
REQUIRE(verifyLogLinePresenceInPollTime(std::chrono::milliseconds(wait_time_), "process group remote site2site port 10001, is secure false"));
}
- REQUIRE(verifyLogLinePresenceInPollTime(std::chrono::milliseconds(wait_time_), "ProcessGroup::refreshRemoteSite2SiteInfo -- curl_easy_perform() failed "));
+ REQUIRE(verifyLogLinePresenceInPollTime(std::chrono::milliseconds(wait_time_), "ProcessGroup::refreshRemoteSiteToSiteInfo -- curl_easy_perform() failed "));
}
protected:
diff --git a/libminifi/test/integration/TimeoutHTTPSiteToSiteTests.cpp b/libminifi/test/integration/TimeoutHTTPSiteToSiteTests.cpp
index b313b8c04..d51e9acf1 100644
--- a/libminifi/test/integration/TimeoutHTTPSiteToSiteTests.cpp
+++ b/libminifi/test/integration/TimeoutHTTPSiteToSiteTests.cpp
@@ -21,11 +21,11 @@
#include <vector>
#include <iostream>
#include <memory>
-#include "sitetosite/HTTPProtocol.h"
+#include "sitetosite/HttpSiteToSiteClient.h"
#include "processors/InvokeHTTP.h"
#include "unit/TestBase.h"
#include "FlowController.h"
-#include "RemoteProcessorGroupPort.h"
+#include "RemoteProcessGroupPort.h"
#include "core/ConfigurableComponentImpl.h"
#include "integration/HTTPIntegrationBase.h"
#include "integration/HTTPHandlers.h"
@@ -45,7 +45,7 @@ class SiteToSiteTestHarness : public HTTPIntegrationBase {
}
void testSetup() override {
- LogTestController::getInstance().setTrace<minifi::RemoteProcessorGroupPort>();
+ LogTestController::getInstance().setTrace<minifi::RemoteProcessGroupPort>();
LogTestController::getInstance().setTrace<minifi::sitetosite::HttpSiteToSiteClient>();
LogTestController::getInstance().setTrace<minifi::sitetosite::SiteToSiteClient>();
LogTestController::getInstance().setTrace<minifi::http::HTTPClient>();
diff --git a/libminifi/test/libtest/integration/HTTPHandlers.cpp b/libminifi/test/libtest/integration/HTTPHandlers.cpp
index 5a36d6654..98d66b675 100644
--- a/libminifi/test/libtest/integration/HTTPHandlers.cpp
+++ b/libminifi/test/libtest/integration/HTTPHandlers.cpp
@@ -29,6 +29,8 @@
#include "range/v3/view/filter.hpp"
#include "range/v3/view/view.hpp"
#include "utils/net/DNS.h"
+#include "sitetosite/HttpSiteToSiteClient.h"
+#include "utils/StringUtils.h"
namespace org::apache::nifi::minifi::test {
@@ -93,6 +95,25 @@ TransactionResponder::TransactionResponder(std::string base_url, std::string por
}
bool TransactionResponder::handlePost(CivetServer* /*server*/, struct mg_connection *conn) {
+ auto req_info = mg_get_request_info(conn);
+ static const std::unordered_map<std::string, std::string> expected_headers {
+ {std::string{minifi::sitetosite::HttpSiteToSiteClient::PROTOCOL_VERSION_HEADER}, "1"},
+ {std::string{minifi::sitetosite::HttpSiteToSiteClient::HANDSHAKE_PROPERTY_USE_COMPRESSION}, "false"},
+ {std::string{minifi::sitetosite::HttpSiteToSiteClient::HANDSHAKE_PROPERTY_REQUEST_EXPIRATION}, "20000"},
+ {std::string{minifi::sitetosite::HttpSiteToSiteClient::HANDSHAKE_PROPERTY_BATCH_COUNT}, "5"},
+ {std::string{minifi::sitetosite::HttpSiteToSiteClient::HANDSHAKE_PROPERTY_BATCH_SIZE}, "100"},
+ {std::string{minifi::sitetosite::HttpSiteToSiteClient::HANDSHAKE_PROPERTY_BATCH_DURATION}, "30000"}
+ };
+ std::unordered_map<std::string, std::string> received_headers;
+ for (int i = 0; i < req_info->num_headers; ++i) {
+ auto header = &req_info->http_headers[i];
+ received_headers[std::string(header->name)] = std::string(header->value);
+ }
+ for (const auto& header : expected_headers) {
+ CHECK(received_headers.contains(header.first));
+ CHECK(received_headers[header.first] == header.second);
+ }
+
std::string site2site_rest_resp;
std::stringstream headers;
headers << "HTTP/1.1 201 OK\r\nContent-Type: application/json\r\nContent-Length: " << site2site_rest_resp.length() << "\r\nX-Location-Uri-Intent: ";
@@ -280,7 +301,7 @@ void HeartbeatHandler::verifyJsonHasAgentManifest(const rapidjson::Document& roo
REQUIRE(manifestHash.length() == 128);
// throws if not a valid hexadecimal hash
- const auto hashVec = utils::string::from_hex(manifestHash);
+ const auto hashVec = minifi::utils::string::from_hex(manifestHash);
REQUIRE(hashVec.size() == 64);
for (auto &bundle : root["agentInfo"]["agentManifest"]["bundles"].GetArray()) {
@@ -406,10 +427,10 @@ void HeartbeatHandler::verifyProperties(const rapidjson::Value& operation_node,
case minifi::c2::Operation::start:
case minifi::c2::Operation::stop: {
auto operands = getOperandsOfProperties(operation_node);
- REQUIRE(operands.find("c2") != operands.end());
+ REQUIRE(operands.contains("c2"));
// FlowController is also present, but this handler has no way of knowing its UUID to test it
for (const auto& component : verify_components) {
- REQUIRE(operands.find(component) != operands.end());
+ REQUIRE(operands.contains(component));
}
break;
}
@@ -426,7 +447,7 @@ void HeartbeatHandler::verifySupportedOperations(const rapidjson::Document& root
for (const auto& operation_node : agent_manifest["supportedOperations"].GetArray()) {
REQUIRE(operation_node.HasMember("type"));
operations.insert(operation_node["type"].GetString());
- verifyProperties(operation_node, utils::enumCast<minifi::c2::Operation>(operation_node["type"].GetString(), true), verify_components, disallowed_properties);
+ verifyProperties(operation_node, minifi::utils::enumCast<minifi::c2::Operation>(operation_node["type"].GetString(), true), verify_components, disallowed_properties);
}
REQUIRE(operations == std::set<std::string>(magic_enum::enum_names<minifi::c2::Operation>().begin(), magic_enum::enum_names<minifi::c2::Operation>().end()));
diff --git a/libminifi/test/libtest/unit/DummyProcessor.h b/libminifi/test/libtest/unit/DummyProcessor.h
index ba7f7bc08..a1b3d2f8c 100644
--- a/libminifi/test/libtest/unit/DummyProcessor.h
+++ b/libminifi/test/libtest/unit/DummyProcessor.h
@@ -46,7 +46,8 @@ class DummyProcessor : public minifi::core::ProcessorImpl {
.isSensitive(true)
.build();
static constexpr auto Properties = std::array<core::PropertyReference, 2>{SimpleProperty, SensitiveProperty};
- static constexpr auto Relationships = std::array<core::RelationshipDefinition, 0>{};
+ static constexpr core::RelationshipDefinition Success{"success", "Success relationship"};
+ static constexpr auto Relationships = std::array{Success};
static constexpr bool SupportsDynamicProperties = true;
static constexpr bool SupportsDynamicRelationships = false;
static constexpr core::annotation::Input InputRequirement = core::annotation::Input::INPUT_ALLOWED;
diff --git a/libminifi/test/resources/TestHTTPSiteToSite.yml b/libminifi/test/resources/TestHTTPSiteToSite.yml
index 5b6baf63c..7250a36ca 100644
--- a/libminifi/test/resources/TestHTTPSiteToSite.yml
+++ b/libminifi/test/resources/TestHTTPSiteToSite.yml
@@ -68,7 +68,7 @@ Remote Processing Groups:
- name: NiFi Flow
id: 471deef6-2a6e-4a7d-912a-81cc17e3a208
url: http://localhost:8099/nifi
- timeout: 30 secs
+ timeout: 20 secs
yield period: 1 sec
transport protocol: HTTP
Input Ports:
@@ -76,6 +76,10 @@ Remote Processing Groups:
name: From Node A
max concurrent tasks: 1
use compression: false
+ batch size:
+ count: 5
+ size: 100 B
+ duration: 30 sec
Properties: # Deviates from spec and will later be removed when this is autonegotiated
Port UUID: 471deef6-2a6e-4a7d-912a-81cc17e3a204
Port: 8082
@@ -85,6 +89,10 @@ Remote Processing Groups:
name: To Node A
max concurrent tasks: 1
use compression: false
+ batch size:
+ count: 5
+ size: 100 B
+ duration: 30 sec
Properties: # Deviates from spec and will later be removed when this is autonegotiated
Port UUID: 471deef6-2a6e-4a7d-912a-81cc17e3a203
Port: 8082
diff --git a/libminifi/test/resources/TestTimeoutHTTPSiteToSite.yml b/libminifi/test/resources/TestTimeoutHTTPSiteToSite.yml
index d49314f18..c41c5e855 100644
--- a/libminifi/test/resources/TestTimeoutHTTPSiteToSite.yml
+++ b/libminifi/test/resources/TestTimeoutHTTPSiteToSite.yml
@@ -45,7 +45,7 @@ Remote Processing Groups:
- name: NiFi Flow
id: 471deef6-2a6e-4a7d-912a-81cc17e3a208
url: http://localhost:8098/nifi
- timeout: 30 secs
+ timeout: 20 secs
yield period: 1 sec
transport protocol: HTTP
Input Ports:
@@ -53,8 +53,12 @@ Remote Processing Groups:
name: From Node A
max concurrent tasks: 1
use compression: false
+ batch size:
+ count: 5
+ size: 100 B
+ duration: 30 sec
Properties: # Deviates from spec and will later be removed when this is autonegotiated
Port UUID: 471deef6-2a6e-4a7d-912a-81cc17e3a204
Port: 8082
Host Name: 127.0.0.1
- Idle Timeout: 200 ms
\ No newline at end of file
+ Idle Timeout: 200 ms
diff --git a/libminifi/test/unit/Site2SiteTests.cpp b/libminifi/test/unit/Site2SiteTests.cpp
deleted file mode 100644
index dd20c2fbb..000000000
--- a/libminifi/test/unit/Site2SiteTests.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- *
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <algorithm>
-#include <map>
-#include <memory>
-#include <string>
-#include <utility>
-
-#include "io/BaseStream.h"
-#include "sitetosite/Peer.h"
-#include "sitetosite/RawSocketProtocol.h"
-#include "unit/TestBase.h"
-#include "unit/Catch.h"
-#include "unit/SiteToSiteHelper.h"
-
-#define FMT_DEFAULT fmt_lower
-
-TEST_CASE("TestSetPortId", "[S2S1]") {
- auto peer = std::make_unique<minifi::sitetosite::SiteToSitePeer>(std::make_unique<org::apache::nifi::minifi::io::BufferStream>(), "fake_host", 65433, "");
-
- minifi::sitetosite::RawSiteToSiteClient protocol(std::move(peer));
-
- utils::Identifier fakeUUID = utils::Identifier::parse("c56a4180-65aa-42ec-a945-5fd21dec0538").value();
-
- protocol.setPortId(fakeUUID);
-
- REQUIRE(fakeUUID == protocol.getPortId());
-}
-
-void sunny_path_bootstrap(const std::unique_ptr<SiteToSiteResponder>& collector) {
- char a = 0x14; // RESOURCE_OK
- std::string resp_code;
- resp_code.insert(resp_code.begin(), a);
- collector->push_response(resp_code);
-
- // Handshake respond code
- resp_code = "R";
- collector->push_response(resp_code);
- resp_code = "C";
- collector->push_response(resp_code);
- char b = 0x1;
- resp_code = b;
- collector->push_response(resp_code);
-
- // Codec Negotiation
- resp_code = a;
- collector->push_response(resp_code);
-}
-
-TEST_CASE("TestSiteToSiteVerifySend", "[S2S3]") {
- auto collector = std::make_unique<SiteToSiteResponder>();
- auto collector_ptr = collector.get();
-
- sunny_path_bootstrap(collector);
-
- auto peer = std::make_unique<minifi::sitetosite::SiteToSitePeer>(std::move(collector), "fake_host", 65433, "");
-
- minifi::sitetosite::RawSiteToSiteClient protocol(std::move(peer));
-
- utils::Identifier fakeUUID = utils::Identifier::parse("C56A4180-65AA-42EC-A945-5FD21DEC0538").value();
-
- protocol.setPortId(fakeUUID);
-
- REQUIRE(true == protocol.bootstrap());
-
- REQUIRE(collector_ptr->get_next_client_response() == "NiFi");
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "SocketFlowFileProtocol");
- collector_ptr->get_next_client_response();
- collector_ptr->get_next_client_response();
- collector_ptr->get_next_client_response();
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "nifi://fake_host:65433");
- collector_ptr->get_next_client_response();
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "GZIP");
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "false");
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "PORT_IDENTIFIER");
- collector_ptr->get_next_client_response();
- REQUIRE(utils::string::equalsIgnoreCase(collector_ptr->get_next_client_response(), "c56a4180-65aa-42ec-a945-5fd21dec0538"));
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "REQUEST_EXPIRATION_MILLIS");
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "30000");
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "NEGOTIATE_FLOWFILE_CODEC");
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "StandardFlowFileCodec");
- collector_ptr->get_next_client_response(); // codec version
-
- // start to send the stuff
- // Create the transaction
- std::string payload = "Test MiNiFi payload";
- std::shared_ptr<minifi::sitetosite::Transaction> transaction;
- transaction = protocol.createTransaction(minifi::sitetosite::SEND);
- REQUIRE(transaction);
- auto transactionID = transaction->getUUID();
- collector_ptr->get_next_client_response();
- REQUIRE(collector_ptr->get_next_client_response() == "SEND_FLOWFILES");
- std::map<std::string, std::string> attributes;
- std::shared_ptr<logging::Logger> logger = nullptr;
- minifi::sitetosite::DataPacket packet(logger, transaction, attributes, payload);
- REQUIRE(protocol.send(transactionID, &packet, nullptr, nullptr) == 0);
- collector_ptr->get_next_client_response();
- collector_ptr->get_next_client_response();
- std::string rx_payload = collector_ptr->get_next_client_response();
- REQUIRE(payload == rx_payload);
-}
-
-TEST_CASE("TestSiteToSiteVerifyNegotiationFail", "[S2S4]") {
- auto collector = std::make_unique<SiteToSiteResponder>();
-
- char a = '\xFF';
- std::string resp_code;
- resp_code.insert(resp_code.begin(), a);
- collector->push_response(resp_code);
- collector->push_response(resp_code);
-
- auto peer = std::make_unique<minifi::sitetosite::SiteToSitePeer>(std::move(collector), "fake_host", 65433, "");
-
- minifi::sitetosite::RawSiteToSiteClient protocol(std::move(peer));
-
- std::string uuid_str = "C56A4180-65AA-42EC-A945-5FD21DEC0538";
-
- utils::Identifier fakeUUID;
-
- fakeUUID = uuid_str;
-
- protocol.setPortId(fakeUUID);
-
- REQUIRE(false == protocol.bootstrap());
-}
diff --git a/libminifi/test/unit/SiteToSiteTests.cpp b/libminifi/test/unit/SiteToSiteTests.cpp
new file mode 100644
index 000000000..e9b6c948d
--- /dev/null
+++ b/libminifi/test/unit/SiteToSiteTests.cpp
@@ -0,0 +1,338 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <algorithm>
+#include <map>
+#include <memory>
+#include <string>
+#include <utility>
+
+#include "io/BaseStream.h"
+#include "sitetosite/Peer.h"
+#include "sitetosite/RawSiteToSiteClient.h"
+#include "unit/TestBase.h"
+#include "unit/Catch.h"
+#include "unit/SiteToSiteHelper.h"
+#include "unit/DummyProcessor.h"
+#include "unit/ProvenanceTestHelper.h"
+
+namespace org::apache::nifi::minifi::test {
+
+class SiteToSiteClientTestAccessor {
+ public:
+ static bool bootstrap(sitetosite::RawSiteToSiteClient& client) {
+ return client.bootstrap();
+ }
+
+ static std::shared_ptr<sitetosite::Transaction> createTransaction(sitetosite::RawSiteToSiteClient& client, sitetosite::TransferDirection direction) {
+ return client.createTransaction(direction);
+ }
+
+ static bool sendFlowFile(sitetosite::RawSiteToSiteClient& client, const std::shared_ptr<sitetosite::Transaction>& transaction, core::FlowFile& flow_file, core::ProcessSession& session) {
+ return client.sendFlowFile(transaction, flow_file, session);
+ }
+
+ static bool sendPacket(sitetosite::RawSiteToSiteClient& client, const sitetosite::DataPacket& packet) {
+ return client.sendPacket(packet);
+ }
+
+ static std::pair<uint64_t, uint64_t> readFlowFiles(sitetosite::RawSiteToSiteClient& client, const std::shared_ptr<sitetosite::Transaction>& transaction, core::ProcessSession& session) {
+ return client.readFlowFiles(transaction, session);
+ }
+};
+
+void initializeMockBootstrapResponses(SiteToSiteResponder& collector) {
+ const char resource_ok_code = magic_enum::enum_underlying(sitetosite::ResourceNegotiationStatusCode::RESOURCE_OK);
+ std::string resp_code;
+ resp_code.insert(resp_code.begin(), resource_ok_code);
+ collector.push_response(resp_code);
+
+ // Handshake response code
+ collector.push_response("R");
+ collector.push_response("C");
+ const char resource_code_properties_ok = magic_enum::enum_underlying(sitetosite::ResponseCode::PROPERTIES_OK);
+ resp_code = resource_code_properties_ok;
+ collector.push_response(resp_code);
+
+ // Codec Negotiation
+ resp_code = resource_ok_code;
+ collector.push_response(resp_code);
+}
+
+void verifyBootstrapMessages(sitetosite::RawSiteToSiteClient& protocol, SiteToSiteResponder& collector) {
+ protocol.setUseCompression(false);
+ protocol.setBatchDuration(std::chrono::milliseconds(100));
+ protocol.setBatchCount(5);
+ protocol.setTimeout(std::chrono::milliseconds(20000));
+
+ minifi::utils::Identifier fake_uuid = minifi::utils::Identifier::parse("C56A4180-65AA-42EC-A945-5FD21DEC0538").value();
+ protocol.setPortId(fake_uuid);
+
+ REQUIRE(true == SiteToSiteClientTestAccessor::bootstrap(protocol));
+
+ REQUIRE(collector.get_next_client_response() == "NiFi");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "SocketFlowFileProtocol");
+ collector.get_next_client_response();
+ collector.get_next_client_response();
+ collector.get_next_client_response();
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "nifi://fake_host:65433");
+ collector.get_next_client_response();
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "BATCH_COUNT");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "5");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "BATCH_DURATION");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "100");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "GZIP");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "false");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "PORT_IDENTIFIER");
+ collector.get_next_client_response();
+ REQUIRE(minifi::utils::string::equalsIgnoreCase(collector.get_next_client_response(), "c56a4180-65aa-42ec-a945-5fd21dec0538"));
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "REQUEST_EXPIRATION_MILLIS");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "20000");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "NEGOTIATE_FLOWFILE_CODEC");
+ collector.get_next_client_response();
+ REQUIRE(collector.get_next_client_response() == "StandardFlowFileCodec");
+ collector.get_next_client_response(); // codec version
+}
+
+void verifySendResponses(SiteToSiteResponder& collector, const std::vector<std::string>& expected_responses) {
+ for (const auto& expected_response : expected_responses) {
+ if (expected_response.empty()) {
+ collector.get_next_client_response();
+ continue;
+ }
+ CHECK(expected_response == collector.get_next_client_response());
+ }
+}
+
+TEST_CASE("TestSetPortId", "[S2S]") {
+ auto peer = gsl::make_not_null(std::make_unique<sitetosite::SiteToSitePeer>(std::make_unique<org::apache::nifi::minifi::io::BufferStream>(), "fake_host", 65433, ""));
+ sitetosite::RawSiteToSiteClient protocol(std::move(peer));
+ auto fake_uuid = minifi::utils::Identifier::parse("c56a4180-65aa-42ec-a945-5fd21dec0538").value();
+ protocol.setPortId(fake_uuid);
+ REQUIRE(fake_uuid == protocol.getPortId());
+}
+
+TEST_CASE("TestSiteToSiteVerifySend using data packet", "[S2S]") {
+ auto collector = std::make_unique<SiteToSiteResponder>();
+ auto collector_ptr = collector.get();
+
+ initializeMockBootstrapResponses(*collector);
+
+ auto peer = gsl::make_not_null(std::make_unique<sitetosite::SiteToSitePeer>(std::move(collector), "fake_host", 65433, ""));
+ sitetosite::RawSiteToSiteClient protocol(std::move(peer));
+
+ std::vector<std::string> expected_responses;
+ std::string payload = "Test MiNiFi payload";
+
+ expected_responses.push_back(""); // attribute count 0
+ expected_responses.push_back(""); // payload length
+ expected_responses.push_back(payload);
+
+ verifyBootstrapMessages(protocol, *collector_ptr);
+
+ // start to send the stuff
+ auto transaction = SiteToSiteClientTestAccessor::createTransaction(protocol, sitetosite::TransferDirection::SEND);
+ REQUIRE(transaction);
+ collector_ptr->get_next_client_response();
+ REQUIRE(collector_ptr->get_next_client_response() == "SEND_FLOWFILES");
+ std::map<std::string, std::string> attributes;
+ sitetosite::DataPacket packet(transaction, attributes, payload);
+ REQUIRE(SiteToSiteClientTestAccessor::sendPacket(protocol, packet));
+ verifySendResponses(*collector_ptr, expected_responses);
+ REQUIRE(transaction->getCRC() == 4000670133);
+}
+
+TEST_CASE("TestSiteToSiteVerifySend using flowfile data", "[S2S]") {
+ auto collector = std::make_unique<SiteToSiteResponder>();
+ auto collector_ptr = collector.get();
+
+ initializeMockBootstrapResponses(*collector);
+
+ auto peer = gsl::make_not_null(std::make_unique<sitetosite::SiteToSitePeer>(std::move(collector), "fake_host", 65433, ""));
+ sitetosite::RawSiteToSiteClient protocol(std::move(peer));
+
+ std::vector<std::string> expected_responses;
+ std::string payload = "Test MiNiFi payload";
+
+ expected_responses.push_back(""); // attribute count
+ expected_responses.push_back(""); // attribute key length
+ expected_responses.push_back("filename");
+ expected_responses.push_back(""); // attribute value length
+ expected_responses.push_back("myfile");
+ expected_responses.push_back(""); // attribute key length
+ expected_responses.push_back("flow.id");
+ expected_responses.push_back(""); // attribute value length
+ expected_responses.push_back("test");
+ expected_responses.push_back(""); // payload length
+ expected_responses.push_back(payload);
+
+ protocol.setBatchDuration(std::chrono::milliseconds(100));
+ protocol.setBatchCount(5);
+ protocol.setTimeout(std::chrono::milliseconds(20000));
+
+ auto fake_uuid = minifi::utils::Identifier::parse("C56A4180-65AA-42EC-A945-5FD21DEC0538").value();
+ protocol.setPortId(fake_uuid);
+
+ verifyBootstrapMessages(protocol, *collector_ptr);
+
+ // start to send the stuff
+ auto transaction = SiteToSiteClientTestAccessor::createTransaction(protocol, sitetosite::TransferDirection::SEND);
+ REQUIRE(transaction);
+ collector_ptr->get_next_client_response();
+ REQUIRE(collector_ptr->get_next_client_response() == "SEND_FLOWFILES");
+
+ TestController test_controller_;
+ TestController::PlanConfig plan_config_;
+ std::shared_ptr<TestPlan> test_plan = test_controller_.createPlan(plan_config_);
+ test_plan->addProcessor("DummyProcessor", "dummyProcessor");
+ std::shared_ptr<minifi::core::ProcessContext> context = [&] { test_plan->runNextProcessor(); return test_plan->getCurrentContext(); }();
+ std::unique_ptr<minifi::core::ProcessSession> session = std::make_unique<core::ProcessSessionImpl>(context);
+
+ auto flow_file = session->create();
+ session->write(flow_file, [&](const std::shared_ptr<io::OutputStream>& output_stream) {
+ std::span<const std::byte> span{reinterpret_cast<const std::byte*>(payload.data()), payload.size()};
+ output_stream->write(span);
+ return payload.size();
+ });
+ flow_file->updateAttribute("filename", "myfile");
+ flow_file->updateAttribute("flow.id", "test");
+ session->transfer(flow_file, DummyProcessor::Success);
+ session->commit();
+
+ std::map<std::string, std::string> attributes;
+ REQUIRE(SiteToSiteClientTestAccessor::sendFlowFile(protocol, transaction, *flow_file, *session));
+ verifySendResponses(*collector_ptr, expected_responses);
+ REQUIRE(transaction->getCRC() == 2886786428);
+}
+
+TEST_CASE("TestSiteToSiteVerifyNegotiationFail", "[S2S]") {
+ auto collector = std::make_unique<SiteToSiteResponder>();
+
+ const char negotiated_abort_code = magic_enum::enum_underlying(sitetosite::ResourceNegotiationStatusCode::NEGOTIATED_ABORT);
+ std::string resp_code;
+ resp_code.insert(resp_code.begin(), negotiated_abort_code);
+ collector->push_response(resp_code);
+ collector->push_response(resp_code);
+
+ auto peer = gsl::make_not_null(std::make_unique<sitetosite::SiteToSitePeer>(std::move(collector), "fake_host", 65433, ""));
+ sitetosite::RawSiteToSiteClient protocol(std::move(peer));
+
+ std::string uuid_str = "C56A4180-65AA-42EC-A945-5FD21DEC0538";
+ minifi::utils::Identifier fake_uuid;
+ fake_uuid = uuid_str;
+ protocol.setPortId(fake_uuid);
+
+ REQUIRE_FALSE(SiteToSiteClientTestAccessor::bootstrap(protocol));
+}
+
+void initializeMockRemoteClientReceiveDataResponses(SiteToSiteResponder& collector) {
+ collector.push_response("R");
+ collector.push_response("C");
+ collector.push_response(std::string{static_cast<char>(magic_enum::enum_underlying(sitetosite::ResponseCode::MORE_DATA))});
+
+ auto addUInt32 = [&collector](uint32_t number) {
+ std::string result(4, '\0');
+ for (std::size_t i = 0; i < 4; ++i) {
+ result[i] = static_cast<char>((number >> (8 * (3 - i))) & 0xFF);
+ }
+ collector.push_response(result);
+ };
+ const uint32_t number_of_attributes = 1;
+ addUInt32(number_of_attributes);
+ std::string attribute_key = "attribute_key";
+ addUInt32(gsl::narrow<uint32_t>(attribute_key.size()));
+ collector.push_response(attribute_key);
+ std::string attribute_value = "attribute_value";
+ addUInt32(gsl::narrow<uint32_t>(attribute_value.size()));
+ collector.push_response(attribute_value);
+ auto addUInt64 = [&collector](uint64_t number) {
+ std::string result(8, '\0');
+ for (std::size_t i = 0; i < 8; ++i) {
+ result[i] = static_cast<char>((number >> (8 * (7 - i))) & 0xFF);
+ }
+ collector.push_response(result);
+ };
+ std::string payload = "data";
+ addUInt64(payload.size());
+ collector.push_response("data");
+
+ collector.push_response("R");
+ collector.push_response("C");
+ const char resource_code_finish_transaction = magic_enum::enum_underlying(sitetosite::ResponseCode::FINISH_TRANSACTION);
+ std::string resp_code;
+ resp_code.insert(resp_code.begin(), resource_code_finish_transaction);
+ collector.push_response(resp_code);
+}
+
+TEST_CASE("Test receiving flow file through site to site", "[S2S]") {
+ auto collector = std::make_unique<SiteToSiteResponder>();
+ auto collector_ptr = collector.get();
+
+ initializeMockBootstrapResponses(*collector);
+ initializeMockRemoteClientReceiveDataResponses(*collector);
+
+ auto peer = gsl::make_not_null(std::make_unique<sitetosite::SiteToSitePeer>(std::move(collector), "fake_host", 65433, ""));
+ sitetosite::RawSiteToSiteClient protocol(std::move(peer));
+
+ verifyBootstrapMessages(protocol, *collector_ptr);
+
+ std::shared_ptr<sitetosite::Transaction> transaction;
+ transaction = SiteToSiteClientTestAccessor::createTransaction(protocol, sitetosite::TransferDirection::RECEIVE);
+ REQUIRE(transaction);
+ collector_ptr->get_next_client_response();
+ REQUIRE(collector_ptr->get_next_client_response() == "RECEIVE_FLOWFILES");
+
+ TestController test_controller;
+ TestController::PlanConfig plan_config;
+ std::shared_ptr<TestPlan> test_plan = test_controller.createPlan(plan_config);
+ auto processor = test_plan->addProcessor("DummyProcessor", "dummyProcessor");
+
+ auto outgoing_connection = std::make_shared<minifi::ConnectionImpl>(nullptr, nullptr, "outgoing_connection");
+ outgoing_connection->addRelationship(core::Relationship{"undefined", ""});
+ outgoing_connection->setSourceUUID(processor->getUUID());
+ outgoing_connection->setSource(processor);
+ processor->addConnection(outgoing_connection.get());
+
+ std::shared_ptr<minifi::core::ProcessContext> context = [&] { test_plan->runNextProcessor(); return test_plan->getCurrentContext(); }();
+ std::unique_ptr<minifi::core::ProcessSession> session = std::make_unique<core::ProcessSessionImpl>(context);
+
+ SiteToSiteClientTestAccessor::readFlowFiles(protocol, transaction, *session);
+ session->commit();
+ std::set<std::shared_ptr<core::FlowFile>> expired;
+ auto flow_file = outgoing_connection->poll(expired);
+ auto attributes = flow_file->getAttributes();
+ REQUIRE(attributes.size() == 3);
+ CHECK(attributes["attribute_key"] == "attribute_value");
+ CHECK(attributes.contains("filename"));
+ CHECK(attributes["flow.id"] == "test");
+ CHECK(test_plan->getContent(flow_file) == "data");
+}
+
+} // namespace org::apache::nifi::minifi::test
diff --git a/packaging/rpm/expected-rpm-contents.in b/packaging/rpm/expected-rpm-contents.in
index 0dbb6968c..cfdd8fa0b 100644
--- a/packaging/rpm/expected-rpm-contents.in
+++ b/packaging/rpm/expected-rpm-contents.in
@@ -34,6 +34,7 @@
/usr/share/doc/nifi-minifi-cpp/FIPS.md
/usr/share/doc/nifi-minifi-cpp/ThirdParties.md
/usr/share/doc/nifi-minifi-cpp/Windows.md
+/usr/share/doc/nifi-minifi-cpp/SITE_TO_SITE.md
/usr/share/doc/nifi-minifi-cpp/pythonprocessor-examples
/usr/share/doc/nifi-minifi-cpp/pythonprocessor-examples/AddPythonAttribute.py
/usr/share/doc/nifi-minifi-cpp/pythonprocessor-examples/CountingProcessor.py
(nifi-minifi-cpp) 02/04: MINIFICPP-2605 Generate MQTT client id in MQTT processors if not set in property
Posted by sz...@apache.org.
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
commit 1fd592fd0c1ed509432431c8b7812e52434aa8bf
Author: Gabor Gyimesi <ga...@gmail.com>
AuthorDate: Tue Sep 30 16:26:41 2025 +0200
MINIFICPP-2605 Generate MQTT client id in MQTT processors if not set in property
Closes #2006
Signed-off-by: Marton Szasz <sz...@apache.org>
---
PROCESSORS.md | 4 ++--
.../mqtt/processors/AbstractMQTTProcessor.cpp | 8 +++----
extensions/mqtt/processors/AbstractMQTTProcessor.h | 5 ++--
extensions/mqtt/processors/ConsumeMQTT.cpp | 10 --------
extensions/mqtt/tests/ConsumeMQTTTests.cpp | 28 ----------------------
extensions/mqtt/tests/PublishMQTTTests.cpp | 8 -------
6 files changed, 9 insertions(+), 54 deletions(-)
diff --git a/PROCESSORS.md b/PROCESSORS.md
index 6749be87b..5204c2f67 100644
--- a/PROCESSORS.md
+++ b/PROCESSORS.md
@@ -402,7 +402,7 @@ In the list below, the names of required properties appear in bold. Any other pr
| Name | Default Value | Allowable Values | Description |
|-----------------------------|---------------|--------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Broker URI** | | | The URI to use to connect to the MQTT broker |
-| Client ID | | | MQTT client ID to use. WARNING: Must not be empty when using MQTT 3.1.0! |
+| Client ID | | | MQTT client ID to use. If not set, a UUID will be generated. |
| **MQTT Version** | 3.x AUTO | 3.x AUTO<br/>3.1.0<br/>3.1.1<br/>5.0 | The MQTT specification version when connecting to the broker. |
| **Topic** | | | The topic to subscribe to. |
| Clean Session | true | true<br/>false | Whether to start afresh rather than remembering previous subscriptions. If true, then make broker forget subscriptions after disconnected. MQTT 3.x only. |
@@ -2218,7 +2218,7 @@ In the list below, the names of required properties appear in bold. Any other pr
| Name | Default Value | Allowable Values | Description |
|-------------------------|---------------|--------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|
| **Broker URI** | | | The URI to use to connect to the MQTT broker |
-| Client ID | | | MQTT client ID to use. WARNING: Must not be empty when using MQTT 3.1.0! |
+| Client ID | | | MQTT client ID to use. If not set, a UUID will be generated. |
| **MQTT Version** | 3.x AUTO | 3.x AUTO<br/>3.1.0<br/>3.1.1<br/>5.0 | The MQTT specification version when connecting to the broker. |
| **Topic** | | | The topic to publish to.<br/>**Supports Expression Language: true** |
| Retain | false | true<br/>false | Retain published message in broker |
diff --git a/extensions/mqtt/processors/AbstractMQTTProcessor.cpp b/extensions/mqtt/processors/AbstractMQTTProcessor.cpp
index 4d132baf1..c1616bf5d 100644
--- a/extensions/mqtt/processors/AbstractMQTTProcessor.cpp
+++ b/extensions/mqtt/processors/AbstractMQTTProcessor.cpp
@@ -30,9 +30,9 @@ void AbstractMQTTProcessor::onSchedule(core::ProcessContext& context, core::Proc
mqtt_version_ = utils::parseEnumProperty<mqtt::MqttVersions>(context, MqttVersion);
if (auto value = context.getProperty(ClientID)) {
- clientID_ = std::move(*value);
- } else if (mqtt_version_ == mqtt::MqttVersions::V_3_1_0) {
- throw minifi::Exception(ExceptionType::PROCESS_SCHEDULE_EXCEPTION, "MQTT 3.1.0 specification does not support empty client IDs");
+ client_id_ = std::move(*value);
+ } else {
+ client_id_ = utils::IdGenerator::getIdGenerator()->generate().to_string();
}
if (auto value = context.getProperty(Username)) {
@@ -120,7 +120,7 @@ void AbstractMQTTProcessor::initializeClient() {
if (mqtt_version_ == mqtt::MqttVersions::V_5_0) {
options.MQTTVersion = MQTTVERSION_5;
}
- if (MQTTAsync_createWithOptions(&client_, uri_.c_str(), clientID_.c_str(), MQTTCLIENT_PERSISTENCE_NONE, nullptr, &options) != MQTTASYNC_SUCCESS) {
+ if (MQTTAsync_createWithOptions(&client_, uri_.c_str(), client_id_.c_str(), MQTTCLIENT_PERSISTENCE_NONE, nullptr, &options) != MQTTASYNC_SUCCESS) {
throw minifi::Exception(ExceptionType::PROCESS_SCHEDULE_EXCEPTION, "Creating MQTT client failed");
}
}
diff --git a/extensions/mqtt/processors/AbstractMQTTProcessor.h b/extensions/mqtt/processors/AbstractMQTTProcessor.h
index 8fdc4f045..222777001 100644
--- a/extensions/mqtt/processors/AbstractMQTTProcessor.h
+++ b/extensions/mqtt/processors/AbstractMQTTProcessor.h
@@ -97,7 +97,8 @@ class AbstractMQTTProcessor : public core::ProcessorImpl {
.isRequired(true)
.build();
EXTENSIONAPI static constexpr auto ClientID = core::PropertyDefinitionBuilder<>::createProperty("Client ID")
- .withDescription("MQTT client ID to use. WARNING: Must not be empty when using MQTT 3.1.0!")
+ .withDescription("MQTT client ID to use. If not set, a UUID will be generated.")
+ .withValidator(core::StandardPropertyValidators::NON_BLANK_VALIDATOR)
.build();
EXTENSIONAPI static constexpr auto QoS = core::PropertyDefinitionBuilder<magic_enum::enum_count<mqtt::MqttQoS>()>::createProperty("Quality of Service")
.withDescription("The Quality of Service (QoS) of messages.")
@@ -236,7 +237,7 @@ class AbstractMQTTProcessor : public core::ProcessorImpl {
std::chrono::seconds keep_alive_interval_{60};
std::chrono::seconds connection_timeout_{10};
mqtt::MqttQoS qos_{mqtt::MqttQoS::LEVEL_0};
- std::string clientID_;
+ std::string client_id_;
std::string username_;
std::string password_;
mqtt::MqttVersions mqtt_version_{mqtt::MqttVersions::V_3X_AUTO};
diff --git a/extensions/mqtt/processors/ConsumeMQTT.cpp b/extensions/mqtt/processors/ConsumeMQTT.cpp
index b354eef22..a2f8be2a6 100644
--- a/extensions/mqtt/processors/ConsumeMQTT.cpp
+++ b/extensions/mqtt/processors/ConsumeMQTT.cpp
@@ -231,16 +231,6 @@ void ConsumeMQTT::checkProperties(core::ProcessContext& context) {
logger_->log_warn("MQTT 5.0 specification does not support Clean Session. Property is not used.");
}
- if (clientID_.empty()) {
- if (mqtt_version_ == mqtt::MqttVersions::V_5_0) {
- if (session_expiry_interval_ > std::chrono::seconds(0)) {
- throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Processor must have a Client ID for durable (Session Expiry Interval > 0) sessions");
- }
- } else if (!clean_session_) {
- throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Processor must have a Client ID for durable (non-clean) sessions");
- }
- }
-
if (qos_ == mqtt::MqttQoS::LEVEL_0) {
if (mqtt_version_ == mqtt::MqttVersions::V_5_0) {
if (session_expiry_interval_ > std::chrono::seconds(0)) {
diff --git a/extensions/mqtt/tests/ConsumeMQTTTests.cpp b/extensions/mqtt/tests/ConsumeMQTTTests.cpp
index 488cbfa21..6e22381c6 100644
--- a/extensions/mqtt/tests/ConsumeMQTTTests.cpp
+++ b/extensions/mqtt/tests/ConsumeMQTTTests.cpp
@@ -58,27 +58,6 @@ TEST_CASE_METHOD(Fixture, "ConsumeMQTTTest_EmptyBrokerURI", "[consumeMQTTTest]")
Catch::Matchers::EndsWith("Expected valid value from \"consumeMqttProcessor::Broker URI\", but got PropertyNotSet (Property Error:2)"));
}
-TEST_CASE_METHOD(Fixture, "ConsumeMQTTTest_DurableSessionWithoutID", "[consumeMQTTTest]") {
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::BrokerURI.name, "127.0.0.1:1883"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::ConsumeMQTT::Topic.name, "mytopic"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::QoS.name, "1"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::ConsumeMQTT::CleanSession.name, "false"));
-
- REQUIRE_THROWS_WITH(plan_->scheduleProcessor(consumeMqttProcessor_),
- Catch::Matchers::EndsWith("Processor must have a Client ID for durable (non-clean) sessions"));
-}
-
-TEST_CASE_METHOD(Fixture, "ConsumeMQTTTest_DurableSessionWithoutID_V_5", "[consumeMQTTTest]") {
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::BrokerURI.name, "127.0.0.1:1883"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::ConsumeMQTT::Topic.name, "mytopic"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::QoS.name, "1"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::MqttVersion.name, std::string{magic_enum::enum_name(minifi::processors::mqtt::MqttVersions::V_5_0)}));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::ConsumeMQTT::SessionExpiryInterval.name, "1 h"));
-
- REQUIRE_THROWS_WITH(plan_->scheduleProcessor(consumeMqttProcessor_),
- Catch::Matchers::EndsWith("Processor must have a Client ID for durable (Session Expiry Interval > 0) sessions"));
-}
-
TEST_CASE_METHOD(Fixture, "ConsumeMQTTTest_DurableSessionWithID", "[consumeMQTTTest]") {
REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::BrokerURI.name, "127.0.0.1:1883"));
REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::ClientID.name, "subscriber"));
@@ -131,13 +110,6 @@ TEST_CASE_METHOD(Fixture, "ConsumeMQTTTest_DurableSessionWithQoS0_V_5", "[consum
"by the broker when QoS is less than 1 for durable (Session Expiry Interval > 0) sessions. Only subscriptions are preserved.", 1s));
}
-TEST_CASE_METHOD(Fixture, "ConsumeMQTTTest_EmptyClientID_V_3_1_0", "[consumeMQTTTest]") {
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::ConsumeMQTT::Topic.name, "mytopic"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::BrokerURI.name, "127.0.0.1:1883"));
- REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::MqttVersion.name, std::string{magic_enum::enum_name(minifi::processors::mqtt::MqttVersions::V_3_1_0)}));
- REQUIRE_THROWS_WITH(plan_->scheduleProcessor(consumeMqttProcessor_), Catch::Matchers::EndsWith("MQTT 3.1.0 specification does not support empty client IDs"));
-}
-
TEST_CASE_METHOD(Fixture, "ConsumeMQTTTest_CleanStart_V_3", "[consumeMQTTTest]") {
REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::BrokerURI.name, "127.0.0.1:1883"));
REQUIRE(consumeMqttProcessor_->setProperty(minifi::processors::ConsumeMQTT::Topic.name, "mytopic"));
diff --git a/extensions/mqtt/tests/PublishMQTTTests.cpp b/extensions/mqtt/tests/PublishMQTTTests.cpp
index dd1d569f1..bcc84f65f 100644
--- a/extensions/mqtt/tests/PublishMQTTTests.cpp
+++ b/extensions/mqtt/tests/PublishMQTTTests.cpp
@@ -60,14 +60,6 @@ TEST_CASE_METHOD(Fixture, "PublishMQTTTest_EmptyBrokerURI", "[publishMQTTTest]")
Catch::Matchers::EndsWith("Expected valid value from \"publishMqttProcessor::Broker URI\", but got PropertyNotSet (Property Error:2)"));
}
-TEST_CASE_METHOD(Fixture, "PublishMQTTTest_EmptyClientID_V_3_1_0", "[publishMQTTTest]") {
- REQUIRE(publishMqttProcessor_->setProperty(minifi::processors::PublishMQTT::Topic.name, "mytopic"));
- REQUIRE(publishMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::BrokerURI.name, "127.0.0.1:1883"));
- REQUIRE(publishMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::MqttVersion.name, std::string{magic_enum::enum_name(minifi::processors::mqtt::MqttVersions::V_3_1_0)}));
- REQUIRE_THROWS_WITH(plan_->scheduleProcessor(publishMqttProcessor_),
- Catch::Matchers::EndsWith("MQTT 3.1.0 specification does not support empty client IDs"));
-}
-
TEST_CASE_METHOD(Fixture, "PublishMQTTTest_EmptyClientID_V_3", "[publishMQTTTest]") {
REQUIRE(publishMqttProcessor_->setProperty(minifi::processors::PublishMQTT::Topic.name, "mytopic"));
REQUIRE(publishMqttProcessor_->setProperty(minifi::processors::AbstractMQTTProcessor::BrokerURI.name, "127.0.0.1:1883"));
(nifi-minifi-cpp) 03/04: MINIFICPP-2614 Add more authentication options to Azure processors
Posted by sz...@apache.org.
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
commit 26409cfd52c762bb6c5242a594a849edac1b19e7
Author: Gabor Gyimesi <ga...@gmail.com>
AuthorDate: Tue Sep 30 16:26:51 2025 +0200
MINIFICPP-2614 Add more authentication options to Azure processors
- Add credential configuration strategy property with from properties,
default credentials, managed identity, and workload identity options
- Add managed identity client id property
- Do not allow SAS Token and Account Key to be used together
BREAKING CHANGE: removing the old `Managed Identity Credentials`
property in favor of the new `Credential Configuration Strategy`
property which allows multiple new Azure authentication options
Closes #2016
Signed-off-by: Marton Szasz <sz...@apache.org>
---
CONTROLLERS.md | 17 ++--
PROCESSORS.md | 102 +++++++++++----------
extensions/aws/processors/PutS3Object.h | 6 +-
.../AzureStorageCredentialsService.cpp | 13 ++-
.../AzureStorageCredentialsService.h | 28 ++++--
.../processors/AzureBlobStorageProcessorBase.cpp | 13 ++-
.../processors/AzureBlobStorageProcessorBase.h | 32 +++++--
.../azure/processors/FetchAzureBlobStorage.h | 2 +-
.../azure/processors/FetchAzureDataLakeStorage.h | 2 +-
.../azure/processors/PutAzureDataLakeStorage.cpp | 13 +--
.../azure/storage/AzureBlobStorageClient.cpp | 10 +-
.../azure/storage/AzureDataLakeStorageClient.cpp | 10 +-
.../azure/storage/AzureStorageCredentials.cpp | 51 +++++++++--
extensions/azure/storage/AzureStorageCredentials.h | 17 +++-
.../azure/tests/DeleteAzureBlobStorageTests.cpp | 74 ++++++++++++++-
.../tests/DeleteAzureDataLakeStorageTests.cpp | 32 ++++++-
.../azure/tests/FetchAzureBlobStorageTests.cpp | 74 ++++++++++++++-
.../azure/tests/FetchAzureDataLakeStorageTests.cpp | 32 ++++++-
.../azure/tests/ListAzureBlobStorageTests.cpp | 64 ++++++++++++-
.../azure/tests/ListAzureDataLakeStorageTests.cpp | 42 ++++++++-
.../azure/tests/PutAzureBlobStorageTests.cpp | 74 ++++++++++++++-
.../azure/tests/PutAzureDataLakeStorageTests.cpp | 32 ++++++-
extensions/azure/utils/AzureEnums.h | 28 ++++++
23 files changed, 621 insertions(+), 147 deletions(-)
diff --git a/CONTROLLERS.md b/CONTROLLERS.md
index 52bf80d40..587470fdd 100644
--- a/CONTROLLERS.md
+++ b/CONTROLLERS.md
@@ -64,14 +64,15 @@ Manages the credentials for an Azure Storage account. This allows for multiple A
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 |
-|----------------------------------------|---------------|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Storage Account Name | | | The storage account name. |
-| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies.<br/>**Sensitive Property: true** |
-| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Managed Identity is not used.<br/>**Sensitive Property: true** |
-| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions). |
-| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Managed Identity is not used. |
-| **Use Managed Identity Credentials** | false | true<br/>false | If true Managed Identity credentials will be used together with the Storage Account Name for authentication. |
+| Name | Default Value | Allowable Values | Description [...]
+|----------------------------------------|-----------------|-----------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ [...]
+| Storage Account Name | | | The storage account name. [...]
+| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies if Credential Configuration Strategy is set to From Properties. If set, SAS Token must be empty.<br/>**Sensitive Property: true* [...]
+| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Credential Configuration Strategy is set to From Properties. If set, Storage Account Key must be empty.<br/>**Sensitive Property: true** [...]
+| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions). [...]
+| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Credential Configuration Strategy is set to From Properties. [...]
+| **Credential Configuration Strategy** | From Properties | From Properties<br/>Default Credential<br/>Managed Identity<br/>Workload Identity | The strategy to use for credential configuration. If set to From Properties, the credentials are parsed from the SAS Token, Storage Account Key, and Connection String properties. In other cases, the selected Azure identity source is used. [...]
+| Managed Identity Client ID | | | Client ID of the managed identity. The property is required when User Assigned Managed Identity is used for authentication and multiple user-assigned identities are added to the resource. It must be empty in case of System Assigned Managed Identity and can also be left empty if only one user-assigned identity is present.<br/>**Sensitive Property [...]
## CouchbaseClusterService
diff --git a/PROCESSORS.md b/PROCESSORS.md
index 5204c2f67..cd4b7141a 100644
--- a/PROCESSORS.md
+++ b/PROCESSORS.md
@@ -543,18 +543,19 @@ Deletes the provided blob from Azure Storage
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 |
-|----------------------------------------|---------------|------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. |
-| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** |
-| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** |
-| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Managed Identity is not used.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions). <br/>**Supports Expression Language: true** |
-| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Managed Identity is not used.<br/>**Supports Expression Language: true** |
-| **Use Managed Identity Credentials** | false | true<br/>false | If true Managed Identity credentials will be used together with the Storage Account Name for authentication. |
-| Blob | | | The filename of the blob. If left empty the filename attribute will be used by default.<br/>**Supports Expression Language: true** |
-| **Delete Snapshots Option** | None | None<br/>Include Snapshots<br/>Delete Snapshots Only | Specifies the snapshot deletion options to be used when deleting a blob. None: Deletes the blob only. Include Snapshots: Delete the blob and its snapshots. Delete Snapshots Only: Delete only the blob's snapshots. |
+| Name | Default Value | Allowable Values | Description [...]
+|----------------------------------------|-----------------|-----------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ [...]
+| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. [...]
+| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** [...]
+| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** [...]
+| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies if Credential Configuration Strategy is set to From Properties. If set, SAS Token must be empty.<br/>**Sensitive Property: true* [...]
+| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Credential Configuration Strategy is set to From Properties. If set, Storage Account Key must be empty.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** [...]
+| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions).<br/>**Supports Expression Language: true** [...]
+| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Credential Configuration Strategy is set to From Properties.<br/>**Supports Expression Language: true** [...]
+| **Credential Configuration Strategy** | From Properties | From Properties<br/>Default Credential<br/>Managed Identity<br/>Workload Identity | The strategy to use for credential configuration. If set to From Properties, the credentials are parsed from the SAS Token, Storage Account Key, and Connection String properties. In other cases, the selected Azure identity source is used. [...]
+| Managed Identity Client ID | | | Client ID of the managed identity. The property is required when User Assigned Managed Identity is used for authentication and multiple user-assigned identities are added to the resource. It must be empty in case of System Assigned Managed Identity and can also be left empty if only one user-assigned identity is present.<br/>**Sensitive Property [...]
+| Blob | | | The filename of the blob. If left empty the filename attribute will be used by default.<br/>**Supports Expression Language: true** [...]
+| **Delete Snapshots Option** | None | None<br/>Include Snapshots<br/>Delete Snapshots Only | Specifies the snapshot deletion options to be used when deleting a blob. None: Deletes the blob only. Include Snapshots: Delete the blob and its snapshots. Delete Snapshots Only: Delete only the blob's snapshots. [...]
### Relationships
@@ -834,19 +835,20 @@ Retrieves contents of an Azure Storage Blob, writing the contents to the content
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 |
-|----------------------------------------|---------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. |
-| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** |
-| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** |
-| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Managed Identity is not used.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions). <br/>**Supports Expression Language: true** |
-| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Managed Identity is not used.<br/>**Supports Expression Language: true** |
-| **Use Managed Identity Credentials** | false | true<br/>false | If true Managed Identity credentials will be used together with the Storage Account Name for authentication. |
-| Blob | | | The filename of the blob. If left empty the filename attribute will be used by default.<br/>**Supports Expression Language: true** |
-| Range Start | | | The byte position at which to start reading from the blob. An empty value or a value of zero will start reading at the beginning of the blob.<br/>**Supports Expression Language: true** |
-| Range Length | | | The number of bytes to download from the blob, starting from the Range Start. An empty value or a value that extends beyond the end of the blob will read to the end of the blob.<br/>**Supports Expression Language: true** |
+| Name | Default Value | Allowable Values | Description [...]
+|----------------------------------------|-----------------|-----------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ [...]
+| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. [...]
+| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** [...]
+| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** [...]
+| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies if Credential Configuration Strategy is set to From Properties. If set, SAS Token must be empty.<br/>**Sensitive Property: true* [...]
+| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Credential Configuration Strategy is set to From Properties. If set, Storage Account Key must be empty.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** [...]
+| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions).<br/>**Supports Expression Language: true** [...]
+| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Credential Configuration Strategy is set to From Properties.<br/>**Supports Expression Language: true** [...]
+| **Credential Configuration Strategy** | From Properties | From Properties<br/>Default Credential<br/>Managed Identity<br/>Workload Identity | The strategy to use for credential configuration. If set to From Properties, the credentials are parsed from the SAS Token, Storage Account Key, and Connection String properties. In other cases, the selected Azure identity source is used. [...]
+| Managed Identity Client ID | | | Client ID of the managed identity. The property is required when User Assigned Managed Identity is used for authentication and multiple user-assigned identities are added to the resource. It must be empty in case of System Assigned Managed Identity and can also be left empty if only one user-assigned identity is present.<br/>**Sensitive Property [...]
+| Blob | | | The filename of the blob. If left empty the filename attribute will be used by default.<br/>**Supports Expression Language: true** [...]
+| Range Start | | | The byte position at which to start reading from the blob. An empty value or a value of zero will start reading at the beginning of the blob.<br/>**Supports Expression Language: true** [...]
+| Range Length | | | The number of bytes to download from the blob, starting from the Range Start. An empty value or a value that extends beyond the end of the blob will read to the end of the blob.<br/>**Supports Expression Language: true** [...]
### Relationships
@@ -1400,18 +1402,19 @@ Lists blobs in an Azure Storage container. Listing details are attached to an em
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 |
-|----------------------------------------|---------------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. |
-| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** |
-| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** |
-| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Managed Identity is not used.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions). <br/>**Supports Expression Language: true** |
-| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Managed Identity is not used.<br/>**Supports Expression Language: true** |
-| **Use Managed Identity Credentials** | false | true<br/>false | If true Managed Identity credentials will be used together with the Storage Account Name for authentication. |
-| **Listing Strategy** | timestamps | none<br/>timestamps | Specify how to determine new/updated entities. If 'timestamps' is selected it tracks the latest timestamp of listed entity to determine new/updated entities. If 'none' is selected it lists an entity without any tracking, the same entity will be listed each time on executing this processor. |
-| Prefix | | | Search prefix for listing<br/>**Supports Expression Language: true** |
+| Name | Default Value | Allowable Values | Description [...]
+|----------------------------------------|-----------------|-----------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ [...]
+| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. [...]
+| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** [...]
+| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** [...]
+| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies if Credential Configuration Strategy is set to From Properties. If set, SAS Token must be empty.<br/>**Sensitive Property: true* [...]
+| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Credential Configuration Strategy is set to From Properties. If set, Storage Account Key must be empty.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** [...]
+| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions).<br/>**Supports Expression Language: true** [...]
+| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Credential Configuration Strategy is set to From Properties.<br/>**Supports Expression Language: true** [...]
+| **Credential Configuration Strategy** | From Properties | From Properties<br/>Default Credential<br/>Managed Identity<br/>Workload Identity | The strategy to use for credential configuration. If set to From Properties, the credentials are parsed from the SAS Token, Storage Account Key, and Connection String properties. In other cases, the selected Azure identity source is used. [...]
+| Managed Identity Client ID | | | Client ID of the managed identity. The property is required when User Assigned Managed Identity is used for authentication and multiple user-assigned identities are added to the resource. It must be empty in case of System Assigned Managed Identity and can also be left empty if only one user-assigned identity is present.<br/>**Sensitive Property [...]
+| **Listing Strategy** | timestamps | none<br/>timestamps | Specify how to determine new/updated entities. If 'timestamps' is selected it tracks the latest timestamp of listed entity to determine new/updated entities. If 'none' is selected it lists an entity without any tracking, the same entity will be listed each time on executing this processor. [...]
+| Prefix | | | Search prefix for listing<br/>**Supports Expression Language: true** [...]
### Relationships
@@ -2325,18 +2328,19 @@ Puts content into an Azure Storage Blob
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 |
-|----------------------------------------|---------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. |
-| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** |
-| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** |
-| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Managed Identity is not used.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** |
-| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions). <br/>**Supports Expression Language: true** |
-| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Managed Identity is not used.<br/>**Supports Expression Language: true** |
-| **Use Managed Identity Credentials** | false | true<br/>false | If true Managed Identity credentials will be used together with the Storage Account Name for authentication. |
-| Blob | | | The filename of the blob. If left empty the filename attribute will be used by default.<br/>**Supports Expression Language: true** |
-| **Create Container** | false | true<br/>false | Specifies whether to check if the container exists and to automatically create it if it does not. Permission to list containers is required. If false, this check is not made, but the Put operation will fail if the container does not exist. |
+| Name | Default Value | Allowable Values | Description [...]
+|----------------------------------------|-----------------|-----------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ [...]
+| Azure Storage Credentials Service | | | Name of the Azure Storage Credentials Service used to retrieve the connection string from. [...]
+| **Container Name** | | | Name of the Azure Storage container. In case of PutAzureBlobStorage processor, container can be created if it does not exist.<br/>**Supports Expression Language: true** [...]
+| Storage Account Name | | | The storage account name.<br/>**Supports Expression Language: true** [...]
+| Storage Account Key | | | The storage account key. This is an admin-like password providing access to every container in this account. It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies if Credential Configuration Strategy is set to From Properties. If set, SAS Token must be empty.<br/>**Sensitive Property: true* [...]
+| SAS Token | | | Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Credential Configuration Strategy is set to From Properties. If set, Storage Account Key must be empty.<br/>**Sensitive Property: true**<br/>**Supports Expression Language: true** [...]
+| Common Storage Account Endpoint Suffix | | | Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a different suffix in certain circumstances (like Azure Stack or non-public Azure regions).<br/>**Supports Expression Language: true** [...]
+| Connection String | | | Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Credential Configuration Strategy is set to From Properties.<br/>**Supports Expression Language: true** [...]
+| **Credential Configuration Strategy** | From Properties | From Properties<br/>Default Credential<br/>Managed Identity<br/>Workload Identity | The strategy to use for credential configuration. If set to From Properties, the credentials are parsed from the SAS Token, Storage Account Key, and Connection String properties. In other cases, the selected Azure identity source is used. [...]
+| Managed Identity Client ID | | | Client ID of the managed identity. The property is required when User Assigned Managed Identity is used for authentication and multiple user-assigned identities are added to the resource. It must be empty in case of System Assigned Managed Identity and can also be left empty if only one user-assigned identity is present.<br/>**Sensitive Property [...]
+| Blob | | | The filename of the blob. If left empty the filename attribute will be used by default.<br/>**Supports Expression Language: true** [...]
+| **Create Container** | false | true<br/>false | Specifies whether to check if the container exists and to automatically create it if it does not. Permission to list containers is required. If false, this check is not made, but the Put operation will fail if the container does not exist. [...]
### Relationships
diff --git a/extensions/aws/processors/PutS3Object.h b/extensions/aws/processors/PutS3Object.h
index 5fe86bf0d..912c45b7d 100644
--- a/extensions/aws/processors/PutS3Object.h
+++ b/extensions/aws/processors/PutS3Object.h
@@ -119,21 +119,21 @@ class PutS3Object : public S3Processor { // NOLINT(cppcoreguidelines-special-me
.build();
EXTENSIONAPI static constexpr auto MultipartThreshold = core::PropertyDefinitionBuilder<>::createProperty("Multipart Threshold")
.withDescription("Specifies the file size threshold for switch from the PutS3Object API to the PutS3MultipartUpload API. "
- "Flow files bigger than this limit will be sent using the multipart process. The valid range is 5MB to 5GB.")
+ "Flow files bigger than this limit will be sent using the multipart process. The valid range is 5MB to 5GB.")
.withValidator(core::StandardPropertyValidators::DATA_SIZE_VALIDATOR)
.withDefaultValue("5 GB")
.isRequired(true)
.build();
EXTENSIONAPI static constexpr auto MultipartPartSize = core::PropertyDefinitionBuilder<>::createProperty("Multipart Part Size")
.withDescription("Specifies the part size for use when the PutS3Multipart Upload API is used. "
- "Flow files will be broken into chunks of this size for the upload process, but the last part sent can be smaller since it is not padded. The valid range is 5MB to 5GB.")
+ "Flow files will be broken into chunks of this size for the upload process, but the last part sent can be smaller since it is not padded. The valid range is 5MB to 5GB.")
.withValidator(core::StandardPropertyValidators::DATA_SIZE_VALIDATOR)
.withDefaultValue("5 GB")
.isRequired(true)
.build();
EXTENSIONAPI static constexpr auto MultipartUploadAgeOffInterval = core::PropertyDefinitionBuilder<>::createProperty("Multipart Upload AgeOff Interval")
.withDescription("Specifies the interval at which existing multipart uploads in AWS S3 will be evaluated for ageoff. "
- "When processor is triggered it will initiate the ageoff evaluation if this interval has been exceeded.")
+ "When processor is triggered it will initiate the ageoff evaluation if this interval has been exceeded.")
.withValidator(core::StandardPropertyValidators::TIME_PERIOD_VALIDATOR)
.withDefaultValue("60 min")
.isRequired(true)
diff --git a/extensions/azure/controllerservices/AzureStorageCredentialsService.cpp b/extensions/azure/controllerservices/AzureStorageCredentialsService.cpp
index 4d0ae2b39..4f128f8f7 100644
--- a/extensions/azure/controllerservices/AzureStorageCredentialsService.cpp
+++ b/extensions/azure/controllerservices/AzureStorageCredentialsService.cpp
@@ -21,6 +21,7 @@
#include <set>
#include "core/Resource.h"
+#include "minifi-cpp/Exception.h"
namespace org::apache::nifi::minifi::azure::controllers {
@@ -29,6 +30,12 @@ void AzureStorageCredentialsService::initialize() {
}
void AzureStorageCredentialsService::onEnable() {
+ auto credential_configuration_strategy_str = getProperty(CredentialConfigurationStrategy.name).value_or(std::string{magic_enum::enum_name(CredentialConfigurationStrategyOption::FromProperties)});
+ if (auto credential_configuration_strategy = magic_enum::enum_cast<CredentialConfigurationStrategyOption>(credential_configuration_strategy_str)) {
+ credentials_.setCredentialConfigurationStrategy(*credential_configuration_strategy);
+ } else {
+ throw minifi::Exception(ExceptionType::PROCESS_SCHEDULE_EXCEPTION, "Invalid Credential Configuration Strategy: " + credential_configuration_strategy_str);
+ }
if (auto storage_account_name = getProperty(StorageAccountName.name)) {
credentials_.setStorageAccountName(*storage_account_name);
}
@@ -39,13 +46,13 @@ void AzureStorageCredentialsService::onEnable() {
credentials_.setSasToken(*sas_token);
}
if (auto common_storage_account_endpoint_suffix = getProperty(CommonStorageAccountEndpointSuffix.name)) {
- credentials_.setEndpontSuffix(*common_storage_account_endpoint_suffix);
+ credentials_.setEndpointSuffix(*common_storage_account_endpoint_suffix);
}
if (auto connection_String = getProperty(ConnectionString.name)) {
credentials_.setConnectionString(*connection_String);
}
- if (auto use_managed_identity_credentials = getProperty(UseManagedIdentityCredentials.name) | utils::andThen(parsing::parseBool)) {
- credentials_.setUseManagedIdentityCredentials(*use_managed_identity_credentials);
+ if (auto managed_identity_client_id = getProperty(ManagedIdentityClientId.name)) {
+ credentials_.setManagedIdentityClientId(*managed_identity_client_id);
}
}
diff --git a/extensions/azure/controllerservices/AzureStorageCredentialsService.h b/extensions/azure/controllerservices/AzureStorageCredentialsService.h
index 0b655edcb..4662bd630 100644
--- a/extensions/azure/controllerservices/AzureStorageCredentialsService.h
+++ b/extensions/azure/controllerservices/AzureStorageCredentialsService.h
@@ -29,6 +29,7 @@
#include "minifi-cpp/core/PropertyValidator.h"
#include "storage/AzureStorageCredentials.h"
#include "utils/Export.h"
+#include "utils/AzureEnums.h"
namespace org::apache::nifi::minifi::azure::controllers {
@@ -42,11 +43,13 @@ class AzureStorageCredentialsService : public core::controller::ControllerServic
.build();
EXTENSIONAPI static constexpr auto StorageAccountKey = core::PropertyDefinitionBuilder<>::createProperty("Storage Account Key")
.withDescription("The storage account key. This is an admin-like password providing access to every container in this account. "
- "It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies.")
+ "It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies "
+ "if Credential Configuration Strategy is set to From Properties. If set, SAS Token must be empty.")
.isSensitive(true)
.build();
EXTENSIONAPI static constexpr auto SASToken = core::PropertyDefinitionBuilder<>::createProperty("SAS Token")
- .withDescription("Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Managed Identity is not used.")
+ .withDescription("Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name "
+ "if Credential Configuration Strategy is set to From Properties. If set, Storage Account Key must be empty.")
.isSensitive(true)
.build();
EXTENSIONAPI static constexpr auto CommonStorageAccountEndpointSuffix = core::PropertyDefinitionBuilder<>::createProperty("Common Storage Account Endpoint Suffix")
@@ -54,13 +57,21 @@ class AzureStorageCredentialsService : public core::controller::ControllerServic
"different suffix in certain circumstances (like Azure Stack or non-public Azure regions).")
.build();
EXTENSIONAPI static constexpr auto ConnectionString = core::PropertyDefinitionBuilder<>::createProperty("Connection String")
- .withDescription("Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Managed Identity is not used.")
+ .withDescription("Connection string used to connect to Azure Storage service. This overrides all other set credential properties "
+ "if Credential Configuration Strategy is set to From Properties.")
.build();
- EXTENSIONAPI static constexpr auto UseManagedIdentityCredentials = core::PropertyDefinitionBuilder<>::createProperty("Use Managed Identity Credentials")
- .withDescription("If true Managed Identity credentials will be used together with the Storage Account Name for authentication.")
+ EXTENSIONAPI static constexpr auto CredentialConfigurationStrategy =
+ core::PropertyDefinitionBuilder<magic_enum::enum_count<CredentialConfigurationStrategyOption>()>::createProperty("Credential Configuration Strategy")
+ .withDescription("The strategy to use for credential configuration. If set to From Properties, the credentials are parsed from the SAS Token, Storage Account Key, "
+ "and Connection String properties. In other cases, the selected Azure identity source is used.")
.isRequired(true)
- .withValidator(core::StandardPropertyValidators::BOOLEAN_VALIDATOR)
- .withDefaultValue("false")
+ .withDefaultValue(magic_enum::enum_name(CredentialConfigurationStrategyOption::FromProperties))
+ .withAllowedValues(magic_enum::enum_names<CredentialConfigurationStrategyOption>())
+ .build();
+ EXTENSIONAPI static constexpr auto ManagedIdentityClientId = core::PropertyDefinitionBuilder<>::createProperty("Managed Identity Client ID")
+ .withDescription("Client ID of the managed identity. The property is required when User Assigned Managed Identity is used for authentication and multiple user-assigned identities "
+ "are added to the resource. It must be empty in case of System Assigned Managed Identity and can also be left empty if only one user-assigned identity is present.")
+ .isSensitive(true)
.build();
EXTENSIONAPI static constexpr auto Properties = std::to_array<core::PropertyReference>({
StorageAccountName,
@@ -68,7 +79,8 @@ class AzureStorageCredentialsService : public core::controller::ControllerServic
SASToken,
CommonStorageAccountEndpointSuffix,
ConnectionString,
- UseManagedIdentityCredentials
+ CredentialConfigurationStrategy,
+ ManagedIdentityClientId
});
diff --git a/extensions/azure/processors/AzureBlobStorageProcessorBase.cpp b/extensions/azure/processors/AzureBlobStorageProcessorBase.cpp
index f0eee83a7..88ae2a2e9 100644
--- a/extensions/azure/processors/AzureBlobStorageProcessorBase.cpp
+++ b/extensions/azure/processors/AzureBlobStorageProcessorBase.cpp
@@ -35,10 +35,10 @@ void AzureBlobStorageProcessorBase::onSchedule(core::ProcessContext& context, co
return;
}
- use_managed_identity_credentials_ = minifi::utils::parseBoolProperty(context, UseManagedIdentityCredentials);
+ credential_configuration_strategy_ = minifi::utils::parseEnumProperty<CredentialConfigurationStrategyOption>(context, CredentialConfigurationStrategy);
- if (use_managed_identity_credentials_) {
- logger_->log_info("Using Managed Identity for authentication");
+ if (credential_configuration_strategy_ != CredentialConfigurationStrategyOption::FromProperties) {
+ logger_->log_info("Using {} for authentication", magic_enum::enum_name(credential_configuration_strategy_));
return;
}
@@ -66,6 +66,7 @@ void AzureBlobStorageProcessorBase::onSchedule(core::ProcessContext& context, co
storage::AzureStorageCredentials AzureBlobStorageProcessorBase::getAzureCredentialsFromProperties(
core::ProcessContext &context, const core::FlowFile* const flow_file) const {
storage::AzureStorageCredentials credentials;
+ credentials.setCredentialConfigurationStrategy(credential_configuration_strategy_);
if (const auto value = context.getProperty(StorageAccountName, flow_file)) {
credentials.setStorageAccountName(*value);
}
@@ -76,12 +77,14 @@ storage::AzureStorageCredentials AzureBlobStorageProcessorBase::getAzureCredenti
credentials.setSasToken(*value);
}
if (const auto value = context.getProperty(CommonStorageAccountEndpointSuffix, flow_file)) {
- credentials.setEndpontSuffix(*value);
+ credentials.setEndpointSuffix(*value);
}
if (const auto value = context.getProperty(ConnectionString, flow_file)) {
credentials.setConnectionString(*value);
}
- credentials.setUseManagedIdentityCredentials(use_managed_identity_credentials_);
+ if (const auto value = context.getProperty(ManagedIdentityClientId, flow_file)) {
+ credentials.setManagedIdentityClientId(*value);
+ }
return credentials;
}
diff --git a/extensions/azure/processors/AzureBlobStorageProcessorBase.h b/extensions/azure/processors/AzureBlobStorageProcessorBase.h
index 32eb7f793..88c09bd75 100644
--- a/extensions/azure/processors/AzureBlobStorageProcessorBase.h
+++ b/extensions/azure/processors/AzureBlobStorageProcessorBase.h
@@ -50,29 +50,40 @@ class AzureBlobStorageProcessorBase : public AzureStorageProcessorBase {
.build();
EXTENSIONAPI static constexpr auto StorageAccountKey = core::PropertyDefinitionBuilder<>::createProperty("Storage Account Key")
.withDescription("The storage account key. This is an admin-like password providing access to every container in this account. "
- "It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies.")
+ "It is recommended one uses Shared Access Signature (SAS) token instead for fine-grained control with policies "
+ "if Credential Configuration Strategy is set to From Properties. If set, SAS Token must be empty.")
.supportsExpressionLanguage(true)
.isSensitive(true)
.build();
EXTENSIONAPI static constexpr auto SASToken = core::PropertyDefinitionBuilder<>::createProperty("SAS Token")
- .withDescription("Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name if Managed Identity is not used.")
+ .withDescription("Shared Access Signature token. Specify either SAS Token (recommended) or Storage Account Key together with Storage Account Name "
+ "if Credential Configuration Strategy is set to From Properties. If set, Storage Account Key must be empty.")
.supportsExpressionLanguage(true)
.isSensitive(true)
.build();
EXTENSIONAPI static constexpr auto CommonStorageAccountEndpointSuffix = core::PropertyDefinitionBuilder<>::createProperty("Common Storage Account Endpoint Suffix")
.withDescription("Storage accounts in public Azure always use a common FQDN suffix. Override this endpoint suffix with a "
- "different suffix in certain circumstances (like Azure Stack or non-public Azure regions). ")
+ "different suffix in certain circumstances (like Azure Stack or non-public Azure regions).")
.supportsExpressionLanguage(true)
.build();
EXTENSIONAPI static constexpr auto ConnectionString = core::PropertyDefinitionBuilder<>::createProperty("Connection String")
- .withDescription("Connection string used to connect to Azure Storage service. This overrides all other set credential properties if Managed Identity is not used.")
+ .withDescription("Connection string used to connect to Azure Storage service. This overrides all other set credential properties "
+ "if Credential Configuration Strategy is set to From Properties.")
.supportsExpressionLanguage(true)
.build();
- EXTENSIONAPI static constexpr auto UseManagedIdentityCredentials = core::PropertyDefinitionBuilder<>::createProperty("Use Managed Identity Credentials")
- .withDescription("If true Managed Identity credentials will be used together with the Storage Account Name for authentication.")
+ EXTENSIONAPI static constexpr auto CredentialConfigurationStrategy =
+ core::PropertyDefinitionBuilder<magic_enum::enum_count<CredentialConfigurationStrategyOption>()>::createProperty("Credential Configuration Strategy")
+ .withDescription("The strategy to use for credential configuration. If set to From Properties, the credentials are parsed from the SAS Token, Storage Account Key, "
+ "and Connection String properties. In other cases, the selected Azure identity source is used.")
.isRequired(true)
- .withValidator(core::StandardPropertyValidators::BOOLEAN_VALIDATOR)
- .withDefaultValue("false")
+ .withDefaultValue(magic_enum::enum_name(CredentialConfigurationStrategyOption::FromProperties))
+ .withAllowedValues(magic_enum::enum_names<CredentialConfigurationStrategyOption>())
+ .build();
+ EXTENSIONAPI static constexpr auto ManagedIdentityClientId = core::PropertyDefinitionBuilder<>::createProperty("Managed Identity Client ID")
+ .withDescription("Client ID of the managed identity. The property is required when User Assigned Managed Identity is used for authentication and multiple user-assigned identities "
+ "are added to the resource. It must be empty in case of System Assigned Managed Identity and can also be left empty if only one user-assigned identity is present.")
+ .isSensitive(true)
+ .supportsExpressionLanguage(true)
.build();
EXTENSIONAPI static constexpr auto Properties = utils::array_cat(AzureStorageProcessorBase::Properties, std::to_array<core::PropertyReference>({
ContainerName,
@@ -81,7 +92,8 @@ class AzureBlobStorageProcessorBase : public AzureStorageProcessorBase {
SASToken,
CommonStorageAccountEndpointSuffix,
ConnectionString,
- UseManagedIdentityCredentials
+ CredentialConfigurationStrategy,
+ ManagedIdentityClientId
}));
@@ -105,7 +117,7 @@ class AzureBlobStorageProcessorBase : public AzureStorageProcessorBase {
const core::FlowFile* const flow_file);
storage::AzureBlobStorage azure_blob_storage_;
- bool use_managed_identity_credentials_ = false;
+ CredentialConfigurationStrategyOption credential_configuration_strategy_ = CredentialConfigurationStrategyOption::FromProperties;
};
} // namespace org::apache::nifi::minifi::azure::processors
diff --git a/extensions/azure/processors/FetchAzureBlobStorage.h b/extensions/azure/processors/FetchAzureBlobStorage.h
index 3270becc4..c9e1ee601 100644
--- a/extensions/azure/processors/FetchAzureBlobStorage.h
+++ b/extensions/azure/processors/FetchAzureBlobStorage.h
@@ -48,7 +48,7 @@ class FetchAzureBlobStorage final : public AzureBlobStorageSingleBlobProcessorBa
EXTENSIONAPI static constexpr auto RangeLength = core::PropertyDefinitionBuilder<>::createProperty("Range Length")
.withDescription("The number of bytes to download from the blob, starting from the Range Start. "
- "An empty value or a value that extends beyond the end of the blob will read to the end of the blob.")
+ "An empty value or a value that extends beyond the end of the blob will read to the end of the blob.")
.supportsExpressionLanguage(true)
.build();
EXTENSIONAPI static constexpr auto Properties = utils::array_cat(AzureBlobStorageSingleBlobProcessorBase::Properties, std::to_array<core::PropertyReference>({
diff --git a/extensions/azure/processors/FetchAzureDataLakeStorage.h b/extensions/azure/processors/FetchAzureDataLakeStorage.h
index bb9c4d338..f7ab3a11d 100644
--- a/extensions/azure/processors/FetchAzureDataLakeStorage.h
+++ b/extensions/azure/processors/FetchAzureDataLakeStorage.h
@@ -42,7 +42,7 @@ class FetchAzureDataLakeStorage final : public AzureDataLakeStorageFileProcessor
.build();
EXTENSIONAPI static constexpr auto RangeLength = core::PropertyDefinitionBuilder<>::createProperty("Range Length")
.withDescription("The number of bytes to download from the object, starting from the Range Start. "
- "An empty value or a value that extends beyond the end of the object will read to the end of the object.")
+ "An empty value or a value that extends beyond the end of the object will read to the end of the object.")
.supportsExpressionLanguage(true)
.build();
EXTENSIONAPI static constexpr auto NumberOfRetries = core::PropertyDefinitionBuilder<>::createProperty("Number of Retries")
diff --git a/extensions/azure/processors/PutAzureDataLakeStorage.cpp b/extensions/azure/processors/PutAzureDataLakeStorage.cpp
index 00f4874cf..c1531de2c 100644
--- a/extensions/azure/processors/PutAzureDataLakeStorage.cpp
+++ b/extensions/azure/processors/PutAzureDataLakeStorage.cpp
@@ -36,17 +36,6 @@ void PutAzureDataLakeStorage::initialize() {
void PutAzureDataLakeStorage::onSchedule(core::ProcessContext& context, core::ProcessSessionFactory& session_factory) {
AzureDataLakeStorageFileProcessorBase::onSchedule(context, session_factory);
- std::optional<storage::AzureStorageCredentials> credentials;
- std::tie(std::ignore, credentials) = getCredentialsFromControllerService(context);
- if (!credentials) {
- throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Azure Storage Credentials Service property missing or invalid");
- }
-
- if (!credentials->isValid()) {
- throw Exception(PROCESS_SCHEDULE_EXCEPTION, "Azure Storage Credentials Service properties are not set or invalid");
- }
-
- credentials_ = *credentials;
conflict_resolution_strategy_ = utils::parseEnumProperty<azure::FileExistsResolutionStrategy>(context, ConflictResolutionStrategy);
}
@@ -123,7 +112,7 @@ int64_t PutAzureDataLakeStorage::ReadCallback::operator()(const std::shared_ptr<
}
result_ = azure_data_lake_storage_.uploadFile(params_, buffer);
- return read_ret;
+ return gsl::narrow<int64_t>(read_ret);
}
REGISTER_RESOURCE(PutAzureDataLakeStorage, Processor);
diff --git a/extensions/azure/storage/AzureBlobStorageClient.cpp b/extensions/azure/storage/AzureBlobStorageClient.cpp
index 9393008ba..be6186a7f 100644
--- a/extensions/azure/storage/AzureBlobStorageClient.cpp
+++ b/extensions/azure/storage/AzureBlobStorageClient.cpp
@@ -56,13 +56,13 @@ AzureBlobStorageClient::AzureBlobStorageClient() {
}
Azure::Storage::Blobs::BlobContainerClient AzureBlobStorageClient::createClient(const AzureStorageCredentials &credentials, const std::string &container_name) {
- if (credentials.getUseManagedIdentityCredentials()) {
- auto storage_client = Azure::Storage::Blobs::BlobServiceClient(
- "https://" + credentials.getStorageAccountName() + ".blob." + credentials.getEndpointSuffix(), std::make_shared<Azure::Identity::ManagedIdentityCredential>());
- return storage_client.GetBlobContainerClient(container_name);
- } else {
+ if (credentials.getCredentialConfigurationStrategy() == CredentialConfigurationStrategyOption::FromProperties) {
return Azure::Storage::Blobs::BlobContainerClient::CreateFromConnectionString(credentials.buildConnectionString(), container_name);
}
+
+ auto storage_client = Azure::Storage::Blobs::BlobServiceClient("https://" + credentials.getStorageAccountName() + ".blob." + credentials.getEndpointSuffix(),
+ credentials.createAzureTokenCredential());
+ return storage_client.GetBlobContainerClient(container_name);
}
bool AzureBlobStorageClient::createContainerIfNotExists(const PutAzureBlobStorageParameters& params) {
diff --git a/extensions/azure/storage/AzureDataLakeStorageClient.cpp b/extensions/azure/storage/AzureDataLakeStorageClient.cpp
index 7f588139f..d7618818e 100644
--- a/extensions/azure/storage/AzureDataLakeStorageClient.cpp
+++ b/extensions/azure/storage/AzureDataLakeStorageClient.cpp
@@ -42,14 +42,14 @@ std::unique_ptr<Azure::Storage::Files::DataLake::DataLakeFileSystemClient> Azure
options.Retry.MaxRetries = gsl::narrow<int32_t>(*number_of_retries);
}
- if (credentials.getUseManagedIdentityCredentials()) {
- auto datalake_service_client = Azure::Storage::Files::DataLake::DataLakeServiceClient(
- "https://" + credentials.getStorageAccountName() + ".dfs." + credentials.getEndpointSuffix(), std::make_shared<Azure::Identity::ManagedIdentityCredential>(), options);
- return std::make_unique<Azure::Storage::Files::DataLake::DataLakeFileSystemClient>(datalake_service_client.GetFileSystemClient(file_system_name));
- } else {
+ if (credentials.getCredentialConfigurationStrategy() == CredentialConfigurationStrategyOption::FromProperties) {
return std::make_unique<Azure::Storage::Files::DataLake::DataLakeFileSystemClient>(
Azure::Storage::Files::DataLake::DataLakeFileSystemClient::CreateFromConnectionString(credentials.buildConnectionString(), file_system_name, options));
}
+
+ auto datalake_service_client = Azure::Storage::Files::DataLake::DataLakeServiceClient(
+ "https://" + credentials.getStorageAccountName() + ".dfs." + credentials.getEndpointSuffix(), credentials.createAzureTokenCredential(), options);
+ return std::make_unique<Azure::Storage::Files::DataLake::DataLakeFileSystemClient>(datalake_service_client.GetFileSystemClient(file_system_name));
}
Azure::Storage::Files::DataLake::DataLakeDirectoryClient AzureDataLakeStorageClient::getDirectoryClient(const AzureDataLakeStorageParameters& params) {
diff --git a/extensions/azure/storage/AzureStorageCredentials.cpp b/extensions/azure/storage/AzureStorageCredentials.cpp
index 070dfe860..7af832d22 100644
--- a/extensions/azure/storage/AzureStorageCredentials.cpp
+++ b/extensions/azure/storage/AzureStorageCredentials.cpp
@@ -34,7 +34,7 @@ void AzureStorageCredentials::setSasToken(const std::string& sas_token) {
sas_token_ = sas_token;
}
-void AzureStorageCredentials::setEndpontSuffix(const std::string& endpoint_suffix) {
+void AzureStorageCredentials::setEndpointSuffix(const std::string& endpoint_suffix) {
endpoint_suffix_ = endpoint_suffix;
}
@@ -42,8 +42,12 @@ void AzureStorageCredentials::setConnectionString(const std::string& connection_
connection_string_ = connection_string;
}
-void AzureStorageCredentials::setUseManagedIdentityCredentials(bool use_managed_identity_credentials) {
- use_managed_identity_credentials_ = use_managed_identity_credentials;
+void AzureStorageCredentials::setCredentialConfigurationStrategy(CredentialConfigurationStrategyOption credential_configuration_strategy) {
+ credential_configuration_strategy_ = credential_configuration_strategy;
+}
+
+void AzureStorageCredentials::setManagedIdentityClientId(const std::string& managed_identity_client_id) {
+ managed_identity_client_id_ = managed_identity_client_id;
}
std::string AzureStorageCredentials::getStorageAccountName() const {
@@ -54,12 +58,16 @@ std::string AzureStorageCredentials::getEndpointSuffix() const {
return endpoint_suffix_.empty() ? "core.windows.net" : endpoint_suffix_;
}
-bool AzureStorageCredentials::getUseManagedIdentityCredentials() const {
- return use_managed_identity_credentials_;
+CredentialConfigurationStrategyOption AzureStorageCredentials::getCredentialConfigurationStrategy() const {
+ return credential_configuration_strategy_;
+}
+
+std::string AzureStorageCredentials::getManagedIdentityClientId() const {
+ return managed_identity_client_id_;
}
std::string AzureStorageCredentials::buildConnectionString() const {
- if (use_managed_identity_credentials_) {
+ if (credential_configuration_strategy_ != CredentialConfigurationStrategyOption::FromProperties) {
return "";
}
@@ -67,6 +75,10 @@ std::string AzureStorageCredentials::buildConnectionString() const {
return connection_string_;
}
+ if (!storage_account_key_.empty() && !sas_token_.empty()) {
+ return "";
+ }
+
if (storage_account_name_.empty() || (storage_account_key_.empty() && sas_token_.empty())) {
return "";
}
@@ -90,16 +102,35 @@ std::string AzureStorageCredentials::buildConnectionString() const {
}
bool AzureStorageCredentials::isValid() const {
- return (getUseManagedIdentityCredentials() && !getStorageAccountName().empty()) ||
- (!getUseManagedIdentityCredentials() && !buildConnectionString().empty());
+ return (credential_configuration_strategy_ != CredentialConfigurationStrategyOption::FromProperties && !getStorageAccountName().empty()) ||
+ (credential_configuration_strategy_ == CredentialConfigurationStrategyOption::FromProperties && !buildConnectionString().empty());
+}
+
+std::shared_ptr<Azure::Core::Credentials::TokenCredential> AzureStorageCredentials::createAzureTokenCredential() const {
+ std::shared_ptr<Azure::Core::Credentials::TokenCredential> credential;
+ if (credential_configuration_strategy_ == CredentialConfigurationStrategyOption::ManagedIdentity) {
+ Azure::Identity::ManagedIdentityCredentialOptions options;
+ if (managed_identity_client_id_.empty()) {
+ options.IdentityId = Azure::Identity::ManagedIdentityId::SystemAssigned();
+ } else {
+ options.IdentityId = Azure::Identity::ManagedIdentityId::FromUserAssignedClientId(managed_identity_client_id_);
+ }
+ credential = std::make_shared<Azure::Identity::ManagedIdentityCredential>(options);
+ } else if (credential_configuration_strategy_ == CredentialConfigurationStrategyOption::DefaultCredential) {
+ credential = std::make_shared<Azure::Identity::DefaultAzureCredential>();
+ } else if (credential_configuration_strategy_ == CredentialConfigurationStrategyOption::WorkloadIdentity) {
+ credential = std::make_shared<Azure::Identity::WorkloadIdentityCredential>();
+ }
+
+ return credential;
}
bool AzureStorageCredentials::operator==(const AzureStorageCredentials& other) const {
- if (other.use_managed_identity_credentials_ != use_managed_identity_credentials_) {
+ if (other.credential_configuration_strategy_ != credential_configuration_strategy_) {
return false;
}
- if (use_managed_identity_credentials_) {
+ if (credential_configuration_strategy_ != CredentialConfigurationStrategyOption::FromProperties) {
return storage_account_name_ == other.storage_account_name_ && endpoint_suffix_ == other.endpoint_suffix_;
} else {
return buildConnectionString() == other.buildConnectionString();
diff --git a/extensions/azure/storage/AzureStorageCredentials.h b/extensions/azure/storage/AzureStorageCredentials.h
index ea14d2fb8..b156b5361 100644
--- a/extensions/azure/storage/AzureStorageCredentials.h
+++ b/extensions/azure/storage/AzureStorageCredentials.h
@@ -20,6 +20,10 @@
#pragma once
#include <string>
+#include <memory>
+
+#include "utils/AzureEnums.h"
+#include "azure/identity.hpp"
namespace org::apache::nifi::minifi::azure::storage {
@@ -28,16 +32,20 @@ class AzureStorageCredentials {
void setStorageAccountName(const std::string& storage_account_name);
void setStorageAccountKey(const std::string& storage_account_key);
void setSasToken(const std::string& sas_token);
- void setEndpontSuffix(const std::string& endpoint_suffix);
+ void setEndpointSuffix(const std::string& endpoint_suffix);
void setConnectionString(const std::string& connection_string);
- void setUseManagedIdentityCredentials(bool use_managed_identity_credentials);
+ void setCredentialConfigurationStrategy(CredentialConfigurationStrategyOption credential_configuration_strategy);
+ void setManagedIdentityClientId(const std::string& managed_identity_client_id);
std::string getStorageAccountName() const;
std::string getEndpointSuffix() const;
- bool getUseManagedIdentityCredentials() const;
+ CredentialConfigurationStrategyOption getCredentialConfigurationStrategy() const;
+ std::string getManagedIdentityClientId() const;
std::string buildConnectionString() const;
bool isValid() const;
+ std::shared_ptr<Azure::Core::Credentials::TokenCredential> createAzureTokenCredential() const;
+
bool operator==(const AzureStorageCredentials& other) const;
private:
@@ -46,7 +54,8 @@ class AzureStorageCredentials {
std::string sas_token_;
std::string endpoint_suffix_;
std::string connection_string_;
- bool use_managed_identity_credentials_ = false;
+ std::string managed_identity_client_id_;
+ CredentialConfigurationStrategyOption credential_configuration_strategy_ = CredentialConfigurationStrategyOption::FromProperties;
};
} // namespace org::apache::nifi::minifi::azure::storage
diff --git a/extensions/azure/tests/DeleteAzureBlobStorageTests.cpp b/extensions/azure/tests/DeleteAzureBlobStorageTests.cpp
index 7c7d790fd..b554021bb 100644
--- a/extensions/azure/tests/DeleteAzureBlobStorageTests.cpp
+++ b/extensions/azure/tests/DeleteAzureBlobStorageTests.cpp
@@ -134,23 +134,61 @@ TEST_CASE_METHOD(DeleteAzureBlobStorageTestsFixture, "Test credentials settings"
REQUIRE(failed_flowfiles[0] == TEST_DATA);
}
- SECTION("Account name and managed identity are used in properties") {
+ SECTION("Account name and Azure default identity sources are used in properties") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
plan_->setProperty(azure_blob_storage_processor_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(azure_blob_storage_processor_, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(azure_blob_storage_processor_, "Credential Configuration Strategy", credential_configuration_strategy_string);
+ plan_->setProperty(azure_blob_storage_processor_, "Managed Identity Client ID", managed_identity_client_id);
test_controller_.runSession(plan_, true);
CHECK(getFailedFlowFileContents().empty());
auto passed_params = mock_blob_storage_ptr_->getPassedDeleteParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
- SECTION("Account name and managed identity are used from Azure Storage Credentials Service") {
+ SECTION("Account name and Azure default identity sources are used from Azure Storage Credentials Service") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(azure_storage_cred_service, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(azure_storage_cred_service, "Credential Configuration Strategy", credential_configuration_strategy_string);
plan_->setProperty(azure_storage_cred_service, "Common Storage Account Endpoint Suffix", "core.chinacloudapi.cn");
+ plan_->setProperty(azure_storage_cred_service, "Managed Identity Client ID", managed_identity_client_id);
plan_->setProperty(azure_blob_storage_processor_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
test_controller_.runSession(plan_, true);
CHECK(getFailedFlowFileContents().empty());
@@ -158,6 +196,8 @@ TEST_CASE_METHOD(DeleteAzureBlobStorageTestsFixture, "Test credentials settings"
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.chinacloudapi.cn");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
@@ -209,6 +249,32 @@ TEST_CASE_METHOD(DeleteAzureBlobStorageTestsFixture, "Test credentials settings"
REQUIRE(failed_flowfiles.size() == 1);
REQUIRE(failed_flowfiles[0] == TEST_DATA);
}
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(azure_storage_cred_service, "SAS Token", SAS_TOKEN);
+ plan_->setProperty(azure_blob_storage_processor_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
+ test_controller_.runSession(plan_, true);
+ auto passed_params = mock_blob_storage_ptr_->getPassedDeleteParams();
+ REQUIRE(passed_params.credentials.buildConnectionString().empty());
+ auto failed_flowfiles = getFailedFlowFileContents();
+ REQUIRE(failed_flowfiles.size() == 1);
+ REQUIRE(failed_flowfiles[0] == TEST_DATA);
+ }
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in properties") {
+ plan_->setProperty(azure_blob_storage_processor_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(azure_blob_storage_processor_, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(azure_blob_storage_processor_, "SAS Token", SAS_TOKEN);
+ test_controller_.runSession(plan_, true);
+ auto passed_params = mock_blob_storage_ptr_->getPassedDeleteParams();
+ REQUIRE(passed_params.credentials.buildConnectionString().empty());
+ auto failed_flowfiles = getFailedFlowFileContents();
+ REQUIRE(failed_flowfiles.size() == 1);
+ REQUIRE(failed_flowfiles[0] == TEST_DATA);
+ }
}
TEST_CASE_METHOD(DeleteAzureBlobStorageTestsFixture, "Test Azure blob delete failure in case Blob is not set and filename is empty", "[azureBlobStorageDelete]") {
diff --git a/extensions/azure/tests/DeleteAzureDataLakeStorageTests.cpp b/extensions/azure/tests/DeleteAzureDataLakeStorageTests.cpp
index 40bacdca5..a241429c2 100644
--- a/extensions/azure/tests/DeleteAzureDataLakeStorageTests.cpp
+++ b/extensions/azure/tests/DeleteAzureDataLakeStorageTests.cpp
@@ -54,19 +54,47 @@ TEST_CASE_METHOD(DeleteAzureDataLakeStorageTestsFixture, "Test Azure credentials
CHECK(getFailedFlowFileContents().empty());
}
-TEST_CASE_METHOD(DeleteAzureDataLakeStorageTestsFixture, "Test Azure credentials with managed identity use", "[azureDataLakeStorageParameters]") {
+TEST_CASE_METHOD(DeleteAzureDataLakeStorageTestsFixture, "Test Azure credentials with Azure default identity sources", "[azureDataLakeStorageParameters]") {
setDefaultProperties();
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "test");
- plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::UseManagedIdentityCredentials, "true");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::CredentialConfigurationStrategy, credential_configuration_strategy_string);
plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ManagedIdentityClientId, managed_identity_client_id);
test_controller_.runSession(plan_, true);
auto passed_params = mock_data_lake_storage_client_ptr_->getPassedDeleteParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == "TEST_ACCOUNT");
CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(getFailedFlowFileContents().empty());
}
+TEST_CASE_METHOD(DeleteAzureDataLakeStorageTestsFixture, "Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ setDefaultProperties();
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::SASToken, "token");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountKey, "TEST_KEY");
+ REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
+}
+
TEST_CASE_METHOD(DeleteAzureDataLakeStorageTestsFixture, "Filesystem name is not set", "[azureDataLakeStorageParameters]") {
plan_->setDynamicProperty(update_attribute_, "test.filesystemname", "");
test_controller_.runSession(plan_, true);
diff --git a/extensions/azure/tests/FetchAzureBlobStorageTests.cpp b/extensions/azure/tests/FetchAzureBlobStorageTests.cpp
index a1e901744..cd57961cb 100644
--- a/extensions/azure/tests/FetchAzureBlobStorageTests.cpp
+++ b/extensions/azure/tests/FetchAzureBlobStorageTests.cpp
@@ -130,23 +130,61 @@ TEST_CASE_METHOD(FetchAzureBlobStorageTestsFixture, "Test credentials settings",
REQUIRE(failed_flowfiles[0] == TEST_DATA);
}
- SECTION("Account name and managed identity are used in properties") {
+ SECTION("Account name and Azure default identity sources are used in properties") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
plan_->setProperty(azure_blob_storage_processor_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(azure_blob_storage_processor_, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(azure_blob_storage_processor_, "Credential Configuration Strategy", credential_configuration_strategy_string);
+ plan_->setProperty(azure_blob_storage_processor_, "Managed Identity Client ID", managed_identity_client_id);
test_controller_.runSession(plan_, true);
CHECK(getFailedFlowFileContents().empty());
auto passed_params = mock_blob_storage_ptr_->getPassedFetchParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
- SECTION("Account name and managed identity are used from Azure Storage Credentials Service") {
+ SECTION("Account name and Azure default identity sources are used from Azure Storage Credentials Service") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(azure_storage_cred_service, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(azure_storage_cred_service, "Credential Configuration Strategy", credential_configuration_strategy_string);
plan_->setProperty(azure_storage_cred_service, "Common Storage Account Endpoint Suffix", "core.chinacloudapi.cn");
+ plan_->setProperty(azure_storage_cred_service, "Managed Identity Client ID", managed_identity_client_id);
plan_->setProperty(azure_blob_storage_processor_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
test_controller_.runSession(plan_, true);
CHECK(getFailedFlowFileContents().empty());
@@ -154,6 +192,8 @@ TEST_CASE_METHOD(FetchAzureBlobStorageTestsFixture, "Test credentials settings",
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.chinacloudapi.cn");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
@@ -205,6 +245,32 @@ TEST_CASE_METHOD(FetchAzureBlobStorageTestsFixture, "Test credentials settings",
REQUIRE(failed_flowfiles.size() == 1);
REQUIRE(failed_flowfiles[0] == TEST_DATA);
}
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(azure_storage_cred_service, "SAS Token", SAS_TOKEN);
+ plan_->setProperty(azure_blob_storage_processor_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
+ test_controller_.runSession(plan_, true);
+ auto passed_params = mock_blob_storage_ptr_->getPassedFetchParams();
+ REQUIRE(passed_params.credentials.buildConnectionString().empty());
+ auto failed_flowfiles = getFailedFlowFileContents();
+ REQUIRE(failed_flowfiles.size() == 1);
+ REQUIRE(failed_flowfiles[0] == TEST_DATA);
+ }
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in properties") {
+ plan_->setProperty(azure_blob_storage_processor_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(azure_blob_storage_processor_, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(azure_blob_storage_processor_, "SAS Token", SAS_TOKEN);
+ test_controller_.runSession(plan_, true);
+ auto passed_params = mock_blob_storage_ptr_->getPassedFetchParams();
+ REQUIRE(passed_params.credentials.buildConnectionString().empty());
+ auto failed_flowfiles = getFailedFlowFileContents();
+ REQUIRE(failed_flowfiles.size() == 1);
+ REQUIRE(failed_flowfiles[0] == TEST_DATA);
+ }
}
TEST_CASE_METHOD(FetchAzureBlobStorageTestsFixture, "Test Azure blob fetch failure in case Blob is not set and filename is empty", "[azureBlobStorageFetch]") {
diff --git a/extensions/azure/tests/FetchAzureDataLakeStorageTests.cpp b/extensions/azure/tests/FetchAzureDataLakeStorageTests.cpp
index 70d63bc6d..c5505f49e 100644
--- a/extensions/azure/tests/FetchAzureDataLakeStorageTests.cpp
+++ b/extensions/azure/tests/FetchAzureDataLakeStorageTests.cpp
@@ -54,19 +54,47 @@ TEST_CASE_METHOD(FetchAzureDataLakeStorageTestsFixture, "Test Azure credentials
CHECK(getFailedFlowFileContents().empty());
}
-TEST_CASE_METHOD(FetchAzureDataLakeStorageTestsFixture, "Test Azure credentials with managed identity use", "[azureDataLakeStorageParameters]") {
+TEST_CASE_METHOD(FetchAzureDataLakeStorageTestsFixture, "Test Azure credentials with Azure default identity sources", "[azureDataLakeStorageParameters]") {
setDefaultProperties();
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "test");
- plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::UseManagedIdentityCredentials, "true");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::CredentialConfigurationStrategy, credential_configuration_strategy_string);
plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ManagedIdentityClientId, managed_identity_client_id);
test_controller_.runSession(plan_, true);
auto passed_params = mock_data_lake_storage_client_ptr_->getPassedFetchParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == "TEST_ACCOUNT");
CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(getFailedFlowFileContents().empty());
}
+TEST_CASE_METHOD(FetchAzureDataLakeStorageTestsFixture, "Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ setDefaultProperties();
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::SASToken, "token");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountKey, "TEST_KEY");
+ REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
+}
+
TEST_CASE_METHOD(FetchAzureDataLakeStorageTestsFixture, "Filesystem name is not set", "[azureDataLakeStorageParameters]") {
plan_->setDynamicProperty(update_attribute_, "test.filesystemname", "");
test_controller_.runSession(plan_, true);
diff --git a/extensions/azure/tests/ListAzureBlobStorageTests.cpp b/extensions/azure/tests/ListAzureBlobStorageTests.cpp
index 2717469ec..31bdad909 100644
--- a/extensions/azure/tests/ListAzureBlobStorageTests.cpp
+++ b/extensions/azure/tests/ListAzureBlobStorageTests.cpp
@@ -168,28 +168,68 @@ TEST_CASE_METHOD(ListAzureBlobStorageTestsFixture, "Test credentials settings",
REQUIRE(passed_params.credentials.buildConnectionString() == CONNECTION_STRING);
}
- SECTION("Account name and managed identity are used in properties") {
+ SECTION("Account name and Azure default identity sources are used in properties") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
plan_->setProperty(list_azure_blob_storage_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(list_azure_blob_storage_, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(list_azure_blob_storage_, "Credential Configuration Strategy", credential_configuration_strategy_string);
+ plan_->setProperty(list_azure_blob_storage_, "Managed Identity Client ID", managed_identity_client_id);
test_controller_.runSession(plan_, true);
auto passed_params = mock_blob_storage_ptr_->getPassedListParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
- SECTION("Account name and managed identity are used from Azure Storage Credentials Service") {
+ SECTION("Account name and Azure default identity sources are used from Azure Storage Credentials Service") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(azure_storage_cred_service, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(azure_storage_cred_service, "Credential Configuration Strategy", credential_configuration_strategy_string);
plan_->setProperty(azure_storage_cred_service, "Common Storage Account Endpoint Suffix", "core.chinacloudapi.cn");
+ plan_->setProperty(azure_storage_cred_service, "Managed Identity Client ID", managed_identity_client_id);
plan_->setProperty(list_azure_blob_storage_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
test_controller_.runSession(plan_, true);
auto passed_params = mock_blob_storage_ptr_->getPassedListParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.chinacloudapi.cn");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
@@ -224,6 +264,22 @@ TEST_CASE_METHOD(ListAzureBlobStorageTestsFixture, "Test credentials settings",
plan_->setProperty(list_azure_blob_storage_, "Storage Account Key", STORAGE_ACCOUNT_KEY);
REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
}
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(azure_storage_cred_service, "SAS Token", SAS_TOKEN);
+ plan_->setProperty(list_azure_blob_storage_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
+ REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
+ }
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in properties") {
+ plan_->setProperty(list_azure_blob_storage_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(list_azure_blob_storage_, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(list_azure_blob_storage_, "SAS Token", SAS_TOKEN);
+ REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
+ }
}
TEST_CASE_METHOD(ListAzureBlobStorageTestsFixture, "List all files every time", "[ListAzureBlobStorage]") {
diff --git a/extensions/azure/tests/ListAzureDataLakeStorageTests.cpp b/extensions/azure/tests/ListAzureDataLakeStorageTests.cpp
index 4cc0fa5c7..4f2a19b51 100644
--- a/extensions/azure/tests/ListAzureDataLakeStorageTests.cpp
+++ b/extensions/azure/tests/ListAzureDataLakeStorageTests.cpp
@@ -43,7 +43,7 @@ class ListAzureDataLakeStorageTestsFixture {
auto mock_data_lake_storage_client = std::make_unique<MockDataLakeStorageClient>();
mock_data_lake_storage_client_ptr_ = mock_data_lake_storage_client.get();
auto uuid = utils::IdGenerator::getIdGenerator()->generate();
- auto impl = std::unique_ptr<minifi::azure::processors::ListAzureDataLakeStorage>(
+ auto impl = std::unique_ptr<minifi::azure::processors::ListAzureDataLakeStorage>( // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
new minifi::azure::processors::ListAzureDataLakeStorage({
.uuid = uuid, .name = "ListAzureDataLakeStorage",
.logger = logging::LoggerFactory<minifi::azure::processors::ListAzureDataLakeStorage>::getLogger(uuid)}, std::move(mock_data_lake_storage_client)));
@@ -216,4 +216,44 @@ TEST_CASE_METHOD(ListAzureDataLakeStorageTestsFixture, "Throw on invalid path fi
REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
}
+TEST_CASE_METHOD(ListAzureDataLakeStorageTestsFixture, "Test Azure credentials with Azure default identity sources", "[azureDataLakeStorageParameters]") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "test");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::CredentialConfigurationStrategy, credential_configuration_strategy_string);
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ManagedIdentityClientId, managed_identity_client_id);
+ test_controller_.runSession(plan_, true);
+ auto passed_params = mock_data_lake_storage_client_ptr_->getPassedListParams();
+ CHECK(passed_params.credentials.buildConnectionString().empty());
+ CHECK(passed_params.credentials.getStorageAccountName() == "TEST_ACCOUNT");
+ CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
+}
+
+TEST_CASE_METHOD(ListAzureDataLakeStorageTestsFixture, "Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ setDefaultProperties();
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::SASToken, "token");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountKey, "TEST_KEY");
+ REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
+}
+
} // namespace
diff --git a/extensions/azure/tests/PutAzureBlobStorageTests.cpp b/extensions/azure/tests/PutAzureBlobStorageTests.cpp
index 1b4e6cc7b..a4a0ed19e 100644
--- a/extensions/azure/tests/PutAzureBlobStorageTests.cpp
+++ b/extensions/azure/tests/PutAzureBlobStorageTests.cpp
@@ -134,23 +134,61 @@ TEST_CASE_METHOD(PutAzureBlobStorageTestsFixture, "Test credentials settings", "
REQUIRE(failed_flowfiles[0] == TEST_DATA);
}
- SECTION("Account name and managed identity are used in properties") {
+ SECTION("Account name and Azure default identity sources are used in properties") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
plan_->setProperty(azure_blob_storage_processor_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(azure_blob_storage_processor_, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(azure_blob_storage_processor_, "Credential Configuration Strategy", credential_configuration_strategy_string);
+ plan_->setProperty(azure_blob_storage_processor_, "Managed Identity Client ID", managed_identity_client_id);
test_controller_.runSession(plan_, true);
CHECK(getFailedFlowFileContents().empty());
auto passed_params = mock_blob_storage_ptr_->getPassedPutParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
- SECTION("Account name and managed identity are used from Azure Storage Credentials Service") {
+ SECTION("Account name and Azure default identity sources are used from Azure Storage Credentials Service") {
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
+
auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
- plan_->setProperty(azure_storage_cred_service, "Use Managed Identity Credentials", "true");
+ plan_->setProperty(azure_storage_cred_service, "Credential Configuration Strategy", credential_configuration_strategy_string);
plan_->setProperty(azure_storage_cred_service, "Common Storage Account Endpoint Suffix", "core.chinacloudapi.cn");
+ plan_->setProperty(azure_storage_cred_service, "Managed Identity Client ID", managed_identity_client_id);
plan_->setProperty(azure_blob_storage_processor_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
test_controller_.runSession(plan_, true);
CHECK(getFailedFlowFileContents().empty());
@@ -158,6 +196,8 @@ TEST_CASE_METHOD(PutAzureBlobStorageTestsFixture, "Test credentials settings", "
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == STORAGE_ACCOUNT_NAME);
CHECK(passed_params.credentials.getEndpointSuffix() == "core.chinacloudapi.cn");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
CHECK(passed_params.container_name == CONTAINER_NAME);
}
@@ -209,6 +249,32 @@ TEST_CASE_METHOD(PutAzureBlobStorageTestsFixture, "Test credentials settings", "
REQUIRE(failed_flowfiles.size() == 1);
REQUIRE(failed_flowfiles[0] == TEST_DATA);
}
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ auto azure_storage_cred_service = plan_->addController("AzureStorageCredentialsService", "AzureStorageCredentialsService");
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(azure_storage_cred_service, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(azure_storage_cred_service, "SAS Token", SAS_TOKEN);
+ plan_->setProperty(azure_blob_storage_processor_, "Azure Storage Credentials Service", "AzureStorageCredentialsService");
+ test_controller_.runSession(plan_, true);
+ auto passed_params = mock_blob_storage_ptr_->getPassedPutParams();
+ REQUIRE(passed_params.credentials.buildConnectionString().empty());
+ auto failed_flowfiles = getFailedFlowFileContents();
+ REQUIRE(failed_flowfiles.size() == 1);
+ REQUIRE(failed_flowfiles[0] == TEST_DATA);
+ }
+
+ SECTION("Both SAS Token and Storage Account Key cannot be set in properties") {
+ plan_->setProperty(azure_blob_storage_processor_, "Storage Account Name", STORAGE_ACCOUNT_NAME);
+ plan_->setProperty(azure_blob_storage_processor_, "Storage Account Key", STORAGE_ACCOUNT_KEY);
+ plan_->setProperty(azure_blob_storage_processor_, "SAS Token", SAS_TOKEN);
+ test_controller_.runSession(plan_, true);
+ auto passed_params = mock_blob_storage_ptr_->getPassedPutParams();
+ REQUIRE(passed_params.credentials.buildConnectionString().empty());
+ auto failed_flowfiles = getFailedFlowFileContents();
+ REQUIRE(failed_flowfiles.size() == 1);
+ REQUIRE(failed_flowfiles[0] == TEST_DATA);
+ }
}
TEST_CASE_METHOD(PutAzureBlobStorageTestsFixture, "Test Azure blob upload failure in case Blob is not set and filename is empty", "[azureBlobStorageUpload]") {
diff --git a/extensions/azure/tests/PutAzureDataLakeStorageTests.cpp b/extensions/azure/tests/PutAzureDataLakeStorageTests.cpp
index 9ea94222d..6938dc841 100644
--- a/extensions/azure/tests/PutAzureDataLakeStorageTests.cpp
+++ b/extensions/azure/tests/PutAzureDataLakeStorageTests.cpp
@@ -54,19 +54,47 @@ TEST_CASE_METHOD(PutAzureDataLakeStorageTestsFixture, "Test Azure credentials wi
REQUIRE(getFailedFlowFileContents().empty());
}
-TEST_CASE_METHOD(PutAzureDataLakeStorageTestsFixture, "Test Azure credentials with managed identity use", "[azureDataLakeStorageParameters]") {
+TEST_CASE_METHOD(PutAzureDataLakeStorageTestsFixture, "Test Azure credentials with Azure default identity sources", "[azureDataLakeStorageParameters]") {
setDefaultProperties();
+ minifi::azure::CredentialConfigurationStrategyOption expected_configuration_strategy_option{};
+ std::string credential_configuration_strategy_string;
+ std::string managed_identity_client_id;
+ SECTION("Managed Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::ManagedIdentity;
+ credential_configuration_strategy_string = "Managed Identity";
+ managed_identity_client_id = "test-managed-identity-client-id";
+ }
+ SECTION("Default Credential") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::DefaultCredential;
+ credential_configuration_strategy_string = "Default Credential";
+ }
+ SECTION("Workload Identity") {
+ expected_configuration_strategy_option = minifi::azure::CredentialConfigurationStrategyOption::WorkloadIdentity;
+ credential_configuration_strategy_string = "Workload Identity";
+ }
plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "test");
- plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::UseManagedIdentityCredentials, "true");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::CredentialConfigurationStrategy, credential_configuration_strategy_string);
plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ManagedIdentityClientId, managed_identity_client_id);
test_controller_.runSession(plan_, true);
auto passed_params = mock_data_lake_storage_client_ptr_->getPassedPutParams();
CHECK(passed_params.credentials.buildConnectionString().empty());
CHECK(passed_params.credentials.getStorageAccountName() == "TEST_ACCOUNT");
CHECK(passed_params.credentials.getEndpointSuffix() == "core.windows.net");
+ CHECK(passed_params.credentials.getCredentialConfigurationStrategy() == expected_configuration_strategy_option);
+ CHECK(passed_params.credentials.getManagedIdentityClientId() == managed_identity_client_id);
REQUIRE(getFailedFlowFileContents().empty());
}
+TEST_CASE_METHOD(PutAzureDataLakeStorageTestsFixture, "Both SAS Token and Storage Account Key cannot be set in credentials service") {
+ setDefaultProperties();
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::ConnectionString, "");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::SASToken, "token");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountName, "TEST_ACCOUNT");
+ plan_->setProperty(azure_storage_cred_service_, minifi::azure::controllers::AzureStorageCredentialsService::StorageAccountKey, "TEST_KEY");
+ REQUIRE_THROWS_AS(test_controller_.runSession(plan_, true), minifi::Exception);
+}
+
TEST_CASE_METHOD(PutAzureDataLakeStorageTestsFixture, "Filesystem name is not set", "[azureDataLakeStorageParameters]") {
plan_->setDynamicProperty(update_attribute_, "test.filesystemname", "");
test_controller_.runSession(plan_, true);
diff --git a/extensions/azure/utils/AzureEnums.h b/extensions/azure/utils/AzureEnums.h
index 28a54535b..ab87836e1 100644
--- a/extensions/azure/utils/AzureEnums.h
+++ b/extensions/azure/utils/AzureEnums.h
@@ -19,6 +19,8 @@
*/
#pragma once
+#include "magic_enum.hpp"
+
namespace org::apache::nifi::minifi::azure {
enum class EntityTracking {
@@ -26,4 +28,30 @@ enum class EntityTracking {
timestamps
};
+enum class CredentialConfigurationStrategyOption {
+ FromProperties,
+ DefaultCredential,
+ ManagedIdentity,
+ WorkloadIdentity
+};
+
} // namespace org::apache::nifi::minifi::azure
+
+namespace magic_enum::customize {
+using CredentialConfigurationStrategyOption = org::apache::nifi::minifi::azure::CredentialConfigurationStrategyOption;
+
+template <>
+constexpr customize_t enum_name<CredentialConfigurationStrategyOption>(CredentialConfigurationStrategyOption value) noexcept {
+ switch (value) {
+ case CredentialConfigurationStrategyOption::FromProperties:
+ return "From Properties";
+ case CredentialConfigurationStrategyOption::DefaultCredential:
+ return "Default Credential";
+ case CredentialConfigurationStrategyOption::ManagedIdentity:
+ return "Managed Identity";
+ case CredentialConfigurationStrategyOption::WorkloadIdentity:
+ return "Workload Identity";
+ }
+ return invalid_tag;
+}
+} // namespace magic_enum::customize