diff --git a/src/cm/app/aoscore.cpp b/src/cm/app/aoscore.cpp index 84c7c31e0..6415e9e86 100644 --- a/src/cm/app/aoscore.cpp +++ b/src/cm/app/aoscore.cpp @@ -124,7 +124,7 @@ void AosCore::Init(const std::string& configFile) mDNSServer.Init(mConfig.mDNSStoragePath, mConfig.mDNSPidFile, mConfig.mDNSIP); - err = mNetworkManager.Init(mDatabase, mCryptoProvider, mDNSServer, &mSMController); + err = mNetworkManager.Init(mDatabase, mCryptoProvider, mDNSServer, &mSMController, mConfig.mNetworkRemoveTimeout); AOS_ERROR_CHECK_AND_THROW(err, "can't initialize network manager"); InitSMController(); @@ -215,6 +215,15 @@ void AosCore::Start() } }); + err = mNetworkManager.Start(); + AOS_ERROR_CHECK_AND_THROW(err, "can't start network manager"); + + mCleanupManager.AddCleanup([this]() { + if (auto err = mNetworkManager.Stop(); !err.IsNone()) { + LOG_ERR() << "Can't stop network manager" << Log::Field(err); + } + }); + err = mSMController.Start(); AOS_ERROR_CHECK_AND_THROW(err, "can't start SM controller"); @@ -309,7 +318,8 @@ void AosCore::InitSMController() config.mCMServerURL = mConfig.mCMServerURL; auto err = mSMController.Init(config, mCommunication, mIAMClient, mCertLoader, mCryptoProvider, mImageManager, - mAlerts, mCommunication, mCommunication, mMonitoring, mLauncher, mNodeInfoProvider, mNetworkManager); + mAlerts, mCommunication, mCommunication, mMonitoring, mLauncher, mNodeInfoProvider, mNetworkManager, + mNetworkManager); AOS_ERROR_CHECK_AND_THROW(err, "can't initialize SM controller"); } diff --git a/src/cm/config/config.cpp b/src/cm/config/config.cpp index 8e56c1b54..38765bd14 100644 --- a/src/cm/config/config.cpp +++ b/src/cm/config/config.cpp @@ -28,6 +28,7 @@ constexpr auto cDefaultLauncherInstanceTTL = "30d"; constexpr auto cDefaultLauncherCheckOverrideEnvVarsPeriod = "1m"; constexpr auto cDefaultLauncherNodesConnectionTimeout = "10m"; constexpr auto cDefaultMonitoringSendPeriod = "1m"; +constexpr auto cDefaultNetworkRemoveTimeout = "2m"; constexpr auto cDefaultSMConnectionTimeout = "1m"; constexpr auto cDefaultUnitStatusSendTimeout = "10s"; constexpr auto cDefaultItemCacheTTL = "30d"; @@ -174,6 +175,10 @@ Error ParseConfig(const std::string& filename, Config& config) Tie(config.mCloudResponseWaitTimeout, err) = common::utils::ParseDuration( object.GetValue("cloudResponseWaitTimeout", cDefaultCloudResponseWaitTimeout)); AOS_ERROR_CHECK_AND_THROW(err, "error parsing cloudResponseWaitTimeout tag"); + + Tie(config.mNetworkRemoveTimeout, err) = common::utils::ParseDuration( + object.GetValue("networkRemoveTimeout", cDefaultNetworkRemoveTimeout)); + AOS_ERROR_CHECK_AND_THROW(err, "error parsing networkRemoveTimeout tag"); } catch (const std::exception& e) { return common::utils::ToAosError(e); } diff --git a/src/cm/config/config.hpp b/src/cm/config/config.hpp index 80e25ec37..3ced91cf8 100644 --- a/src/cm/config/config.hpp +++ b/src/cm/config/config.hpp @@ -53,6 +53,7 @@ struct Config { std::string mUnitConfigFile; Duration mUnitStatusSendTimeout; Duration mCloudResponseWaitTimeout; + Duration mNetworkRemoveTimeout; }; /******************************************************************************* diff --git a/src/cm/config/tests/config.cpp b/src/cm/config/tests/config.cpp index cd5aae7f1..c811a8e00 100644 --- a/src/cm/config/tests/config.cpp +++ b/src/cm/config/tests/config.cpp @@ -35,6 +35,7 @@ constexpr auto cFullTestConfigJSON = R"({ "workingDir": "workingDir", "unitConfigFile": "/var/aos/aos_unit.cfg", "cloudResponseWaitTimeout": "3d", + "networkRemoveTimeout": "5m", "monitoring": { "sendPeriod": "5m" }, @@ -127,6 +128,7 @@ TEST_F(CMConfigTest, ParseFullConfig) EXPECT_EQ(config.mCertStorage, "/var/aos/crypt/cm/"); EXPECT_EQ(config.mCloudResponseWaitTimeout, aos::Time::cDay * 3); + EXPECT_EQ(config.mNetworkRemoveTimeout, aos::Time::cMinutes * 5); EXPECT_EQ(config.mMonitoring.mSendPeriod, aos::Time::cMinutes * 5); EXPECT_EQ(config.mNodeInfoProvider.mSMConnectionTimeout, aos::Time::cMinutes * 10); @@ -193,6 +195,7 @@ TEST_F(CMConfigTest, ParseMinimalConfigWithDefaults) EXPECT_EQ(config.mUnitStatusSendTimeout, aos::Time::cSeconds * 10); EXPECT_EQ(config.mCloudResponseWaitTimeout, aos::Time::cSeconds * 10); + EXPECT_EQ(config.mNetworkRemoveTimeout, aos::Time::cMinutes * 2); EXPECT_EQ(config.mMonitoring.mSendPeriod, aos::Time::cMinutes * 1); EXPECT_EQ(config.mNodeInfoProvider.mSMConnectionTimeout, aos::Time::cMinutes * 1); diff --git a/src/cm/networkmanager/itf/updatesubscriptionlistener.hpp b/src/cm/networkmanager/itf/updatesubscriptionlistener.hpp new file mode 100644 index 000000000..f336d9ed0 --- /dev/null +++ b/src/cm/networkmanager/itf/updatesubscriptionlistener.hpp @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2026 EPAM Systems, Inc. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef AOS_CM_NETWORKMANAGER_ITF_UPDATESUBSCRIPTIONLISTENER_HPP_ +#define AOS_CM_NETWORKMANAGER_ITF_UPDATESUBSCRIPTIONLISTENER_HPP_ + +#include + +namespace aos::cm::networkmanager { + +/** + * Network update subscription listener interface. + */ +class UpdateSubscriptionListenerItf { +public: + /** + * Destructor. + */ + virtual ~UpdateSubscriptionListenerItf() = default; + + /** + * Called when node subscribes to network updates. + * + * @param nodeID Node ID. + */ + virtual void OnNodeSubscribed(const String& nodeID) = 0; + + /** + * Called when node unsubscribes from network updates. + * + * @param nodeID Node ID. + */ + virtual void OnNodeUnsubscribed(const String& nodeID) = 0; +}; + +} // namespace aos::cm::networkmanager + +#endif // AOS_CM_NETWORKMANAGER_ITF_UPDATESUBSCRIPTIONLISTENER_HPP_ diff --git a/src/cm/networkmanager/networkmanager.cpp b/src/cm/networkmanager/networkmanager.cpp index 7ca3b109c..e58438219 100644 --- a/src/cm/networkmanager/networkmanager.cpp +++ b/src/cm/networkmanager/networkmanager.cpp @@ -75,12 +75,13 @@ std::string PortRangesToString(const std::vector& rang **********************************************************************************************************************/ Error NetworkManager::Init(StorageItf& storage, crypto::RandomItf& random, DNSServerItf& dnsServer, - aos::networkmanager::PendingUpdateHandlerItf* pendingUpdateHandler) + aos::networkmanager::PendingUpdateHandlerItf* pendingUpdateHandler, Duration networkRemoveTimeout) { mStorage = &storage; mRandom = &random; mDNSServer = &dnsServer; mPendingUpdateHandler = pendingUpdateHandler; + mNetworkRemoveTimeout = std::chrono::nanoseconds(networkRemoveTimeout.Nanoseconds()); mIpSubnet.Init(); @@ -121,11 +122,17 @@ Error NetworkManager::Init(StorageItf& storage, crypto::RandomItf& random, DNSSe networkState.mHostInstances.emplace(host.mNodeID.CStr(), std::move(hostInstances)); } + if (!HasInstances(networkState)) { + ScheduleNetworkRemoval(network.mNetworkID.CStr()); + } + mNetworkStates.emplace(network.mNetworkID.CStr(), std::move(networkState)); } RemoveExistedNetworks(); + mUnitNetworks = GetUnitNetworks(); + // Restore pending connections from DB auto pendingConnections = std::make_unique>(); @@ -140,8 +147,51 @@ Error NetworkManager::Init(StorageItf& storage, crypto::RandomItf& random, DNSSe return ErrorEnum::eNone; } +Error NetworkManager::Start() +{ + if (mNetworkRemoveTimeout.count() == 0) { + return ErrorEnum::eNone; + } + + LOG_DBG() << "Start network manager"; + + if (mRemovalThread.joinable()) { + return AOS_ERROR_WRAP(ErrorEnum::eWrongState); + } + + try { + mRemovalStopped = false; + mRemovalThread = std::thread(&NetworkManager::RunRemovalThread, this); + } catch (const std::exception& e) { + return AOS_ERROR_WRAP(common::utils::ToAosError(e)); + } + + return ErrorEnum::eNone; +} + +Error NetworkManager::Stop() +{ + LOG_DBG() << "Stop network manager"; + + { + std::lock_guard lock {mRemovalMutex}; + + mRemovalStopped = true; + } + + mRemovalCondVar.notify_all(); + + if (mRemovalThread.joinable()) { + mRemovalThread.join(); + } + + return ErrorEnum::eNone; +} + Error NetworkManager::GetNodeNetworkParams(const String& networkID, const String& nodeID, NetworkParams& result) { + auto syncUnitNetworks = DeferRelease([this]() { SyncUnitNetworks(); }); + std::lock_guard lock {mMutex}; LOG_DBG() << "Getting node network params" << Log::Field("networkID", networkID) << Log::Field("nodeID", nodeID); @@ -208,6 +258,8 @@ Error NetworkManager::GetNodeNetworkParams(const String& networkID, const String mNetworkStates.emplace(networkID.CStr(), std::move(networkState)); + ScheduleNetworkRemoval(networkID.CStr()); + auto err = mStorage->AddNetwork(network); AOS_ERROR_CHECK_AND_THROW(err, "error adding network"); @@ -226,6 +278,8 @@ Error NetworkManager::GetNodeNetworkParams(const String& networkID, const String Error NetworkManager::AllocateInstanceNetwork(const InstanceIdent& instanceIdent, const String& networkID, const String& nodeID, const UpdateItemNetworkParams& serviceData, InstanceNetworkAllocation& result) { + auto syncUnitNetworks = DeferRelease([this]() { SyncUnitNetworks(); }); + std::unique_lock lock {mMutex}; LOG_DBG() << "Allocating instance network" << Log::Field("instanceIdent", instanceIdent) @@ -393,6 +447,8 @@ Error NetworkManager::AllocateInstanceNetwork(const InstanceIdent& instanceIdent return AOS_ERROR_WRAP(err); } + (void)mRemovalDeadlines.erase(networkID.CStr()); + StorePendingConnections( instanceIdent, nodeID, networkID, result.mIP, it->second.mNetwork.mSubnet.CStr(), connections); @@ -418,6 +474,8 @@ Error NetworkManager::ReleaseInstanceNetwork(const InstanceIdent& instanceIdent, auto err = RemoveInstance(instanceIdent, nodeID, targets); + SyncUnitNetworks(); + if (err.IsNone() && targets.empty()) { LOG_WRN() << "Instance network parameters not found" << Log::Field("instanceIdent", instanceIdent); @@ -439,6 +497,8 @@ Error NetworkManager::ReleaseNodeNetwork(const String& networkID, const String& auto err = RemoveNode(networkID, nodeID, targets); + SyncUnitNetworks(); + if (!targets.empty()) { UpdateRequesters(targets, {}); } @@ -523,6 +583,28 @@ Error NetworkManager::SyncNetworkState(const String& nodeID, const Arraysecond.mInstances.erase(itInstance); + if (!HasInstances(networkState)) { + ScheduleNetworkRemoval(networkID); + } + targets = std::move(instanceTargets); (void)mPendingConnections.erase(instanceIdent); @@ -946,6 +1032,8 @@ Error NetworkManager::RemoveNode(const String& networkID, const String& nodeID, std::vector nodeTargets; + const auto hadInstances = !itHost->second.mInstances.empty(); + for (auto& [_, instance] : itHost->second.mInstances) { const auto instanceTargets = GetInstanceTargets(instance.mInstanceIdent); @@ -977,6 +1065,9 @@ Error NetworkManager::RemoveNode(const String& networkID, const String& nodeID, AOS_ERROR_CHECK_AND_THROW(err, "error removing network"); (void)mNetworkStates.erase(it); + (void)mRemovalDeadlines.erase(networkID.CStr()); + } else if (hadInstances && !HasInstances(it->second)) { + ScheduleNetworkRemoval(networkID.CStr()); } targets = std::move(nodeTargets); @@ -1100,4 +1191,182 @@ void NetworkManager::PushFirewallUpdates(const FirewallUpdates& updates) } } +bool NetworkManager::HasInstances(const NetworkState& networkState) +{ + return std::any_of(networkState.mHostInstances.begin(), networkState.mHostInstances.end(), + [](const auto& hostInstances) { return !hostInstances.second.mInstances.empty(); }); +} + +bool NetworkManager::IsUnitNetwork(const std::string& networkID, const NetworkState& networkState) const +{ + return HasInstances(networkState) || mRemovalDeadlines.count(networkID) != 0; +} + +std::vector NetworkManager::GetUnitNetworks() const +{ + std::vector unitNetworks; + + for (const auto& [networkID, networkState] : mNetworkStates) { + if (IsUnitNetwork(networkID, networkState)) { + unitNetworks.push_back(networkID); + } + } + + std::sort(unitNetworks.begin(), unitNetworks.end()); + + return unitNetworks; +} + +void NetworkManager::SyncUnitNetworks() +{ + { + std::lock_guard updateLock {mUpdateMutex}; + + (void)PushUnitNetworksIfChanged(); + } + + NotifyRemovalThread(); +} + +bool NetworkManager::PushUnitNetworksIfChanged() +{ + std::vector unitNetworks; + + { + std::lock_guard lock {mMutex}; + + unitNetworks = GetUnitNetworks(); + } + + if (unitNetworks == mUnitNetworks) { + return false; + } + + mUnitNetworks = std::move(unitNetworks); + + PushUnitNetworks(mSubscribedNodes); + + return true; +} + +void NetworkManager::PushUnitNetworks(const std::set& nodeIDs) +{ + if (!mPendingUpdateHandler) { + return; + } + + auto networkIDs = std::make_unique, cMaxNumOwners>>(); + + for (const auto& networkID : mUnitNetworks) { + StaticString id; + + auto err = id.Assign(networkID.c_str()); + if (err.IsNone()) { + err = networkIDs->PushBack(id); + } + + if (!err.IsNone()) { + LOG_ERR() << "Failed to prepare unit networks update" << Log::Field("networksCount", mUnitNetworks.size()) + << Log::Field(err); + + return; + } + } + + for (const auto& nodeID : nodeIDs) { + LOG_DBG() << "Pushing unit networks update" << Log::Field("nodeID", nodeID.c_str()) + << Log::Field("networksCount", networkIDs->Size()); + + mPendingUpdateHandler->OnUnitNetworksUpdate(nodeID.c_str(), *networkIDs); + } +} + +void NetworkManager::ScheduleNetworkRemoval(const std::string& networkID) +{ + if (mNetworkRemoveTimeout.count() == 0) { + return; + } + + LOG_DBG() << "Schedule network removal" << Log::Field("networkID", networkID.c_str()); + + mRemovalDeadlines[networkID] = Clock::now() + mNetworkRemoveTimeout; +} + +std::optional NetworkManager::GetNextRemovalDeadline() const +{ + std::lock_guard lock {mMutex}; + + auto it = std::min_element(mRemovalDeadlines.begin(), mRemovalDeadlines.end(), + [](const auto& left, const auto& right) { return left.second < right.second; }); + if (it == mRemovalDeadlines.end()) { + return std::nullopt; + } + + return it->second; +} + +void NetworkManager::EraseExpiredDeadlines() +{ + std::lock_guard lock {mMutex}; + + const auto now = Clock::now(); + + for (auto it = mRemovalDeadlines.begin(); it != mRemovalDeadlines.end();) { + if (it->second > now) { + ++it; + continue; + } + + LOG_DBG() << "Network removal timeout expired" << Log::Field("networkID", it->first.c_str()); + + it = mRemovalDeadlines.erase(it); + } +} + +void NetworkManager::HandleRemovalTimeout() +{ + std::lock_guard updateLock {mUpdateMutex}; + + EraseExpiredDeadlines(); + + (void)PushUnitNetworksIfChanged(); +} + +void NetworkManager::NotifyRemovalThread() +{ + { + std::lock_guard lock {mRemovalMutex}; + + mRemovalDeadlinesChanged = true; + } + + mRemovalCondVar.notify_one(); +} + +void NetworkManager::RunRemovalThread() +{ + std::unique_lock lock {mRemovalMutex}; + + const auto wakeUp = [this]() { return mRemovalStopped || mRemovalDeadlinesChanged; }; + + while (!mRemovalStopped) { + mRemovalDeadlinesChanged = false; + + const auto deadline = GetNextRemovalDeadline(); + + if (!deadline) { + mRemovalCondVar.wait(lock, wakeUp); + continue; + } + + if (mRemovalCondVar.wait_until(lock, *deadline, wakeUp)) { + continue; + } + + lock.unlock(); + HandleRemovalTimeout(); + lock.lock(); + } +} + } // namespace aos::cm::networkmanager diff --git a/src/cm/networkmanager/networkmanager.hpp b/src/cm/networkmanager/networkmanager.hpp index 4a13c70ca..157af607f 100644 --- a/src/cm/networkmanager/networkmanager.hpp +++ b/src/cm/networkmanager/networkmanager.hpp @@ -7,9 +7,14 @@ #ifndef AOS_CM_NETWORKMANAGER_NETWORKMANAGER_HPP_ #define AOS_CM_NETWORKMANAGER_NETWORKMANAGER_HPP_ +#include +#include #include +#include +#include #include #include +#include #include #include #include @@ -24,10 +29,11 @@ #include "ipsubnet.hpp" #include "itf/dnsserver.hpp" #include "itf/storage.hpp" +#include "itf/updatesubscriptionlistener.hpp" namespace aos::cm::networkmanager { -class NetworkManager : public aos::networkmanager::NetworkProviderItf { +class NetworkManager : public aos::networkmanager::NetworkProviderItf, public UpdateSubscriptionListenerItf { public: /** * Constructor. @@ -41,10 +47,26 @@ class NetworkManager : public aos::networkmanager::NetworkProviderItf { * @param random Random interface. * @param dnsServer DNS server interface. * @param pendingUpdateHandler Pending firewall update handler (optional). + * @param networkRemoveTimeout Time a network without instances stays in the unit networks (0 - no delay). * @return Error. */ Error Init(StorageItf& storage, crypto::RandomItf& random, DNSServerItf& dnsServer, - aos::networkmanager::PendingUpdateHandlerItf* pendingUpdateHandler = nullptr); + aos::networkmanager::PendingUpdateHandlerItf* pendingUpdateHandler = nullptr, + Duration networkRemoveTimeout = 0); + + /** + * Starts network manager. + * + * @return Error. + */ + Error Start(); + + /** + * Stops network manager. + * + * @return Error. + */ + Error Stop(); /** * Gets node network parameters. @@ -96,6 +118,20 @@ class NetworkManager : public aos::networkmanager::NetworkProviderItf { */ Error SyncNetworkState(const String& nodeID, const Array& instances) override; + /** + * Called when node subscribes to network updates. + * + * @param nodeID Node ID. + */ + void OnNodeSubscribed(const String& nodeID) override; + + /** + * Called when node unsubscribes from network updates. + * + * @param nodeID Node ID. + */ + void OnNodeUnsubscribed(const String& nodeID) override; + private: static constexpr uint64_t cMaxVlanID = 4096; static constexpr int cVlanGenerateRetries = 4; @@ -161,6 +197,22 @@ class NetworkManager : public aos::networkmanager::NetworkProviderItf { Error RestartDNS(); + using Clock = std::chrono::steady_clock; + + static bool HasInstances(const NetworkState& networkState); + bool IsUnitNetwork(const std::string& networkID, const NetworkState& networkState) const; + std::vector GetUnitNetworks() const; + void SyncUnitNetworks(); + bool PushUnitNetworksIfChanged(); + void PushUnitNetworks(const std::set& nodeIDs); + + void ScheduleNetworkRemoval(const std::string& networkID); + std::optional GetNextRemovalDeadline() const; + void EraseExpiredDeadlines(); + void HandleRemovalTimeout(); + void NotifyRemovalThread(); + void RunRemovalThread(); + StorageItf* mStorage {}; crypto::RandomItf* mRandom {}; DNSServerItf* mDNSServer {}; @@ -173,6 +225,15 @@ class NetworkManager : public aos::networkmanager::NetworkProviderItf { std::unordered_map> mPendingConnections; std::unordered_set mPushedRequesters; aos::networkmanager::PendingUpdateHandlerItf* mPendingUpdateHandler {}; + std::vector mUnitNetworks; + std::set mSubscribedNodes; + std::chrono::nanoseconds mNetworkRemoveTimeout {}; + std::unordered_map mRemovalDeadlines; + std::mutex mRemovalMutex; + std::condition_variable mRemovalCondVar; + std::thread mRemovalThread; + bool mRemovalStopped {}; + bool mRemovalDeadlinesChanged {}; }; } // namespace aos::cm::networkmanager diff --git a/src/cm/networkmanager/networkmanager.md b/src/cm/networkmanager/networkmanager.md index 737fa0132..09a453881 100644 --- a/src/cm/networkmanager/networkmanager.md +++ b/src/cm/networkmanager/networkmanager.md @@ -2,8 +2,9 @@ Network manager is the CM side of the AosCore networking. It is the allocator: it hands out subnets, VLAN IDs and IP addresses to nodes and instances, resolves per-instance firewall rules from allowed connections and exposed ports, -maintains the unit-level DNS hosts and keeps the allocation consistent across the unit. The node side (namespaces, -bridges, firewall, bandwidth, DNS on the node) is built by the SM network manager. +maintains the unit-level DNS hosts, announces the set of unit networks to the nodes and keeps the allocation +consistent across the unit. The node side (namespaces, bridges, firewall, bandwidth, DNS on the node) is built by the +SM network manager. The overall networking architecture is described in the public documentation: @@ -21,7 +22,9 @@ It implements the following interfaces: - [aos::networkmanager::NetworkProviderItf][networkprovider-itf] - serves node/instance network allocation, release and state synchronization requests coming from SM. SM controller exposes it to the nodes over the gRPC network - service. + service; +- [aos::cm::networkmanager::UpdateSubscriptionListenerItf](itf/updatesubscriptionlistener.hpp) - notified by SM + controller when a node opens or closes the instance network update stream. It requires the following interfaces: @@ -31,7 +34,7 @@ It requires the following interfaces: DNS IP); - [aos::common::crypto::RandomItf][random-itf] - generates VLAN IDs; - [aos::networkmanager::PendingUpdateHandlerItf][pendingupdatehandler-itf] - optional; receives resolved pending - firewall rules to push them to the node. In CM it is implemented by SM controller. + firewall rules and the set of unit networks to push them to the node. In CM it is implemented by SM controller. It uses the following internal components: @@ -68,6 +71,9 @@ classDiagram class PendingUpdateHandlerItf ["aos::networkmanager::PendingUpdateHandlerItf"] { <> } + class UpdateSubscriptionListenerItf ["aos::cm::networkmanager::UpdateSubscriptionListenerItf"] { + <> + } class IpSubnet ["aos::cm::networkmanager::IpSubnet"] { } @@ -76,7 +82,9 @@ classDiagram %% SM controller serves the gRPC network service and forwards it to network manager SMController ..> NetworkProviderItf + SMController ..> UpdateSubscriptionListenerItf NetworkProviderItf <|.. NetworkManager + UpdateSubscriptionListenerItf <|.. NetworkManager %% network manager dependencies NetworkManager ..> StorageItf @@ -106,7 +114,8 @@ Network manager keeps its state in memory and mirrors it to the storage: - **hosts** - in-memory map instance IP to DNS names, written to the DNS server hosts file. In memory the data is organized as network state per network ID: the network, and per node ID the host and its -instances. +instances. Besides that, network manager keeps the set of unit networks, the nodes subscribed to the network updates +and the scheduled network removal times (see [Unit networks](#unit-networks)). ## Initialization @@ -118,6 +127,14 @@ instances. 3. marks the loaded subnets and IPs as used in the subnet allocator, so they are not allocated again; 4. loads pending connection records from the storage. +`Init` also takes the network remove timeout (`networkRemoveTimeout` in the CM config). A stored network without +instances gets its removal scheduled, so it stays in the set of unit networks for the timeout. The initial set of unit +networks is built from the restored state. + +`Start` runs the thread that handles the network removal timeouts and `Stop` stops it; with zero timeout `Start` does +nothing. In the CM application they are called around the SM controller start, so SM controller is stopped first on +shutdown. + Database migration 1 adds an empty hostname list to existing instance records; those lists are populated when SM next supplies the instance network parameters. @@ -133,7 +150,10 @@ Returns node network parameters (network ID, subnet, node IP, VLAN ID) for the g - if the network exists but the node is not on it yet, allocates a node IP from the network subnet and stores the host; - if the network does not exist, generates a unique VLAN ID, allocates a free subnet from the pools, allocates a node - IP and stores the network and the host. + IP, stores the network and the host and schedules the network removal. The new network is in the set of unit + networks and is announced to all subscribed nodes before its first instance is allocated. + +If the set of unit networks changed, it is pushed to the subscribed nodes (see [Unit networks](#unit-networks)). ```mermaid sequenceDiagram @@ -185,6 +205,8 @@ the new service data. A renamed hostname updates the rules of requesters that re On any failure the allocated IP, the instance record and the hosts map are rolled back. +A successful allocation cancels the scheduled removal of the network. + ```mermaid sequenceDiagram participant smcontroller @@ -222,20 +244,24 @@ sequenceDiagram Releases the instance on the given node: returns the IP to the subnet, removes the instance hosts from the DNS hosts map, removes the instance and its pending connection records (where it is the requester) from the storage and reloads the DNS server. Requesters that reference the released instance's item ID or hostnames are re-resolved and their rule -sets are pushed, so rules to the released address disappear. Unknown instances are ignored. +sets are pushed, so rules to the released address disappear. Unknown instances are ignored. If it was the last +instance on the network, the network removal is scheduled: the network stays in the set of unit networks until the +timeout expires. ### ReleaseNodeNetwork Releases the node from the network: releases all instances of the node on that network the same way as `ReleaseInstanceNetwork`, removes the host from the storage and, if it was the last node on the network, returns the subnet to the pool and removes the network from the storage. The DNS server is reloaded and the requesters referencing -the released instances are updated afterwards. +the released instances are updated afterwards. If the node's instances were the last ones on the network but other +nodes remain on it, the network removal is scheduled. ### SyncNetworkState Reconciles the CM view with the running instances reported by SM on (re)connect: -1. instances that CM has allocated on the node but SM does not report are released (`ReleaseInstanceNetwork`); +1. instances that CM has allocated on the node but SM does not report are released (`ReleaseInstanceNetwork`), so the + set of unit networks is updated the same way; 2. for every reported instance that has pending connection records, the current rule set is resolved and compared with the rules reported by SM. If a resolved rule is missing on SM, or SM holds a rule to an address that is no longer allocated to any instance, the whole rule set is pushed to the node. @@ -261,6 +287,86 @@ sequenceDiagram end ``` +## Unit networks + +Network manager owns the set of unit networks. A network is in the set if it has at least one allocated instance on any +node, or if it has no instances but its removal is still pending. Every node creates the bridge and VLAN of every +network of the set (see the [SM network manager][sm-networkmanager]), so instances of different providers on different +nodes can communicate and a network keeps its VLAN ID and subnet while an instance migrates. + +[sm-networkmanager]: ../../sm/networkmanager/networkmanager.md + +SM stays the initiator of the node network allocation: + +- for a network of the set that it does not have, SM calls `GetNodeNetworkParams`; +- for a network that left the set and has no local instances, SM calls `ReleaseNodeNetwork`. CM frees the VLAN ID and + the subnet of the network when its last host is released. + +### Announcing + +The full set (network IDs, sorted) is pushed with `PendingUpdateHandlerItf::OnUnitNetworksUpdate(nodeID, networkIDs)`. +SM controller writes it to the node's network update stream as a `unit_networks_update` notification. The set is +pushed: + +- to a node when it subscribes to the network update stream, also when the set is empty. SM controller reports it via + `UpdateSubscriptionListenerItf::OnNodeSubscribed`, and `OnNodeUnsubscribed` when the stream of the node is closed, + unless a newer stream of the same node has replaced it; +- to all subscribed nodes when the set changes, after `GetNodeNetworkParams`, `AllocateInstanceNetwork`, + `ReleaseInstanceNetwork`, `ReleaseNodeNetwork`, `SyncNetworkState` and when a removal timeout expires. + +Nothing is pushed if the set did not change. If the set does not fit `cMaxNumOwners` IDs, an error is logged and +nothing is pushed: a truncated set is never sent. SM ignores an update that cannot be converted completely. + +Pushes are serialized by an update mutex. The handler is never called with the state mutex held. + +### Delayed removal + +A network without instances stays in the set for the network remove timeout (`networkRemoveTimeout` in the CM config, +`2m` by default, `0` disables the delay). This keeps the VLAN ID and subnet of a network when its only instance is +moved to another node or restarted on update: the instance is released on the old node before it is allocated on the +new one. + +The removal is scheduled: + +- when the network is created by `GetNodeNetworkParams`; +- when the last instance of the network is released (`ReleaseInstanceNetwork`, `ReleaseNodeNetwork`, stale instances + in `SyncNetworkState`); +- on `Init` for stored networks without instances. + +`GetNodeNetworkParams` for an existing network does not set or extend it. The removal is cancelled when an instance is +allocated in the network. When the timeout expires, the network leaves the set and the new set is pushed. CM does not +delete the network itself: SMs release it and CM removes it with its last host. The removal time is kept in memory +only, so after a CM restart the full timeout starts again. + +```mermaid +sequenceDiagram + participant nodeA as SM (node A) + participant nodeB as SM (node B) + participant networkmanager + participant smcontroller + + nodeA ->> networkmanager: GetNodeNetworkParams(network1, nodeA) + Note over networkmanager: network created, removal scheduled + networkmanager ->> smcontroller: OnUnitNetworksUpdate(nodeA, [network1]) + networkmanager ->> smcontroller: OnUnitNetworksUpdate(nodeB, [network1]) + smcontroller -->> nodeA: unit_networks_update([network1]) + smcontroller -->> nodeB: unit_networks_update([network1]) + nodeB ->> networkmanager: GetNodeNetworkParams(network1, nodeB) + nodeA ->> networkmanager: AllocateInstanceNetwork(instance, network1, nodeA) + Note over networkmanager: removal cancelled + + nodeA ->> networkmanager: ReleaseInstanceNetwork(instance, nodeA) + Note over networkmanager: last instance released, removal scheduled + Note over networkmanager: removal timeout expires + networkmanager ->> smcontroller: OnUnitNetworksUpdate(nodeA, []) + networkmanager ->> smcontroller: OnUnitNetworksUpdate(nodeB, []) + smcontroller -->> nodeA: unit_networks_update([]) + smcontroller -->> nodeB: unit_networks_update([]) + nodeA ->> networkmanager: ReleaseNodeNetwork(network1, nodeA) + nodeB ->> networkmanager: ReleaseNodeNetwork(network1, nodeB) + Note over networkmanager: last host released, network removed +``` + ## Firewall rules Allowed connections are given in the service data as `/[/]` (protocol defaults to `tcp`, port diff --git a/src/cm/networkmanager/tests/mocks/updatesubscriptionlistenermock.hpp b/src/cm/networkmanager/tests/mocks/updatesubscriptionlistenermock.hpp new file mode 100644 index 000000000..333c92613 --- /dev/null +++ b/src/cm/networkmanager/tests/mocks/updatesubscriptionlistenermock.hpp @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2026 EPAM Systems, Inc. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef AOS_CM_NETWORKMANAGER_TESTS_MOCKS_UPDATESUBSCRIPTIONLISTENERMOCK_HPP_ +#define AOS_CM_NETWORKMANAGER_TESTS_MOCKS_UPDATESUBSCRIPTIONLISTENERMOCK_HPP_ + +#include + +#include + +namespace aos::cm::networkmanager { + +class MockUpdateSubscriptionListener : public UpdateSubscriptionListenerItf { +public: + MOCK_METHOD(void, OnNodeSubscribed, (const String& nodeID), (override)); + MOCK_METHOD(void, OnNodeUnsubscribed, (const String& nodeID), (override)); +}; + +} // namespace aos::cm::networkmanager + +#endif // AOS_CM_NETWORKMANAGER_TESTS_MOCKS_UPDATESUBSCRIPTIONLISTENERMOCK_HPP_ diff --git a/src/cm/networkmanager/tests/networkmanager.cpp b/src/cm/networkmanager/tests/networkmanager.cpp index 1b867b9cc..c82cbde00 100644 --- a/src/cm/networkmanager/tests/networkmanager.cpp +++ b/src/cm/networkmanager/tests/networkmanager.cpp @@ -5,8 +5,13 @@ */ #include +#include +#include +#include #include +#include #include +#include #include #include @@ -2500,4 +2505,306 @@ TEST_F(CMHostnameConnectionTest, FailedReleaseUpdatesRequesterOnlyAfterRemoval) EXPECT_TRUE(mUpdates[0].mFirewallRules.IsEmpty()); } +class CMUnitNetworksTest : public CMHostnameConnectionTest { +protected: + using UnitNetworksUpdates = std::vector>>; + + void SetUp() override + { + CMHostnameConnectionTest::SetUp(); + + EXPECT_CALL(mHandler, OnUnitNetworksUpdate(_, _)) + .WillRepeatedly(Invoke([this](const String& nodeID, const Array>& networkIDs) { + std::vector ids; + + for (const auto& networkID : networkIDs) { + ids.emplace_back(networkID.CStr()); + } + + mUnitUpdates.emplace_back(nodeID.CStr(), std::move(ids)); + })); + } + + Error Allocate(const char* itemID, const char* networkID) + { + InstanceIdent ident; + InstanceNetworkAllocation result; + + ident.mItemID = itemID; + ident.mSubjectID = "subject"; + + return mNetworkManager->AllocateInstanceNetwork(ident, networkID, "node", {}, result); + } + + Error Release(const char* itemID) + { + InstanceIdent ident; + + ident.mItemID = itemID; + ident.mSubjectID = "subject"; + + return mNetworkManager->ReleaseInstanceNetwork(ident, "node"); + } + + UnitNetworksUpdates mUnitUpdates; +}; + +TEST_F(CMUnitNetworksTest, SubscribeWithoutNetworksPushesEmptySet) +{ + mNetworkManager->OnNodeSubscribed("node"); + + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {}}})); +} + +TEST_F(CMUnitNetworksTest, SubscribePushesRestoredNetworksWithInstances) +{ + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + + mNetworkManager = std::make_unique(); + ASSERT_TRUE(mNetworkManager->Init(*mStorage, *mRandom, *mDNSServer, &mHandler).IsNone()); + + mNetworkManager->OnNodeSubscribed("node"); + + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {"target-net"}}})); +} + +TEST_F(CMUnitNetworksTest, FirstInstanceInNetworkPushesToSubscribedNodes) +{ + mNetworkManager->OnNodeSubscribed("node"); + mNetworkManager->OnNodeSubscribed("node2"); + mUnitUpdates.clear(); + + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + ASSERT_TRUE(Allocate("b", "target-net").IsNone()); + + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {"target-net"}}, {"node2", {"target-net"}}})); +} + +TEST_F(CMUnitNetworksTest, ReleasingLastInstancePushesSetWithoutNetwork) +{ + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + ASSERT_TRUE(Allocate("b", "target-net").IsNone()); + ASSERT_TRUE(Allocate("c", "requester-net").IsNone()); + + mNetworkManager->OnNodeSubscribed("node"); + + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {"requester-net", "target-net"}}})); + mUnitUpdates.clear(); + + ASSERT_TRUE(Release("a").IsNone()); + EXPECT_TRUE(mUnitUpdates.empty()); + + ASSERT_TRUE(Release("b").IsNone()); + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {"requester-net"}}})); +} + +TEST_F(CMUnitNetworksTest, ReleaseNodeNetworkPushesSetWithoutNetwork) +{ + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + ASSERT_TRUE(Allocate("c", "requester-net").IsNone()); + + mNetworkManager->OnNodeSubscribed("node"); + mUnitUpdates.clear(); + + ASSERT_TRUE(mNetworkManager->ReleaseNodeNetwork("target-net", "node").IsNone()); + + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {"requester-net"}}})); +} + +TEST_F(CMUnitNetworksTest, SyncNetworkStatePushesSetWithoutStaleNetwork) +{ + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + + mNetworkManager->OnNodeSubscribed("node"); + mUnitUpdates.clear(); + + ASSERT_TRUE(mNetworkManager->SyncNetworkState("node", StaticArray()).IsNone()); + + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {}}})); +} + +TEST_F(CMUnitNetworksTest, UnsubscribedNodeGetsNoPushes) +{ + mNetworkManager->OnNodeSubscribed("node"); + mNetworkManager->OnNodeSubscribed("node2"); + mNetworkManager->OnNodeUnsubscribed("node2"); + mUnitUpdates.clear(); + + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + + EXPECT_EQ(mUnitUpdates, UnitNetworksUpdates({{"node", {"target-net"}}})); +} + +class CMUnitNetworksRemoveTimeoutTest : public CMUnitNetworksTest { +protected: + static constexpr auto cRemoveTimeout = std::chrono::milliseconds(400); + static constexpr auto cWaitTimeout = std::chrono::seconds(10); + + void SetUp() override + { + CMUnitNetworksTest::SetUp(); + + EXPECT_CALL(*mRandom, RandInt(_)).WillRepeatedly(Return(RetWithError(2000u, ErrorEnum::eNone))); + EXPECT_CALL(*mStorage, AddNetwork(_)).WillRepeatedly(Return(ErrorEnum::eNone)); + EXPECT_CALL(*mStorage, AddHost(_, _)).WillRepeatedly(Return(ErrorEnum::eNone)); + EXPECT_CALL(mHandler, OnUnitNetworksUpdate(_, _)) + .WillRepeatedly(Invoke([this](const String& nodeID, const Array>& networkIDs) { + std::vector ids; + + for (const auto& networkID : networkIDs) { + ids.emplace_back(networkID.CStr()); + } + + std::lock_guard lock {mUpdatesMutex}; + + mUnitUpdates.emplace_back(nodeID.CStr(), std::move(ids)); + mUpdatesCondVar.notify_all(); + })); + + InitManager(); + } + + void TearDown() override { EXPECT_TRUE(mNetworkManager->Stop().IsNone()); } + + void InitManager() + { + mNetworkManager = std::make_unique(); + + ASSERT_TRUE( + mNetworkManager + ->Init(*mStorage, *mRandom, *mDNSServer, &mHandler, std::chrono::nanoseconds(cRemoveTimeout).count()) + .IsNone()); + } + + bool WaitUpdates(size_t count, std::chrono::milliseconds timeout = cWaitTimeout) + { + std::unique_lock lock {mUpdatesMutex}; + + return mUpdatesCondVar.wait_for(lock, timeout, [&]() { return mUnitUpdates.size() >= count; }); + } + + UnitNetworksUpdates TakeUpdates() + { + std::lock_guard lock {mUpdatesMutex}; + + return std::exchange(mUnitUpdates, {}); + } + + void ExpireRestoredNetworks() + { + mNetworkManager->OnNodeSubscribed("node"); + + ASSERT_TRUE(mNetworkManager->Start().IsNone()); + ASSERT_TRUE(WaitUpdates(2)); + EXPECT_EQ(TakeUpdates(), + UnitNetworksUpdates({{"node", {"requester-net", "target-net", "target-net-2"}}, {"node", {}}})); + } + + std::mutex mUpdatesMutex; + std::condition_variable mUpdatesCondVar; +}; + +TEST_F(CMUnitNetworksRemoveTimeoutTest, NewNetworkIsAnnouncedAndRemovedAfterTimeout) +{ + ExpireRestoredNetworks(); + + NetworkParams params; + + const auto start = std::chrono::steady_clock::now(); + + ASSERT_TRUE(mNetworkManager->GetNodeNetworkParams("new-net", "node", params).IsNone()); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {"new-net"}}})); + + ASSERT_TRUE(WaitUpdates(1)); + EXPECT_GE(std::chrono::steady_clock::now() - start, cRemoveTimeout); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {}}})); +} + +TEST_F(CMUnitNetworksRemoveTimeoutTest, ReleasingLastInstanceRemovesNetworkAfterTimeout) +{ + ExpireRestoredNetworks(); + + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {"target-net"}}})); + + const auto start = std::chrono::steady_clock::now(); + + ASSERT_TRUE(Release("a").IsNone()); + EXPECT_TRUE(TakeUpdates().empty()); + + ASSERT_TRUE(WaitUpdates(1)); + EXPECT_GE(std::chrono::steady_clock::now() - start, cRemoveTimeout); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {}}})); +} + +TEST_F(CMUnitNetworksRemoveTimeoutTest, AllocatingInstanceCancelsRemoval) +{ + ExpireRestoredNetworks(); + + NetworkParams params; + + ASSERT_TRUE(mNetworkManager->GetNodeNetworkParams("new-net", "node", params).IsNone()); + ASSERT_TRUE(Allocate("a", "new-net").IsNone()); + ASSERT_TRUE(Release("a").IsNone()); + ASSERT_TRUE(Allocate("b", "new-net").IsNone()); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {"new-net"}}})); + + EXPECT_FALSE(WaitUpdates(1, 3 * cRemoveTimeout)); + + NetworkParams sameParams; + + ASSERT_TRUE(mNetworkManager->GetNodeNetworkParams("new-net", "node", sameParams).IsNone()); + EXPECT_EQ(sameParams.mVlanID, params.mVlanID); + EXPECT_EQ(sameParams.mSubnet, params.mSubnet); +} + +TEST_F(CMUnitNetworksRemoveTimeoutTest, RestoredNetworkWithoutInstancesRemovedAfterTimeout) +{ + ASSERT_TRUE(Allocate("a", "target-net").IsNone()); + + InitManager(); + + mNetworkManager->OnNodeSubscribed("node"); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {"requester-net", "target-net", "target-net-2"}}})); + + ASSERT_TRUE(mNetworkManager->Start().IsNone()); + ASSERT_TRUE(WaitUpdates(1)); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {"target-net"}}})); +} + +TEST_F(CMUnitNetworksRemoveTimeoutTest, OtherNodeJoiningDoesNotExtendRemoval) +{ + ExpireRestoredNetworks(); + + NetworkParams params; + + ASSERT_TRUE(mNetworkManager->GetNodeNetworkParams("new-net", "node", params).IsNone()); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {"new-net"}}})); + + std::this_thread::sleep_for(cRemoveTimeout / 2); + + const auto joined = std::chrono::steady_clock::now(); + + ASSERT_TRUE(mNetworkManager->GetNodeNetworkParams("new-net", "node2", params).IsNone()); + EXPECT_TRUE(TakeUpdates().empty()); + + ASSERT_TRUE(WaitUpdates(1)); + EXPECT_LT(std::chrono::steady_clock::now() - joined, cRemoveTimeout); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {}}})); +} + +TEST_F(CMUnitNetworksRemoveTimeoutTest, NoPushAfterStop) +{ + ExpireRestoredNetworks(); + + NetworkParams params; + + ASSERT_TRUE(mNetworkManager->GetNodeNetworkParams("new-net", "node", params).IsNone()); + EXPECT_EQ(TakeUpdates(), UnitNetworksUpdates({{"node", {"new-net"}}})); + + ASSERT_TRUE(mNetworkManager->Stop().IsNone()); + + EXPECT_FALSE(WaitUpdates(1, 3 * cRemoveTimeout)); +} + } // namespace aos::cm::networkmanager diff --git a/src/cm/smcontroller/smcontroller.cpp b/src/cm/smcontroller/smcontroller.cpp index 7c661a5f2..6184edbd8 100644 --- a/src/cm/smcontroller/smcontroller.cpp +++ b/src/cm/smcontroller/smcontroller.cpp @@ -32,24 +32,25 @@ Error SMController::Init(const Config& config, cloudconnection::CloudConnectionI alerts::ReceiverItf& alertsReceiver, SenderItf& logSender, launcher::SenderItf& envVarsStatusSender, monitoring::ReceiverItf& monitoringReceiver, launcher::InstanceStatusReceiverItf& instanceStatusReceiver, nodeinfoprovider::SMInfoReceiverItf& smInfoReceiver, aos::networkmanager::NetworkProviderItf& networkProvider, - bool insecureConn) + cm::networkmanager::UpdateSubscriptionListenerItf& updateSubscriptionListener, bool insecureConn) { LOG_DBG() << "Init SM controller"; - mConfig = config; - mCloudConnection = &cloudConnection; - mCertProvider = &certProvider; - mCertLoader = &certLoader; - mCryptoProvider = &cryptoProvider; - mBlobInfoProvider = &blobInfoProvider; - mAlertsReceiver = &alertsReceiver; - mLogSender = &logSender; - mEnvVarsStatusSender = &envVarsStatusSender; - mMonitoringReceiver = &monitoringReceiver; - mInstanceStatusReceiver = &instanceStatusReceiver; - mSMInfoReceiver = &smInfoReceiver; - mNetworkProvider = &networkProvider; - mInsecureConn = insecureConn; + mConfig = config; + mCloudConnection = &cloudConnection; + mCertProvider = &certProvider; + mCertLoader = &certLoader; + mCryptoProvider = &cryptoProvider; + mBlobInfoProvider = &blobInfoProvider; + mAlertsReceiver = &alertsReceiver; + mLogSender = &logSender; + mEnvVarsStatusSender = &envVarsStatusSender; + mMonitoringReceiver = &monitoringReceiver; + mInstanceStatusReceiver = &instanceStatusReceiver; + mSMInfoReceiver = &smInfoReceiver; + mNetworkProvider = &networkProvider; + mUpdateSubscriptionListener = &updateSubscriptionListener; + mInsecureConn = insecureConn; return ErrorEnum::eNone; } @@ -594,8 +595,14 @@ grpc::Status SMController::SubscribeInstanceNetworkUpdates(grpc::ServerContext* LOG_DBG() << "SubscribeInstanceNetworkUpdates" << Log::Field("nodeID", nodeID.c_str()); { - std::lock_guard lock {mStreamMutex}; - mNetworkUpdateStreams[nodeID] = {context, writer}; + std::lock_guard subscriptionLock {mSubscriptionMutex}; + + { + std::lock_guard lock {mStreamMutex}; + mNetworkUpdateStreams[nodeID] = {context, writer}; + } + + mUpdateSubscriptionListener->OnNodeSubscribed(nodeID.c_str()); } { @@ -606,6 +613,10 @@ grpc::Status SMController::SubscribeInstanceNetworkUpdates(grpc::ServerContext* } } + std::lock_guard subscriptionLock {mSubscriptionMutex}; + + auto active = false; + { std::lock_guard lock {mStreamMutex}; @@ -613,9 +624,15 @@ grpc::Status SMController::SubscribeInstanceNetworkUpdates(grpc::ServerContext* auto it = mNetworkUpdateStreams.find(nodeID); if (it != mNetworkUpdateStreams.end() && it->second.mWriter == writer) { mNetworkUpdateStreams.erase(it); + + active = true; } } + if (active) { + mUpdateSubscriptionListener->OnNodeUnsubscribed(nodeID.c_str()); + } + LOG_DBG() << "SubscribeInstanceNetworkUpdates disconnected" << Log::Field("nodeID", nodeID.c_str()); return grpc::Status::OK; @@ -676,4 +693,26 @@ void SMController::OnPendingFirewallUpdate( } } +void SMController::OnUnitNetworksUpdate(const String& nodeID, const Array>& networkIDs) +{ + std::lock_guard lock {mStreamMutex}; + + auto it = mNetworkUpdateStreams.find(nodeID.CStr()); + if (it == mNetworkUpdateStreams.end()) { + LOG_WRN() << "No stream writer for node" << Log::Field("nodeID", nodeID); + return; + } + + servicemanager::v5::InstanceNetworkUpdateNotification notification; + auto* unitUpdate = notification.mutable_unit_networks_update(); + + for (const auto& networkID : networkIDs) { + unitUpdate->add_network_ids(networkID.CStr()); + } + + if (!it->second.mWriter->Write(notification)) { + LOG_ERR() << "Failed to write unit networks update to stream" << Log::Field("nodeID", nodeID); + } +} + } // namespace aos::cm::smcontroller diff --git a/src/cm/smcontroller/smcontroller.hpp b/src/cm/smcontroller/smcontroller.hpp index 5a5d61b7e..eb64c19b3 100644 --- a/src/cm/smcontroller/smcontroller.hpp +++ b/src/cm/smcontroller/smcontroller.hpp @@ -32,6 +32,8 @@ #include #include +#include + #include "config.hpp" #include "smhandler.hpp" @@ -63,6 +65,8 @@ class SMController : public SMControllerItf, * @param monitoringReceiver monitoring receiver. * @param instanceStatusReceiver instance status receiver. * @param smInfoReceiver SM info receiver. + * @param networkProvider network provider. + * @param updateSubscriptionListener network update subscription listener. * @param insecureConn true if insecure connection is used. * @return Error. */ @@ -72,7 +76,7 @@ class SMController : public SMControllerItf, alerts::ReceiverItf& alertsReceiver, SenderItf& logSender, launcher::SenderItf& envVarsStatusSender, monitoring::ReceiverItf& monitoringReceiver, launcher::InstanceStatusReceiverItf& instanceStatusReceiver, nodeinfoprovider::SMInfoReceiverItf& smInfoReceiver, aos::networkmanager::NetworkProviderItf& networkProvider, - bool insecureConn = false); + cm::networkmanager::UpdateSubscriptionListenerItf& updateSubscriptionListener, bool insecureConn = false); /** * Starts the SM controller. @@ -172,6 +176,14 @@ class SMController : public SMControllerItf, void OnPendingFirewallUpdate( const String& nodeID, const aos::networkmanager::PendingFirewallUpdate& update) override; + /** + * Called when the set of networks of the unit changes and the node must be notified. + * + * @param nodeID node ID to notify. + * @param networkIDs IDs of the unit networks. + */ + void OnUnitNetworksUpdate(const String& nodeID, const Array>& networkIDs) override; + private: static constexpr Duration cReconnectRetryTimeout = Time::cSeconds * 10; @@ -241,20 +253,21 @@ class SMController : public SMControllerItf, void ScheduleRestart(); void OnRestartTimer(); - Config mConfig {}; - cloudconnection::CloudConnectionItf* mCloudConnection {}; - crypto::CertLoaderItf* mCertLoader {}; - crypto::x509::ProviderItf* mCryptoProvider {}; - aos::iamclient::CertProviderItf* mCertProvider {}; - common::imagemanager::BlobInfoProviderItf* mBlobInfoProvider {}; - alerts::ReceiverItf* mAlertsReceiver {}; - SenderItf* mLogSender {}; - launcher::SenderItf* mEnvVarsStatusSender {}; - monitoring::ReceiverItf* mMonitoringReceiver {}; - launcher::InstanceStatusReceiverItf* mInstanceStatusReceiver {}; - nodeinfoprovider::SMInfoReceiverItf* mSMInfoReceiver {}; - aos::networkmanager::NetworkProviderItf* mNetworkProvider {}; - bool mInsecureConn {}; + Config mConfig {}; + cloudconnection::CloudConnectionItf* mCloudConnection {}; + crypto::CertLoaderItf* mCertLoader {}; + crypto::x509::ProviderItf* mCryptoProvider {}; + aos::iamclient::CertProviderItf* mCertProvider {}; + common::imagemanager::BlobInfoProviderItf* mBlobInfoProvider {}; + alerts::ReceiverItf* mAlertsReceiver {}; + SenderItf* mLogSender {}; + launcher::SenderItf* mEnvVarsStatusSender {}; + monitoring::ReceiverItf* mMonitoringReceiver {}; + launcher::InstanceStatusReceiverItf* mInstanceStatusReceiver {}; + nodeinfoprovider::SMInfoReceiverItf* mSMInfoReceiver {}; + aos::networkmanager::NetworkProviderItf* mNetworkProvider {}; + cm::networkmanager::UpdateSubscriptionListenerItf* mUpdateSubscriptionListener {}; + bool mInsecureConn {}; std::unique_ptr mServer; std::mutex mMutex; @@ -271,6 +284,7 @@ class SMController : public SMControllerItf, grpc::ServerWriter* mWriter {}; }; + std::mutex mSubscriptionMutex; std::mutex mStreamMutex; std::condition_variable mStreamCV; std::unordered_map mNetworkUpdateStreams; diff --git a/src/cm/smcontroller/tests/smcontroller.cpp b/src/cm/smcontroller/tests/smcontroller.cpp index 160b2e065..62daa5659 100644 --- a/src/cm/smcontroller/tests/smcontroller.cpp +++ b/src/cm/smcontroller/tests/smcontroller.cpp @@ -4,10 +4,14 @@ * SPDX-License-Identifier: Apache-2.0 */ +#include + +#include #include #include +#include #include #include @@ -46,7 +50,7 @@ class SMControllerTest : public Test { auto err = mSMController.Init(mConfig, mCloudConnection, mCertProvider, mCertLoader, mX509Provider, mBlobInfoProvider, mAlertsReceiver, mSMControllerSender, mLauncherSender, mMonitoringReceiver, - mInstanceStatusReceiver, mSMInfoReceiver, mNetworkProvider, true); + mInstanceStatusReceiver, mSMInfoReceiver, mNetworkProvider, mUpdateSubscriptionListener, true); ASSERT_TRUE(err.IsNone()) << err.Message(); err = mSMController.Start(); @@ -104,6 +108,8 @@ class SMControllerTest : public Test { launcher::InstanceStatusReceiverStub mInstanceStatusReceiver; nodeinfoprovider::SMInfoReceiverStub mSMInfoReceiver; NetworkProviderStub mNetworkProvider; + + NiceMock mUpdateSubscriptionListener; }; /*********************************************************************************************************************** @@ -997,4 +1003,121 @@ TEST_F(SMControllerTest, SubscribeInstanceNetworkUpdates_ReceivesPendingFirewall EXPECT_TRUE(err.IsNone()) << err.Message(); } +TEST_F(SMControllerTest, SubscribeInstanceNetworkUpdates_ReceivesUnitNetworksUpdate) +{ + SMClientStub client; + + auto err = client.Init(cMainNodeID); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = client.Start(mConfig.mCMServerURL); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = mSMInfoReceiver.WaitSMInfo(cMainNodeID); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = client.SubscribeInstanceNetworkUpdates(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + + StaticArray, 2> networkIDs; + networkIDs.PushBack("network1"); + networkIDs.PushBack("network2"); + + mSMController.OnUnitNetworksUpdate(cMainNodeID, networkIDs); + + err = client.WaitUnitNetworksUpdate(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + EXPECT_TRUE(client.GetReceivedUpdates().empty()); + + auto& received = client.GetReceivedUnitNetworksUpdates(); + ASSERT_EQ(received.size(), 1); + ASSERT_EQ(received[0].network_ids_size(), 2); + EXPECT_EQ(received[0].network_ids(0), "network1"); + EXPECT_EQ(received[0].network_ids(1), "network2"); + + err = client.Stop(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = mSMInfoReceiver.WaitDisconnect(cMainNodeID); + EXPECT_TRUE(err.IsNone()) << err.Message(); +} + +TEST_F(SMControllerTest, SubscribeInstanceNetworkUpdates_NotifiesSubscriptionListener) +{ + std::promise subscribed; + std::promise unsubscribed; + + EXPECT_CALL(mUpdateSubscriptionListener, OnNodeSubscribed(String(cMainNodeID))).WillOnce(Invoke([&](const String&) { + subscribed.set_value(); + })); + EXPECT_CALL(mUpdateSubscriptionListener, OnNodeUnsubscribed(String(cMainNodeID))) + .WillOnce(Invoke([&](const String&) { unsubscribed.set_value(); })); + + SMClientStub client; + + auto err = client.Init(cMainNodeID); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = client.Start(mConfig.mCMServerURL); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = mSMInfoReceiver.WaitSMInfo(cMainNodeID); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = client.SubscribeInstanceNetworkUpdates(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + ASSERT_EQ(subscribed.get_future().wait_for(std::chrono::seconds(5)), std::future_status::ready); + + err = client.Stop(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + ASSERT_EQ(unsubscribed.get_future().wait_for(std::chrono::seconds(5)), std::future_status::ready); + + err = mSMInfoReceiver.WaitDisconnect(cMainNodeID); + EXPECT_TRUE(err.IsNone()) << err.Message(); +} + +TEST_F(SMControllerTest, SubscribeInstanceNetworkUpdates_ListenerPushesUnitNetworksOnSubscribe) +{ + EXPECT_CALL(mUpdateSubscriptionListener, OnNodeSubscribed(String(cMainNodeID))) + .WillOnce(Invoke([this](const String& nodeID) { + StaticArray, 1> networkIDs; + networkIDs.PushBack("network1"); + + mSMController.OnUnitNetworksUpdate(nodeID, networkIDs); + })); + + SMClientStub client; + + auto err = client.Init(cMainNodeID); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = client.Start(mConfig.mCMServerURL); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = mSMInfoReceiver.WaitSMInfo(cMainNodeID); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = client.SubscribeInstanceNetworkUpdates(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = client.WaitUnitNetworksUpdate(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + auto& received = client.GetReceivedUnitNetworksUpdates(); + ASSERT_EQ(received.size(), 1); + ASSERT_EQ(received[0].network_ids_size(), 1); + EXPECT_EQ(received[0].network_ids(0), "network1"); + + err = client.Stop(); + ASSERT_TRUE(err.IsNone()) << err.Message(); + + err = mSMInfoReceiver.WaitDisconnect(cMainNodeID); + EXPECT_TRUE(err.IsNone()) << err.Message(); +} + } // namespace aos::cm::smcontroller diff --git a/src/cm/smcontroller/tests/stubs/smclientstub.hpp b/src/cm/smcontroller/tests/stubs/smclientstub.hpp index ddadaceb7..2c6653905 100644 --- a/src/cm/smcontroller/tests/stubs/smclientstub.hpp +++ b/src/cm/smcontroller/tests/stubs/smclientstub.hpp @@ -142,6 +142,12 @@ class SMClientStub { mReceivedUpdates.push_back(notification.pending_firewall_update()); mNetworkUpdateCV.notify_all(); } + + if (notification.has_unit_networks_update()) { + std::lock_guard lock {mMutex}; + mReceivedUnitNetworksUpdates.push_back(notification.unit_networks_update()); + mNetworkUpdateCV.notify_all(); + } } }); @@ -164,6 +170,22 @@ class SMClientStub { return mReceivedUpdates; } + Error WaitUnitNetworksUpdate(std::chrono::seconds timeout = std::chrono::seconds(5)) + { + std::unique_lock lock {mMutex}; + + if (!mNetworkUpdateCV.wait_for(lock, timeout, [this]() { return !mReceivedUnitNetworksUpdates.empty(); })) { + return AOS_ERROR_WRAP(Error(ErrorEnum::eTimeout, "timeout waiting for unit networks update")); + } + + return ErrorEnum::eNone; + } + + const std::vector& GetReceivedUnitNetworksUpdates() const + { + return mReceivedUnitNetworksUpdates; + } + void SendOutgoingMessage(const servicemanager::v5::SMOutgoingMessages& msg) { std::lock_guard lock {mMutex}; @@ -637,6 +659,7 @@ class SMClientStub { std::condition_variable mCloudConnectionCV; std::condition_variable mNetworkUpdateCV; std::vector mReceivedUpdates; + std::vector mReceivedUnitNetworksUpdates; }; } // namespace aos::cm::smcontroller diff --git a/src/sm/networkmanager/dnsname.hpp b/src/sm/networkmanager/dnsname.hpp index a99af4494..a2ec52117 100644 --- a/src/sm/networkmanager/dnsname.hpp +++ b/src/sm/networkmanager/dnsname.hpp @@ -63,7 +63,7 @@ class DNSName : public DNSNameItf, private NonCopyable { Error RemoveServer(const String& networkID) override; private: - static constexpr auto cDnsmasqBinary = "/usr/sbin/dnsmasq"; + static constexpr auto cDnsmasqBinary = "dnsmasq"; static constexpr auto cPidFileName = "pidfile"; static constexpr auto cHostsFileName = "addnhosts"; diff --git a/src/sm/networkmanager/networkmanager.md b/src/sm/networkmanager/networkmanager.md index aa311c5cc..ffd12019b 100644 --- a/src/sm/networkmanager/networkmanager.md +++ b/src/sm/networkmanager/networkmanager.md @@ -151,9 +151,11 @@ sequenceDiagram participant BW as Bandwidth participant TM as TrafficMonitor - Note over NM: StartInstanceNetwork, first instance on network + Note over NM: Network is created: it is a unit network or gets its first instance NM ->> IF: CreateBridge / CreateVlan NM ->> FW: AddMasquerade(subnet, uplink) + + Note over NM: StartInstanceNetwork, first instance on network NM ->> DNS: CreateServer(networkID) Note over NM: StartInstanceNetwork, every instance @@ -175,6 +177,8 @@ sequenceDiagram Note over NM: StopInstanceNetwork, last instance on network NM ->> DNS: RemoveServer(networkID) + + Note over NM: Network is removed: it has no instances and is not a unit network NM ->> FW: RemoveMasquerade(subnet, uplink) NM ->> IF: DeleteLink(bridge), DeleteLink(vlan) ``` @@ -317,6 +321,6 @@ corresponding chain is switched to a drop rule until the next period starts. - Linux with network namespaces, nftables and tc support; - `libnftables` and `libnl` (route, tc) at runtime; -- a dnsmasq binary at `/usr/sbin/dnsmasq`; +- a `dnsmasq` binary available in `PATH`; - a writable DNS storage directory (`/dns`); - `CAP_NET_ADMIN` for links, nftables and tc, `CAP_SYS_ADMIN` for network namespaces. diff --git a/src/sm/networkmanager/tests/dnsname.cpp b/src/sm/networkmanager/tests/dnsname.cpp index 1eba260cf..63728369f 100644 --- a/src/sm/networkmanager/tests/dnsname.cpp +++ b/src/sm/networkmanager/tests/dnsname.cpp @@ -28,7 +28,7 @@ using namespace testing; namespace { -constexpr auto cDnsmasqBinary = "/usr/sbin/dnsmasq"; +constexpr auto cDnsmasqBinary = "dnsmasq"; constexpr Poco::Process::PID cSpawnedPID = 12345; constexpr Poco::Process::PID cAdoptPID = 4242; @@ -128,7 +128,7 @@ TEST_F(DNSNameTest, CreateServerAdoptsAlivePidFile) WritePidFile(storageDir, cAdoptPID); - const std::string cmdline = "/usr/sbin/dnsmasq --pid-file=" + storageDir.string() + "/pidfile"; + const std::string cmdline = "dnsmasq --pid-file=" + storageDir.string() + "/pidfile"; EXPECT_CALL(mSpawner, IsAlive(cAdoptPID)).WillOnce(Return(true)); EXPECT_CALL(mSpawner, GetCmdLine(cAdoptPID)) diff --git a/src/sm/smclient/smclient.cpp b/src/sm/smclient/smclient.cpp index 7ccc22800..555ae0c8e 100644 --- a/src/sm/smclient/smclient.cpp +++ b/src/sm/smclient/smclient.cpp @@ -933,6 +933,25 @@ Error SMClient::UnsubscribeListener(ConnectListenerItf& listener) return ErrorEnum::eNone; } +void SMClient::HandleUnitNetworksUpdate(const smproto::UnitNetworksUpdate& update) +{ + StaticArray, cMaxNumOwners> networkIDs; + + for (const auto& networkID : update.network_ids()) { + if (auto err = networkIDs.EmplaceBack(); !err.IsNone()) { + LOG_ERR() << "Failed to convert unit networks update" << Log::Field(err); + return; + } + + if (auto err = networkIDs.Back().Assign(networkID.c_str()); !err.IsNone()) { + LOG_ERR() << "Failed to convert unit networks update" << Log::Field(err); + return; + } + } + + mNetworkUpdateHandler->OnUnitNetworksUpdate(mNodeID.c_str(), networkIDs); +} + void SMClient::StartNetworkUpdateSubscription() { mNetworkUpdateThread = std::thread([this]() { @@ -971,6 +990,8 @@ void SMClient::StartNetworkUpdateSubscription() } mNetworkUpdateHandler->OnPendingFirewallUpdate(mNodeID.c_str(), update); + } else if (notification.has_unit_networks_update()) { + HandleUnitNetworksUpdate(notification.unit_networks_update()); } } diff --git a/src/sm/smclient/smclient.hpp b/src/sm/smclient/smclient.hpp index e10ef45fd..ef867d7b2 100644 --- a/src/sm/smclient/smclient.hpp +++ b/src/sm/smclient/smclient.hpp @@ -271,6 +271,7 @@ class SMClient : public SMClientItf, public aos::iamclient::CertKeyListenerItf, void ConnectionLoop() noexcept; void HandleIncomingMessages(); void StartNetworkUpdateSubscription(); + void HandleUnitNetworksUpdate(const smproto::UnitNetworksUpdate& update); Error ProcessGetNodeConfigStatus(); Error ProcessCheckNodeConfig(const smproto::CheckNodeConfig& checkConfig); diff --git a/src/sm/smclient/tests/smclient.cpp b/src/sm/smclient/tests/smclient.cpp index 5e820514d..60c90d86f 100644 --- a/src/sm/smclient/tests/smclient.cpp +++ b/src/sm/smclient/tests/smclient.cpp @@ -1489,6 +1489,155 @@ TEST_F(SMClientTest, SubscribeInstanceNetworkUpdates_ReceivesUpdate) ASSERT_TRUE(err.IsNone()) << "Stop failed"; } +TEST_F(SMClientTest, SubscribeInstanceNetworkUpdates_ReceivesUnitNetworksUpdate) +{ + auto server = std::make_unique(GetConfig().mCMServerURL); + auto client = std::make_unique(); + + auto runtimes = CreateRuntimeInfos(); + auto resources = CreateResourceInfos(); + auto statuses = CreateInstanceStatuses(); + + EXPECT_CALL(mTLSCredentials, GetTLSClientCredentials()) + .WillRepeatedly(Return(aos::RetWithError> { + grpc::InsecureChannelCredentials(), aos::ErrorEnum::eNone})); + EXPECT_CALL(mRuntimeInfoProvider, GetRuntimesInfos(_)).WillRepeatedly(Invoke([&runtimes](Array& out) { + for (const auto& item : *runtimes) { + out.PushBack(item); + } + return ErrorEnum::eNone; + })); + EXPECT_CALL(mResourceInfoProvider, GetResourcesInfos(_)) + .WillRepeatedly(Invoke([&resources](Array& out) { + for (const auto& item : *resources) { + out.PushBack(item); + } + return ErrorEnum::eNone; + })); + EXPECT_CALL(mInstanceStatusProvider, GetInstancesStatuses(_)) + .WillRepeatedly(Invoke([&statuses](Array& out) { + for (const auto& item : *statuses) { + out.PushBack(item); + } + return ErrorEnum::eNone; + })); + + EXPECT_CALL(*server, OnSMInfo(_)).Times(1); + EXPECT_CALL(*server, OnNodeInstancesStatus(_)).Times(1); + + auto err = client->Init(GetConfig(), "test-node", mTLSCredentials, mCertProvider, mRuntimeInfoProvider, + mResourceInfoProvider, mNodeConfigHandler, mLauncher, mLogProvider, mMonitoring, mInstanceStatusProvider, + mJSONProvider, mPendingUpdateHandler, false); + ASSERT_TRUE(err.IsNone()) << "Init failed"; + + err = client->Start(); + ASSERT_TRUE(err.IsNone()) << "Start failed"; + + server->WaitRegistered(); + server->WaitSMInfo(); + server->WaitNodeInstancesStatus(); + + ASSERT_TRUE(server->WaitNetworkUpdateSubscribed()); + + smproto::UnitNetworksUpdate protoUpdate; + protoUpdate.add_network_ids("network1"); + protoUpdate.add_network_ids("network2"); + + std::promise handlerCalled; + + EXPECT_CALL(mPendingUpdateHandler, OnUnitNetworksUpdate(_, _)) + .WillOnce(Invoke([&](const String& nodeID, const Array>& networkIDs) { + EXPECT_EQ(nodeID, "test-node"); + ASSERT_EQ(networkIDs.Size(), 2); + EXPECT_EQ(networkIDs[0], "network1"); + EXPECT_EQ(networkIDs[1], "network2"); + handlerCalled.set_value(); + })); + + server->SendUnitNetworksUpdate(protoUpdate); + + ASSERT_EQ(handlerCalled.get_future().wait_for(std::chrono::seconds(5)), std::future_status::ready); + + err = client->Stop(); + ASSERT_TRUE(err.IsNone()) << "Stop failed"; +} + +TEST_F(SMClientTest, SubscribeInstanceNetworkUpdates_SkipsInvalidUnitNetworksUpdate) +{ + auto server = std::make_unique(GetConfig().mCMServerURL); + auto client = std::make_unique(); + + auto runtimes = CreateRuntimeInfos(); + auto resources = CreateResourceInfos(); + auto statuses = CreateInstanceStatuses(); + + EXPECT_CALL(mTLSCredentials, GetTLSClientCredentials()) + .WillRepeatedly(Return(aos::RetWithError> { + grpc::InsecureChannelCredentials(), aos::ErrorEnum::eNone})); + EXPECT_CALL(mRuntimeInfoProvider, GetRuntimesInfos(_)).WillRepeatedly(Invoke([&runtimes](Array& out) { + for (const auto& item : *runtimes) { + out.PushBack(item); + } + return ErrorEnum::eNone; + })); + EXPECT_CALL(mResourceInfoProvider, GetResourcesInfos(_)) + .WillRepeatedly(Invoke([&resources](Array& out) { + for (const auto& item : *resources) { + out.PushBack(item); + } + return ErrorEnum::eNone; + })); + EXPECT_CALL(mInstanceStatusProvider, GetInstancesStatuses(_)) + .WillRepeatedly(Invoke([&statuses](Array& out) { + for (const auto& item : *statuses) { + out.PushBack(item); + } + return ErrorEnum::eNone; + })); + + EXPECT_CALL(*server, OnSMInfo(_)).Times(1); + EXPECT_CALL(*server, OnNodeInstancesStatus(_)).Times(1); + + auto err = client->Init(GetConfig(), "test-node", mTLSCredentials, mCertProvider, mRuntimeInfoProvider, + mResourceInfoProvider, mNodeConfigHandler, mLauncher, mLogProvider, mMonitoring, mInstanceStatusProvider, + mJSONProvider, mPendingUpdateHandler, false); + ASSERT_TRUE(err.IsNone()) << "Init failed"; + + err = client->Start(); + ASSERT_TRUE(err.IsNone()) << "Start failed"; + + server->WaitRegistered(); + server->WaitSMInfo(); + server->WaitNodeInstancesStatus(); + + ASSERT_TRUE(server->WaitNetworkUpdateSubscribed()); + + smproto::UnitNetworksUpdate invalidUpdate; + invalidUpdate.add_network_ids("network1"); + invalidUpdate.add_network_ids(std::string(cIDLen + 1, 'a')); + + smproto::UnitNetworksUpdate validUpdate; + validUpdate.add_network_ids("network3"); + + std::promise handlerCalled; + + EXPECT_CALL(mPendingUpdateHandler, OnUnitNetworksUpdate(_, _)) + .WillOnce(Invoke([&](const String& nodeID, const Array>& networkIDs) { + EXPECT_EQ(nodeID, "test-node"); + ASSERT_EQ(networkIDs.Size(), 1); + EXPECT_EQ(networkIDs[0], "network3"); + handlerCalled.set_value(); + })); + + server->SendUnitNetworksUpdate(invalidUpdate); + server->SendUnitNetworksUpdate(validUpdate); + + ASSERT_EQ(handlerCalled.get_future().wait_for(std::chrono::seconds(5)), std::future_status::ready); + + err = client->Stop(); + ASSERT_TRUE(err.IsNone()) << "Stop failed"; +} + TEST_F(SMClientTest, SyncNetworkState_SendsStateToServer) { auto server = std::make_unique(GetConfig().mCMServerURL); diff --git a/src/sm/smclient/tests/stubs/smservicestub.hpp b/src/sm/smclient/tests/stubs/smservicestub.hpp index 2eadba111..b20542e79 100644 --- a/src/sm/smclient/tests/stubs/smservicestub.hpp +++ b/src/sm/smclient/tests/stubs/smservicestub.hpp @@ -195,6 +195,17 @@ class SMServiceStub final : public smproto::SMService::Service, public smproto:: } } + void SendUnitNetworksUpdate(const smproto::UnitNetworksUpdate& update) + { + std::lock_guard lock {mLock}; + + if (mNetworkUpdateWriter) { + smproto::InstanceNetworkUpdateNotification notification; + *notification.mutable_unit_networks_update() = update; + mNetworkUpdateWriter->Write(notification); + } + } + bool WaitNetworkUpdateSubscribed(std::chrono::seconds timeout = std::chrono::seconds(5)) { std::unique_lock lock {mLock};