bakaid commented on a change in pull request #629: URL: https://github.com/apache/nifi-minifi-cpp/pull/629#discussion_r412963415
########## File path: extensions/openwsman/processors/SourceInitiatedSubscriptionListener.cpp ########## @@ -0,0 +1,918 @@ +/** + * + * 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 "SourceInitiatedSubscriptionListener.h" + +#include <memory> +#include <algorithm> +#include <cctype> +#include <cstdint> +#include <cstring> +#include <iostream> +#include <iterator> +#include <limits> +#include <map> +#include <set> +#include <string> +#include <utility> +#include <vector> + +#include <openssl/x509.h> +extern "C" { +#include "wsman-api.h" +#include "wsman-xml-api.h" +#include "wsman-xml-serialize.h" +#include "wsman-xml-serializer.h" +#include "wsman-soap.h" +#include "wsman-soap-envelope.h" +} + +#include "utils/ByteArrayCallback.h" +#include "core/FlowFile.h" +#include "core/logging/Logger.h" +#include "core/ProcessContext.h" +#include "core/Relationship.h" +#include "io/DataStream.h" +#include "io/StreamFactory.h" +#include "ResourceClaim.h" +#include "utils/StringUtils.h" +#include "utils/ScopeGuard.h" +#include "utils/file/FileUtils.h" + +#define XML_NS_CUSTOM_SUBSCRIPTION "http://schemas.microsoft.com/wbem/wsman/1/subscription" +#define XML_NS_CUSTOM_AUTHENTICATION "http://schemas.microsoft.com/wbem/wsman/1/authentication" +#define XML_NS_CUSTOM_POLICY "http://schemas.xmlsoap.org/ws/2002/12/policy" +#define XML_NS_CUSTOM_MACHINEID "http://schemas.microsoft.com/wbem/wsman/1/machineid" +#define WSMAN_CUSTOM_ACTION_ACK "http://schemas.dmtf.org/wbem/wsman/1/wsman/Ack" +#define WSMAN_CUSTOM_ACTION_HEARTBEAT "http://schemas.dmtf.org/wbem/wsman/1/wsman/Heartbeat" +#define WSMAN_CUSTOM_ACTION_EVENTS "http://schemas.dmtf.org/wbem/wsman/1/wsman/Events" + +namespace org { +namespace apache { +namespace nifi { +namespace minifi { +namespace processors { +core::Property SourceInitiatedSubscriptionListener::ListenHostname( + core::PropertyBuilder::createProperty("Listen Hostname")->withDescription("The hostname or IP of this machine that will be advertised to event sources to connect to. " + "It must be contained as a Subject Alternative Name in the server certificate, " + "otherwise source machines will refuse to connect.") + ->isRequired(true)->build()); +core::Property SourceInitiatedSubscriptionListener::ListenPort( + core::PropertyBuilder::createProperty("Listen Port")->withDescription("The port to listen on.") + ->isRequired(true)->withDefaultValue<int64_t>(5986, core::StandardValidators::LISTEN_PORT_VALIDATOR())->build()); +core::Property SourceInitiatedSubscriptionListener::SubscriptionManagerPath( + core::PropertyBuilder::createProperty("Subscription Manager Path")->withDescription("The URI path that will be used for the WEC Subscription Manager endpoint.") + ->isRequired(true)->withDefaultValue("/wsman/SubscriptionManager/WEC")->build()); +core::Property SourceInitiatedSubscriptionListener::SubscriptionsBasePath( + core::PropertyBuilder::createProperty("Subscriptions Base Path")->withDescription("The URI path that will be used as the base for endpoints serving individual subscriptions.") + ->isRequired(true)->withDefaultValue("/wsman/subscriptions")->build()); +core::Property SourceInitiatedSubscriptionListener::SSLCertificate( + core::PropertyBuilder::createProperty("SSL Certificate")->withDescription("File containing PEM-formatted file including TLS/SSL certificate and key. " + "The root CA of the certificate must be the CA set in SSL Certificate Authority.") + ->isRequired(true)->build()); +core::Property SourceInitiatedSubscriptionListener::SSLCertificateAuthority( + core::PropertyBuilder::createProperty("SSL Certificate Authority")->withDescription("File containing the PEM-formatted CA that is the root CA for both this server's certificate " + "and the event source clients' certificates.") + ->isRequired(true)->build()); +core::Property SourceInitiatedSubscriptionListener::SSLVerifyPeer( + core::PropertyBuilder::createProperty("SSL Verify Peer")->withDescription("Whether or not to verify the client's certificate") + ->isRequired(false)->withDefaultValue<bool>(true)->build()); +core::Property SourceInitiatedSubscriptionListener::XPathXmlQuery( + core::PropertyBuilder::createProperty("XPath XML Query")->withDescription("An XPath Query in structured XML format conforming to the Query Schema described in " + "https://docs.microsoft.com/en-gb/windows/win32/wes/queryschema-schema, " + "see an example here: https://docs.microsoft.com/en-gb/windows/win32/wes/consuming-events") + ->isRequired(true) + ->withDefaultValue("<QueryList>\n" + " <Query Id=\"0\">\n" + " <Select Path=\"Application\">*</Select>\n" + " </Query>\n" + "</QueryList>\n")->build()); +core::Property SourceInitiatedSubscriptionListener::InitialExistingEventsStrategy( + core::PropertyBuilder::createProperty("Initial Existing Events Strategy")->withDescription("Defines the behaviour of the Processor when a new event source connects.\n" + "None: will not request existing events\n" + "All: will request all existing events matching the query") + ->isRequired(true)->withAllowableValues<std::string>({INITIAL_EXISTING_EVENTS_STRATEGY_NONE, INITIAL_EXISTING_EVENTS_STRATEGY_ALL}) + ->withDefaultValue(INITIAL_EXISTING_EVENTS_STRATEGY_NONE)->build()); +core::Property SourceInitiatedSubscriptionListener::SubscriptionExpirationInterval( + core::PropertyBuilder::createProperty("Subscription Expiration Interval")->withDescription("The interval while a subscription is valid without renewal. " + "Because in a source-initiated subscription, the collector can not cancel the subscription, " + "setting this too large could cause unnecessary load on the source machine. " + "Setting this too small causes frequent reenumeration and resubscription which is ineffective.") + ->isRequired(true)->withDefaultValue<core::TimePeriodValue>("10 min")->build()); +core::Property SourceInitiatedSubscriptionListener::HeartbeatInterval( + core::PropertyBuilder::createProperty("Heartbeat Interval")->withDescription("The processor will ask the sources to send heartbeats with this interval.") + ->isRequired(true)->withDefaultValue<core::TimePeriodValue>("30 sec")->build()); +core::Property SourceInitiatedSubscriptionListener::MaxElements( + core::PropertyBuilder::createProperty("Max Elements")->withDescription("The maximum number of events a source will batch together and send at once.") + ->isRequired(true)->withDefaultValue<uint32_t>(20U)->build()); +core::Property SourceInitiatedSubscriptionListener::MaxLatency( + core::PropertyBuilder::createProperty("Max Latency")->withDescription("The maximum time a source will wait to send new events.") + ->isRequired(true)->withDefaultValue<core::TimePeriodValue>("10 sec")->build()); +core::Property SourceInitiatedSubscriptionListener::ConnectionRetryInterval( + core::PropertyBuilder::createProperty("Connection Retry Interval")->withDescription("The interval with which a source will try to reconnect to the server.") + ->withDefaultValue<core::TimePeriodValue>("10 sec")->build()); +core::Property SourceInitiatedSubscriptionListener::ConnectionRetryCount( + core::PropertyBuilder::createProperty("Connection Retry Count")->withDescription("The number of connection retries after which a source will consider the subscription expired.") + ->withDefaultValue<uint32_t>(5U)->build()); +core::Property SourceInitiatedSubscriptionListener::StateDirectory( + core::PropertyBuilder::createProperty("State Directory")->withDescription("The directory the Processor will use to store the current bookmark for each event source. " + "This will be used after restart to continue event ingestion from the point the Processor left off.") + ->isRequired(true)->build()); + +core::Relationship SourceInitiatedSubscriptionListener::Success("success", "All Events are routed to success"); + +constexpr char const* SourceInitiatedSubscriptionListener::ATTRIBUTE_WEF_REMOTE_MACHINEID; +constexpr char const* SourceInitiatedSubscriptionListener::ATTRIBUTE_WEF_REMOTE_IP; + +constexpr char const* SourceInitiatedSubscriptionListener::INITIAL_EXISTING_EVENTS_STRATEGY_NONE; +constexpr char const* SourceInitiatedSubscriptionListener::INITIAL_EXISTING_EVENTS_STRATEGY_ALL; + +constexpr char const* SourceInitiatedSubscriptionListener::ProcessorName; + +SourceInitiatedSubscriptionListener::SourceInitiatedSubscriptionListener(std::string name, utils::Identifier uuid) + : Processor(name, uuid) + , logger_(logging::LoggerFactory<SourceInitiatedSubscriptionListener>::getLogger()) + , session_factory_(nullptr) + , listen_port_(0U) + , subscription_expiration_interval_(0) + , heartbeat_interval_(0) + , max_elements_(0U) + , max_latency_(0) + , connection_retry_interval_(0) + , connection_retry_count_(0U) { +} + +SourceInitiatedSubscriptionListener::Handler::Handler(SourceInitiatedSubscriptionListener& processor) + : processor_(processor) { +} + +SourceInitiatedSubscriptionListener::SubscriberData::SubscriberData() + : bookmark_(nullptr) + , subscription_(nullptr) { +} + +SourceInitiatedSubscriptionListener::SubscriberData::~SubscriberData() { + clearSubscription(); + clearBookmark(); +} + +void SourceInitiatedSubscriptionListener::SubscriberData::setSubscription(const std::string& subscription_version, + WsXmlDocH subscription, + const std::string& subscription_endpoint, + const std::string& subscription_identifier) { + clearSubscription(); + subscription_version_ = subscription_version; + subscription_ = subscription; + subscription_endpoint_ = subscription_endpoint; + subscription_identifier_ = subscription_identifier; +} + +void SourceInitiatedSubscriptionListener::SubscriberData::clearSubscription() { + subscription_version_.clear(); + if (subscription_ != nullptr) { + ws_xml_destroy_doc(subscription_); + } + subscription_ = nullptr; +} + +void SourceInitiatedSubscriptionListener::SubscriberData::setBookmark(WsXmlDocH bookmark) { + clearBookmark(); + bookmark_ = bookmark; +} + +void SourceInitiatedSubscriptionListener::SubscriberData::clearBookmark() { + if (bookmark_ != nullptr) { + ws_xml_destroy_doc(bookmark_); + } + bookmark_ = nullptr; +} + +/* + * This is very basic state storage. We will have to ensure that the configurations match before we use a bookmark, + * and we also have to remove serialized bookmarks when needed. Once the proper centralized state storage is merged back, + * it will be much easier to implement a proper state storage with that, so for the time being I will leave it like this. + */ +bool SourceInitiatedSubscriptionListener::persistState() const { + utils::file::FileUtils::create_dir(state_directory_path_); + for (const auto& subscriber : subscribers_) { + std::ofstream bookmark_file(utils::file::FileUtils::concat_path(state_directory_path_, subscriber.first)); + char* xml_buf = nullptr; + int xml_buf_size = 0; + ws_xml_dump_memory_enc(subscriber.second.bookmark_, &xml_buf, &xml_buf_size, "UTF-8"); + bookmark_file.write(xml_buf, xml_buf_size); + ws_xml_free_memory(xml_buf); + } + return true; +} + +bool SourceInitiatedSubscriptionListener::loadState() { + std::map<std::string /*machineId*/, WsXmlDocH /*bookmark*/> bookmarks; Review comment: We don't need ordering, but if we had to communicate with enough machines to cause a significant performance difference between map and unordered_map, we would have bigger problems. Doesn't hurt to change it, though, so I will. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org