diff --git a/src/core/common/networkmanager/itf/pendingupdatehandler.hpp b/src/core/common/networkmanager/itf/pendingupdatehandler.hpp index 143d9afc1..a32586391 100644 --- a/src/core/common/networkmanager/itf/pendingupdatehandler.hpp +++ b/src/core/common/networkmanager/itf/pendingupdatehandler.hpp @@ -51,9 +51,10 @@ struct PendingFirewallUpdate { }; /** - * Handler for pending firewall update notifications. + * Handler for CM -> SM network notifications: pending firewall updates and unit networks updates. * CM side: CM NetworkManager notifies SMController which pushes to stream. - * SM side: SM NetworkManager implements this to apply resolved pending rules. + * SM side: SM NetworkManager implements this to apply resolved pending rules and to keep the node networks in sync + * with the networks of the unit. */ class PendingUpdateHandlerItf { public: @@ -69,6 +70,17 @@ class PendingUpdateHandlerItf { * @param update pending firewall update. */ virtual void OnPendingFirewallUpdate(const String& nodeID, const PendingFirewallUpdate& update) = 0; + + /** + * Called with the full set of network IDs that exist in the unit. + * + * The set is complete, not a delta: a receiver has to replace the unit networks it holds with this set. Sent when + * SM subscribes and whenever the set changes. + * + * @param nodeID node ID the update is addressed to. + * @param networkIDs IDs of all networks of the unit. + */ + virtual void OnUnitNetworksUpdate(const String& nodeID, const Array>& networkIDs) = 0; }; /** @}*/ diff --git a/src/core/common/networkmanager/networkmanager.md b/src/core/common/networkmanager/networkmanager.md index 190fe4647..9c3e7eaf6 100644 --- a/src/core/common/networkmanager/networkmanager.md +++ b/src/core/common/networkmanager/networkmanager.md @@ -2,7 +2,7 @@ This document describes the network manager interfaces shared between CM (Communication Manager) and SM (Service Manager). They define the contract for allocating and releasing network resources, synchronizing network state on -(re)connect and delivering deferred firewall rule updates. +(re)connect, delivering deferred firewall rule updates and announcing the networks of the unit. The overall networking architecture is described in the public documentation: @@ -21,6 +21,10 @@ CM is the allocator: it hands out subnets, IP addresses and per-instance firewal across the unit. SM is the runtime owner: it asks CM what an instance network should look like and builds it on the node. +CM also keeps the set of networks that exist in the unit and announces it to every node. SM keeps every network of +this set present on its node, whether or not the node runs instances of it, so instances of different networks on +different nodes can reach each other and an instance can move to another node without waiting for its network. + The interfaces are placed in `common` because both sides depend on them: - [aos::networkmanager::NetworkProviderItf](itf/networkprovider.hpp) - SM -> CM requests. On the SM side it is @@ -54,6 +58,7 @@ classDiagram class PendingUpdateHandlerItf ["aos::networkmanager::PendingUpdateHandlerItf"] { <> OnPendingFirewallUpdate() + OnUnitNetworksUpdate() } %% SM -> CM requests @@ -73,7 +78,8 @@ Network provider interface used by SM to request network resources from CM. ### GetNodeNetworkParams Returns node network parameters (`NetworkParams`: subnet, bridge IP, VLAN ID) for the given network and node. SM calls -it once per network when the first instance of that network is created on the node. +it once per network when the network is not known on the node yet: when CM announces it in the unit networks (see +[Unit networks](#unit-networks)) or when the first instance of that network is created on the node. ### AllocateInstanceNetwork @@ -91,7 +97,8 @@ Releases instance network resources on CM. SM calls it when the instance network ### ReleaseNodeNetwork -Releases node network resources on CM. SM calls it when the last instance of the network on the node is released. +Releases node network resources on CM. SM calls it when the network is not in the unit networks and the node has no +instances of it: when the network leaves the unit networks or when its last instance on the node is released. ### SyncNetworkState @@ -102,7 +109,7 @@ not drift apart after restarts or connection interruptions. ## aos::networkmanager::PendingUpdateHandlerItf -Handler interface for deferred firewall update notifications. +Handler interface for CM -> SM notifications: deferred firewall updates and unit networks updates. ### OnPendingFirewallUpdate @@ -111,6 +118,11 @@ identifier and the instance's whole current rule set, resolved from all of its a target addresses. The receiver has to replace the rules it holds for the instance with these, so rules to released or re-addressed targets are removed and rules to new addresses are added. +### OnUnitNetworksUpdate + +Called with the IDs of all networks that exist in the unit. The set is complete, not a delta: the receiver replaces the +set it holds with it. CM sends it when SM subscribes and whenever the set changes. + ## Deferred firewall rules When an instance has allowed connections to a target (item ID or hostname) that has no allocated instance yet, CM @@ -138,6 +150,37 @@ sequenceDiagram SM_A ->> SM_A: replace rules, update instance1 firewall ``` +## Unit networks + +CM announces the networks that exist in the unit to every node via `PendingUpdateHandlerItf::OnUnitNetworksUpdate`. SM +stays the initiator of node network creation: for every announced network it does not have yet, it requests the node +network parameters with `GetNodeNetworkParams` and creates the network links. When a network leaves the set, SM releases +it with `ReleaseNodeNetwork` once the node has no instances of it. + +```mermaid +sequenceDiagram + participant CM + participant SM_A as SM (node A) + participant SM_B as SM (node B) + + CM ->> SM_A: OnUnitNetworksUpdate(nodeA, [network1, network2]) + CM ->> SM_B: OnUnitNetworksUpdate(nodeB, [network1, network2]) + + loop announced networks not known on the node + SM_B ->> CM: GetNodeNetworkParams(network2, nodeB) + CM -->> SM_B: NetworkParams + SM_B ->> SM_B: create bridge/VLAN + end + + CM ->> SM_A: OnUnitNetworksUpdate(nodeA, [network1]) + CM ->> SM_B: OnUnitNetworksUpdate(nodeB, [network1]) + + alt no instances of network2 on node B + SM_B ->> SM_B: remove bridge/VLAN + SM_B ->> CM: ReleaseNodeNetwork(network2, nodeB) + end +``` + ## Types The data types used by the interfaces are defined in [core/common/types/network.hpp](../types/network.hpp): diff --git a/src/core/common/networkmanager/tests/mocks/pendingupdatehandlermock.hpp b/src/core/common/networkmanager/tests/mocks/pendingupdatehandlermock.hpp index affa6093b..0f16dcd6c 100644 --- a/src/core/common/networkmanager/tests/mocks/pendingupdatehandlermock.hpp +++ b/src/core/common/networkmanager/tests/mocks/pendingupdatehandlermock.hpp @@ -15,6 +15,8 @@ class PendingUpdateHandlerMock : public aos::networkmanager::PendingUpdateHandle public: MOCK_METHOD(void, OnPendingFirewallUpdate, (const aos::String& nodeID, const aos::networkmanager::PendingFirewallUpdate& update), (override)); + MOCK_METHOD(void, OnUnitNetworksUpdate, + (const aos::String& nodeID, const aos::Array>& networkIDs), (override)); }; #endif diff --git a/src/core/sm/networkmanager/itf/dnsname.hpp b/src/core/sm/networkmanager/itf/dnsname.hpp index 3fc7964ff..34debc510 100644 --- a/src/core/sm/networkmanager/itf/dnsname.hpp +++ b/src/core/sm/networkmanager/itf/dnsname.hpp @@ -87,10 +87,11 @@ class DNSNameItf { /** * Removes orphan DNS servers left over from a previous SM lifetime. * Tears down any dnsmasq state whose networkID is not in - * @p knownNetworkIDs — networks that were released while SM was down. + * @p knownNetworkIDs — networks that were released while SM was down + * or have no instances. * Called once from NetworkManager::Start, before any CreateServer. * - * @param knownNetworkIDs networkIDs still present in storage. + * @param knownNetworkIDs networkIDs that have stored instances. * @return Error. */ virtual Error RemoveOrphans(const Array>& knownNetworkIDs) = 0; diff --git a/src/core/sm/networkmanager/itf/networkmanager.hpp b/src/core/sm/networkmanager/itf/networkmanager.hpp index 6a2a3074b..2e3ce17b2 100644 --- a/src/core/sm/networkmanager/itf/networkmanager.hpp +++ b/src/core/sm/networkmanager/itf/networkmanager.hpp @@ -109,7 +109,8 @@ class NetworkManagerItf : public SystemTrafficProviderItf, /** * Stops instance network: tears down DNS/bandwidth/firewall/bridge for the * instance, deletes its namespace and monitoring. - * If last running instance on network — clears bridge/VLAN. + * If last running instance on network — removes its DNS server and, unless the network is a unit network, + * clears bridge/VLAN. * Does NOT remove from DB, does NOT call CM. * * @param instanceID instance ID. @@ -120,7 +121,8 @@ class NetworkManagerItf : public SystemTrafficProviderItf, /** * Releases instance network: removes from DB, calls CM ReleaseInstanceNetwork. - * If last instance on network — removes node network info from DB, releases on CM. + * If last instance on network and the network is not a unit network — removes node network info from DB, + * releases on CM. * Requires Stop to be called first. * * @param instanceID instance ID. diff --git a/src/core/sm/networkmanager/networkmanager.cpp b/src/core/sm/networkmanager/networkmanager.cpp index 3f81a439a..eaca7305c 100644 --- a/src/core/sm/networkmanager/networkmanager.cpp +++ b/src/core/sm/networkmanager/networkmanager.cpp @@ -64,6 +64,10 @@ Error NetworkManager::Init(AllocatorItf& allocator, StorageItf& storage, BridgeN if (auto err = mNetworkProviders.Set(networkInfo.mNetworkID, networkInfo); !err.IsNone()) { return AOS_ERROR_WRAP(err); } + + if (auto err = mUnitNetworks.PushBack(networkInfo.mNetworkID); !err.IsNone()) { + return AOS_ERROR_WRAP(err); + } } return ErrorEnum::eNone; @@ -137,11 +141,21 @@ Error NetworkManager::Start() return err; } + err = RestoreUnitNetworks(); + if (!err.IsNone()) { + return err; + } + err = ReconcileInstances(); if (!err.IsNone()) { return err; } + err = RemoveIdleDNSServers(); + if (!err.IsNone()) { + return err; + } + return ErrorEnum::eNone; } @@ -213,6 +227,8 @@ Error NetworkManager::CreateInstanceNetwork( if (auto err = mInstanceNetworkInfos.Emplace(instanceID); !err.IsNone()) { return AOS_ERROR_WRAP(err); } + + mInstanceNetworkInfos.Find(instanceID)->mSecond.mNetworkID = networkID; } Error err; @@ -314,6 +330,10 @@ Error NetworkManager::StartInstanceNetwork(const String& instanceID, const Strin return AOS_ERROR_WRAP(Error(ErrorEnum::eInvalidArgument, "networkID mismatch")); } + if (itInfo->mSecond.mInstanceID.IsEmpty()) { + return AOS_ERROR_WRAP(Error(ErrorEnum::eWrongState, "instance network is being created")); + } + *cachedInfo = itInfo->mSecond; } @@ -337,6 +357,19 @@ Error NetworkManager::StartInstanceNetwork(const String& instanceID, const Strin return err; } + bool dnsServerCreated = false; + + Tie(dnsServerCreated, err) = EnsureDNSServer(networkID); + if (!err.IsNone()) { + return err; + } + + auto cleanupDNSServer = DeferRelease(&instanceID, [this, networkID, dnsServerCreated, &err](const String* id) { + if (!err.IsNone() && dnsServerCreated) { + RemoveUnusedDNSServer(*id, networkID); + } + }); + err = AddInstanceToNetwork(instanceID, networkID, cachedInfo->mNetworkConfig, cachedInfo->mAllocatedParams); if (err.IsNone()) { @@ -505,6 +538,18 @@ Error NetworkManager::StopInstanceNetwork(const String& instanceID, const String return err; } + if (mUnitNetworks.Contains(networkID)) { + LOG_DBG() << "Last running instance on unit network, removing DNS server" + << Log::Field("networkID", networkID); + + if (auto errRemove = RemoveDNSServer(networkID); !errRemove.IsNone()) { + LOG_WRN() << "Failed to remove DNS server" << Log::Field("networkID", networkID) + << Log::Field(errRemove); + } + + return err; + } + auto it = mNetworkProviders.Find(networkID); if (it != mNetworkProviders.end()) { LOG_DBG() << "Last running instance on network, clearing physical network" @@ -543,6 +588,10 @@ Error NetworkManager::ReleaseInstanceNetwork(const String& instanceID, const Str return AOS_ERROR_WRAP(Error(ErrorEnum::eInvalidArgument, "networkID mismatch")); } + if (itInfo->mSecond.mInstanceID.IsEmpty()) { + return AOS_ERROR_WRAP(Error(ErrorEnum::eWrongState, "instance network is being created")); + } + instanceIdent = itInfo->mSecond.mNetworkConfig.mInstanceIdent; found = true; (void)mInstanceNetworkInfos.Remove(instanceID); @@ -562,35 +611,7 @@ Error NetworkManager::ReleaseInstanceNetwork(const String& instanceID, const Str } } - { - LockGuard lock {mMutex}; - - for (const auto& info : mInstanceNetworkInfos) { - if (info.mSecond.mNetworkID == networkID) { - return ErrorEnum::eNone; - } - } - - if (auto runtimeNetwork = mRuntimeCache.Find(networkID); - runtimeNetwork != mRuntimeCache.end() && !runtimeNetwork->mSecond.IsEmpty()) { - return ErrorEnum::eNone; - } - - if (mNetworkProviders.Find(networkID) == mNetworkProviders.end()) { - return ErrorEnum::eNone; - } - - (void)mNetworkProviders.Remove(networkID); - } - - if (auto err = mStorage->RemoveNetworkInfo(networkID); !err.IsNone()) { - LOG_WRN() << "Failed to remove network info from storage" << Log::Field("networkID", networkID) - << Log::Field(err); - } - - if (auto err = mNetworkProvider->ReleaseNodeNetwork(networkID, mNodeID); !err.IsNone()) { - LOG_WRN() << "Failed to release node network on CM" << Log::Field("networkID", networkID) << Log::Field(err); - } + RemoveNodeNetworkIfUnused(networkID); return ErrorEnum::eNone; } @@ -869,6 +890,8 @@ Error NetworkManager::PrepareUpdateItemNetworkParams( Error NetworkManager::EnsureNodeNetwork(const String& networkID) { + LockGuard nodeNetworkLock {mNodeNetworkMutex}; + { LockGuard lock {mMutex}; @@ -1190,6 +1213,65 @@ Error NetworkManager::EnsureNodeNetworkPhysical(const String& networkID) return ErrorEnum::eNone; } +void NetworkManager::RemoveNodeNetworkIfUnused(const String& networkID) +{ + LockGuard nodeNetworkLock {mNodeNetworkMutex}; + + { + LockGuard lock {mMutex}; + + auto it = mNetworkProviders.Find(networkID); + if (it == mNetworkProviders.end()) { + return; + } + + if (IsNodeNetworkInUse(networkID)) { + LOG_DBG() << "Node network is still in use" << Log::Field("networkID", networkID); + + return; + } + + if (mUnitNetworks.Contains(networkID)) { + LOG_DBG() << "Keep unit network" << Log::Field("networkID", networkID); + + return; + } + + if (mPhysicalNetworks.Contains(networkID)) { + if (auto err = ClearNetwork(it->mSecond); !err.IsNone()) { + LOG_WRN() << "Failed to clear network" << Log::Field("networkID", networkID) << Log::Field(err); + } + + (void)mPhysicalNetworks.Remove(networkID); + } + + (void)mNetworkProviders.Remove(networkID); + } + + LOG_DBG() << "Release node network" << Log::Field("networkID", networkID); + + if (auto err = mStorage->RemoveNetworkInfo(networkID); !err.IsNone()) { + LOG_WRN() << "Failed to remove network info from storage" << Log::Field("networkID", networkID) + << Log::Field(err); + } + + if (auto err = mNetworkProvider->ReleaseNodeNetwork(networkID, mNodeID); !err.IsNone()) { + LOG_WRN() << "Failed to release node network on CM" << Log::Field("networkID", networkID) << Log::Field(err); + } +} + +bool NetworkManager::IsNodeNetworkInUse(const String& networkID) const +{ + if (mInstanceNetworkInfos.ContainsIf( + [&networkID](const auto& item) { return item.mSecond.mNetworkID == networkID; })) { + return true; + } + + auto network = mRuntimeCache.Find(networkID); + + return network != mRuntimeCache.end() && !network->mSecond.IsEmpty(); +} + Error NetworkManager::DeleteInstanceNetworkConfig(const String& instanceID, const String& networkID) { StaticString hostIfName; @@ -1493,7 +1575,7 @@ Error NetworkManager::ReconcileInstances() if (alive) { err = InitInstance(entry.mInstanceID, entry.mNetworkID); if (err.IsNone()) { - if (auto dnsErr = AdoptDNSServer(entry.mNetworkID); !dnsErr.IsNone()) { + if (auto dnsErr = EnsureDNSServer(entry.mNetworkID).mError; !dnsErr.IsNone()) { LOG_WRN() << "Failed to adopt DNS server for running instance" << Log::Field("networkID", entry.mNetworkID) << Log::Field(dnsErr); } @@ -1505,7 +1587,7 @@ Error NetworkManager::ReconcileInstances() } } - err = AdoptDNSServer(entry.mNetworkID); + err = EnsureDNSServer(entry.mNetworkID).mError; if (!err.IsNone()) { LOG_WRN() << "Failed to adopt DNS server for leftover cleanup" << Log::Field("networkID", entry.mNetworkID) << Log::Field(err); @@ -1616,8 +1698,12 @@ Error NetworkManager::RemoveDNSOrphans() { LockGuard lock {mMutex}; - for (const auto& [id, _] : mNetworkProviders) { - if (auto err = known->PushBack(id); !err.IsNone()) { + for (const auto& [_, info] : mInstanceNetworkInfos) { + if (known->Contains(info.mNetworkID)) { + continue; + } + + if (auto err = known->PushBack(info.mNetworkID); !err.IsNone()) { return AOS_ERROR_WRAP(err); } } @@ -1630,7 +1716,60 @@ Error NetworkManager::RemoveDNSOrphans() return ErrorEnum::eNone; } -Error NetworkManager::AdoptDNSServer(const String& networkID) +Error NetworkManager::RestoreUnitNetworks() +{ + auto networkIDs = MakeUnique, cMaxNumOwners>>(mAllocator); + if (!networkIDs) { + return AOS_ERROR_WRAP(ErrorEnum::eNoMemory); + } + + { + LockGuard lock {mMutex}; + + *networkIDs = mUnitNetworks; + } + + for (const auto& networkID : *networkIDs) { + LOG_DBG() << "Restore unit network" << Log::Field("networkID", networkID); + + if (auto err = EnsureNodeNetworkPhysical(networkID); !err.IsNone()) { + LOG_ERR() << "Failed to restore unit network" << Log::Field("networkID", networkID) << Log::Field(err); + } + } + + return ErrorEnum::eNone; +} + +Error NetworkManager::RemoveIdleDNSServers() +{ + auto idleNetworks = MakeUnique, cMaxNumOwners>>(mAllocator); + if (!idleNetworks) { + return AOS_ERROR_WRAP(ErrorEnum::eNoMemory); + } + + LockGuard lock {mMutex}; + + for (const auto& [networkID, _] : mDNSServers) { + if (auto network = mRuntimeCache.Find(networkID); + network != mRuntimeCache.end() && !network->mSecond.IsEmpty()) { + continue; + } + + if (auto err = idleNetworks->PushBack(networkID); !err.IsNone()) { + return AOS_ERROR_WRAP(err); + } + } + + for (const auto& networkID : *idleNetworks) { + if (auto err = RemoveDNSServer(networkID); !err.IsNone()) { + LOG_WRN() << "Failed to remove idle DNS server" << Log::Field("networkID", networkID) << Log::Field(err); + } + } + + return ErrorEnum::eNone; +} + +RetWithError NetworkManager::EnsureDNSServer(const String& networkID) { NetworkInfo networkInfo; @@ -1638,21 +1777,23 @@ Error NetworkManager::AdoptDNSServer(const String& networkID) LockGuard lock {mMutex}; if (mDNSServers.Find(networkID) != mDNSServers.end()) { - return ErrorEnum::eNone; + return {false, ErrorEnum::eNone}; } auto it = mNetworkProviders.Find(networkID); if (it == mNetworkProviders.end()) { - return AOS_ERROR_WRAP(Error(ErrorEnum::eNotFound, "network provider not found")); + return {false, AOS_ERROR_WRAP(Error(ErrorEnum::eNotFound, "network provider not found"))}; } networkInfo = it->mSecond; } + LOG_DBG() << "Create DNS server" << Log::Field("networkID", networkID); + DNSServerParams params; if (auto err = PrepareDNSServerParams(networkInfo, params); !err.IsNone()) { - return err; + return {false, err}; } DNSServerItf* handle = nullptr; @@ -1660,13 +1801,46 @@ Error NetworkManager::AdoptDNSServer(const String& networkID) Tie(handle, err) = mDNSName->CreateServer(networkID, params); if (!err.IsNone()) { - return AOS_ERROR_WRAP(err); + return {false, AOS_ERROR_WRAP(err)}; } LockGuard lock {mMutex}; if (auto setErr = mDNSServers.Set(networkID, handle); !setErr.IsNone()) { - return AOS_ERROR_WRAP(setErr); + return {false, AOS_ERROR_WRAP(setErr)}; + } + + return {true, ErrorEnum::eNone}; +} + +void NetworkManager::RemoveUnusedDNSServer(const String& instanceID, const String& networkID) +{ + LockGuard lock {mMutex}; + + // Another instance may have started on the network meanwhile and already uses the server. + if (auto network = mRuntimeCache.Find(networkID); network != mRuntimeCache.end()) { + if (network->mSecond.ContainsIf([&instanceID](const auto& item) { return item.mFirst != instanceID; })) { + return; + } + } + + if (auto err = RemoveDNSServer(networkID); !err.IsNone()) { + LOG_ERR() << "Failed to remove DNS server" << Log::Field("networkID", networkID) << Log::Field(err); + } +} + +Error NetworkManager::RemoveDNSServer(const String& networkID) +{ + if (mDNSServers.Find(networkID) == mDNSServers.end()) { + return ErrorEnum::eNone; + } + + LOG_DBG() << "Remove DNS server" << Log::Field("networkID", networkID); + + (void)mDNSServers.Remove(networkID); + + if (auto err = mDNSName->RemoveServer(networkID); !err.IsNone()) { + return AOS_ERROR_WRAP(err); } return ErrorEnum::eNone; @@ -1729,12 +1903,8 @@ Error NetworkManager::ClearNetwork(const NetworkInfo& networkInfo) Error err; - if (mDNSServers.Find(networkInfo.mNetworkID) != mDNSServers.end()) { - if (auto errRemove = mDNSName->RemoveServer(networkInfo.mNetworkID); !errRemove.IsNone() && err.IsNone()) { - err = AOS_ERROR_WRAP(errRemove); - } - - (void)mDNSServers.Remove(networkInfo.mNetworkID); + if (auto errRemove = RemoveDNSServer(networkInfo.mNetworkID); !errRemove.IsNone() && err.IsNone()) { + err = errRemove; } if (auto errMasq = mFirewall->RemoveMasquerade(networkInfo.mSubnet, mUplinkIfName); @@ -2053,43 +2223,6 @@ Error NetworkManager::CreateNetwork(const NetworkInfo& network) return AOS_ERROR_WRAP(err); } - auto cleanupMasquerade = DeferRelease(&network, [this, &err](const NetworkInfo* network) { - if (!err.IsNone()) { - if (auto errMasq = mFirewall->RemoveMasquerade(network->mSubnet, mUplinkIfName); !errMasq.IsNone()) { - LOG_ERR() << "Failed to remove masquerade on CreateNetwork rollback" - << Log::Field("networkID", network->mNetworkID) << Log::Field(errMasq); - } - } - }); - - DNSServerParams dnsParams; - - err = PrepareDNSServerParams(network, dnsParams); - if (!err.IsNone()) { - return err; - } - - DNSServerItf* dnsServer = nullptr; - - Tie(dnsServer, err) = mDNSName->CreateServer(network.mNetworkID, dnsParams); - if (!err.IsNone()) { - return AOS_ERROR_WRAP(err); - } - - auto cleanupDNSServer = DeferRelease(&network, [this, &err](const NetworkInfo* network) { - if (!err.IsNone()) { - if (auto errRemove = mDNSName->RemoveServer(network->mNetworkID); !errRemove.IsNone()) { - LOG_ERR() << "Failed to remove DNS server on CreateNetwork rollback" - << Log::Field("networkID", network->mNetworkID) << Log::Field(errRemove); - } - } - }); - - err = mDNSServers.Set(network.mNetworkID, dnsServer); - if (!err.IsNone()) { - return AOS_ERROR_WRAP(err); - } - LOG_DBG() << "Network created" << Log::Field("networkID", network.mNetworkID); return ErrorEnum::eNone; @@ -2320,6 +2453,62 @@ void NetworkManager::SetFirewallApplied(const String& instanceID, bool applied) } } +void NetworkManager::OnUnitNetworksUpdate(const String& nodeID, const Array>& networkIDs) +{ + if (nodeID != mNodeID) { + LOG_WRN() << "Ignoring unit networks update for different node" << Log::Field("expectedNodeID", mNodeID) + << Log::Field("receivedNodeID", nodeID); + + return; + } + + LOG_DBG() << "Received unit networks update" << Log::Field("count", networkIDs.Size()); + + auto droppedNetworks = MakeUnique, cMaxNumOwners>>(mAllocator); + if (!droppedNetworks) { + LOG_ERR() << "Failed to allocate dropped networks" << Log::Field(ErrorEnum::eNoMemory); + + return; + } + + { + LockGuard lock {mMutex}; + + if (auto err = mUnitNetworks.Assign(networkIDs); !err.IsNone()) { + LOG_ERR() << "Failed to set unit networks" << Log::Field(AOS_ERROR_WRAP(err)); + + return; + } + + for (const auto& [networkID, _] : mNetworkProviders) { + if (mUnitNetworks.Contains(networkID)) { + continue; + } + + if (auto err = droppedNetworks->PushBack(networkID); !err.IsNone()) { + LOG_ERR() << "Failed to add dropped network" << Log::Field("networkID", networkID) + << Log::Field(AOS_ERROR_WRAP(err)); + } + } + } + + for (const auto& networkID : *droppedNetworks) { + RemoveNodeNetworkIfUnused(networkID); + } + + for (const auto& networkID : networkIDs) { + if (auto err = EnsureNodeNetwork(networkID); !err.IsNone()) { + LOG_ERR() << "Failed to ensure unit network" << Log::Field("networkID", networkID) << Log::Field(err); + + continue; + } + + if (auto err = EnsureNodeNetworkPhysical(networkID); !err.IsNone()) { + LOG_ERR() << "Failed to create unit network" << Log::Field("networkID", networkID) << Log::Field(err); + } + } +} + void NetworkManager::OnConnect() { LOG_DBG() << "SM connected to CM, synchronizing network state"; diff --git a/src/core/sm/networkmanager/networkmanager.hpp b/src/core/sm/networkmanager/networkmanager.hpp index 9995572d4..3b83b6b90 100644 --- a/src/core/sm/networkmanager/networkmanager.hpp +++ b/src/core/sm/networkmanager/networkmanager.hpp @@ -45,7 +45,8 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { ~NetworkManager(); /** - * Initializes network manager. + * Initializes network manager: loads the stored node and instance networks and takes the stored node networks as + * unit networks until CM sends the unit networks update. * * @param allocator allocator to use for temporary objects. * @param storage storage interface. @@ -64,7 +65,8 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { aos::networkmanager::NetworkProviderItf& networkProvider, const String& nodeID); /** - * Starts network manager. + * Starts network manager: removes firewall and DNS orphans, restores the links of the unit networks and + * reconciles the stored instances. DNS servers are kept only for networks with running instances. * * @return Error. */ @@ -192,6 +194,15 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { void OnPendingFirewallUpdate( const String& nodeID, const aos::networkmanager::PendingFirewallUpdate& update) override; + /** + * Called with the full set of unit network IDs: creates the missing node networks and releases the node + * networks that left the set and have no instances. + * + * @param nodeID node ID the update is addressed to. + * @param networkIDs IDs of all networks of the unit. + */ + void OnUnitNetworksUpdate(const String& nodeID, const Array>& networkIDs) override; + /** * Called when SM successfully connects/reconnects to CM. */ @@ -227,6 +238,8 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { Error RemoveFirewallOrphans(); Error EnsureNodeNetwork(const String& networkID); Error EnsureNodeNetworkPhysical(const String& networkID); + void RemoveNodeNetworkIfUnused(const String& networkID); + bool IsNodeNetworkInUse(const String& networkID) const; Error UpdateInstanceFirewall(const String& instanceID, const String& networkID, const InstanceNetworkConfig& networkConfig, const aos::InstanceNetworkAllocation& networkParams); Error AddInstanceToNetwork(const String& instanceID, const String& networkID, @@ -235,7 +248,8 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { void ReapplyBatchEntries(Array>& failedInstanceIDs); void ClearBatchState(); Error RemoveDNSOrphans(); - Error AdoptDNSServer(const String& networkID); + Error RestoreUnitNetworks(); + Error RemoveIdleDNSServers(); Error PrepareBridgeParams( const String& networkID, const aos::InstanceNetworkAllocation& networkParams, BridgeParams& params) const; Error PrepareInstanceFirewallParams(const InstanceNetworkConfig& networkConfig, @@ -256,6 +270,9 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { Error PushHostWithDomain( const String& host, const String& networkID, Array>& hosts) const; RetWithError IsLinkExist(const String& ifName) const; + RetWithError EnsureDNSServer(const String& networkID); + void RemoveUnusedDNSServer(const String& instanceID, const String& networkID); + Error RemoveDNSServer(const String& networkID); Error CreateNetwork(const NetworkInfo& network); Error DeleteInstanceNetworkConfig(const String& instanceID, const String& networkID); Error GenerateIfName(String& ifName, const String& ifPrefix); @@ -309,6 +326,7 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { StaticMap, DNSServerItf*, cMaxNumOwners> mDNSServers; StaticMap, InstanceNetworkInfo, cMaxNumInstances> mInstanceNetworkInfos; StaticArray, cMaxNumOwners> mPhysicalNetworks; + StaticArray, cMaxNumOwners> mUnitNetworks; bool mBatchMode {false}; StaticArray mBatchEntries; @@ -316,6 +334,7 @@ class NetworkManager : public NetworkManagerItf, private NonCopyable { StaticArray, cMaxNumInstances> mUnappliedFirewalls; mutable Mutex mMutex; + Mutex mNodeNetworkMutex; AllocatorItf* mAllocator {}; }; diff --git a/src/core/sm/networkmanager/networkmanager.md b/src/core/sm/networkmanager/networkmanager.md index 63fed55c9..398c56892 100644 --- a/src/core/sm/networkmanager/networkmanager.md +++ b/src/core/sm/networkmanager/networkmanager.md @@ -11,9 +11,9 @@ documentation: - [Networking overview][arch-overview]; - [Per-instance network lifecycle][arch-lifecycle]. -The contract between SM and CM (network parameters allocation, release, state synchronization and deferred firewall -updates) is described in [common network manager][common-networkmanager]. This document only covers the SM -implementation of that contract. +The contract between SM and CM (network parameters allocation, release, state synchronization, deferred firewall +updates and unit networks updates) is described in [common network manager][common-networkmanager]. This document +only covers the SM implementation of that contract. [arch-overview]: https://github.com/aosedge/public-docs/blob/main/docs/aos-core/14-network/index.md [arch-lifecycle]: https://github.com/aosedge/public-docs/blob/main/docs/aos-core/14-network/per-instance-networking.md @@ -37,8 +37,13 @@ Network manager keeps the following state: - **instance network infos** (`InstanceNetworkInfo`) - instance network config (`InstanceNetworkConfig`), parameters allocated by CM (`InstanceNetworkAllocation`) and the host-side veth name once the instance is started. Persisted in the storage; +- **unit networks** - IDs of the networks that exist in the unit. Taken from the stored network infos on `Init` and + replaced by every unit networks update from CM. Not persisted separately; - **runtime cache** - instances that are currently physically started, grouped by network. Not persisted; -- **physical networks** - networks whose bridge/VLAN/masquerade/DNS server are currently created. Not persisted; +- **physical networks** - networks whose bridge/VLAN links and masquerade rule are currently created: every unit network + and every other network with running instances on the node. Not persisted; +- **DNS servers** - per-network DNS servers. A network has one only while it has running instances on the node. Not + persisted; - **deferred firewall updates** - pending firewall updates received from CM for instances that are not created yet. Not persisted. @@ -50,7 +55,7 @@ It implements the following interfaces: - [aos::sm::networkmanager::InstanceTrafficProviderItf](itf/instancetrafficprovider.hpp) - provides instance traffic; - [aos::networkmanager::PendingUpdateHandlerItf](../../common/networkmanager/itf/pendingupdatehandler.hpp) - - receives resolved pending firewall rules from CM; + receives resolved pending firewall rules and unit networks updates from CM; - [aos::sm::smclient::ConnectListenerItf](../smclient/itf/connection.hpp) - receives CM connection events to synchronize network state. @@ -163,7 +168,8 @@ classDiagram ## Initialization `Init` stores the dependencies and loads network infos and instance network infos from the storage into the internal -cache. No CM calls and no physical changes are made at this stage. +cache. The stored networks are taken as the unit networks until CM sends a unit networks update. No CM calls and no +physical changes are made at this stage. `Start` brings the node into a consistent state after SM (re)start: @@ -171,11 +177,16 @@ cache. No CM calls and no physical changes are made at this stage. 2. resolves the uplink interface (the one the default route points to) used for masquerade; 3. removes orphan firewall chains and masquerade rules that do not belong to any known instance/network; 4. re-asserts masquerade rules for all known networks; -5. removes orphan DNS servers left from the previous SM lifetime; -6. reconciles instances: for every instance network info that has a host-side veth name recorded, checks whether the +5. removes orphan DNS servers left from the previous SM lifetime: only networks that have stored instances are known; +6. restores the unit networks: creates the missing bridge/VLAN links (existing links are adopted) and installs the + masquerade rule for every unit network. No DNS server is created. A network that fails to be restored is logged and + does not fail `Start`; +7. reconciles instances: for every instance network info that has a host-side veth name recorded, checks whether the veth still exists and is attached to the expected bridge. If it is alive, the instance is adopted: it is added to the runtime cache, traffic monitoring is restarted and the DNS server for its network is adopted. Otherwise the leftover - physical configuration (DNS host, bandwidth, firewall chain, namespace) is cleaned up. + physical configuration (DNS host, bandwidth, firewall chain, namespace) is cleaned up; +8. removes the DNS servers of networks that have no running instances, e.g. the ones adopted only to clean up leftover + instances. Adopted instances are treated as running, so the launcher does not need to restart them. @@ -187,6 +198,7 @@ sequenceDiagram participant trafficmonitor participant dnsname participant interfacemanager + participant interfacefactory launcher ->> networkmanager: Start @@ -199,7 +211,13 @@ sequenceDiagram networkmanager ->> firewall: AddMasquerade(subnet, uplink) end - networkmanager ->> dnsname: RemoveOrphans(knownNetworks) + networkmanager ->> dnsname: RemoveOrphans(networksWithInstances) + + loop unit networks + networkmanager ->> interfacemanager: GetLink(bridge), GetLink(vlan) + networkmanager ->> interfacefactory: CreateBridge / CreateVlan (missing links) + networkmanager ->> firewall: AddMasquerade(subnet, uplink) + end loop instance network infos with host veth networkmanager ->> interfacemanager: GetLink(hostIfName) @@ -212,6 +230,10 @@ sequenceDiagram networkmanager ->> networkmanager: cleanupPhysicalConfig end end + + loop DNS servers of networks without running instances + networkmanager ->> dnsname: RemoveServer(networkID) + end ``` `Stop` stops the traffic monitor and the firewall (deletes the nft table). Instance networks are not touched. @@ -236,7 +258,8 @@ The typical sequence for an instance is `CreateInstanceNetwork` -> `StartInstanc 5. stores instance network info in the storage and in the internal cache. On any failure the allocation is released on CM and the cache is rolled back. No bridge/VLAN, namespace or veth is -created here. +created here. While the instance network is being created, `StartInstanceNetwork` and `ReleaseInstanceNetwork` return +`eWrongState` for it. ```mermaid sequenceDiagram @@ -263,23 +286,25 @@ sequenceDiagram ### Start instance network `StartInstanceNetwork` performs the physical part only, using the cached parameters. It does not call CM. It returns -`eNotFound` if `CreateInstanceNetwork` was not called for the instance and `eInvalidArgument` if the network ID does not -match the created one. +`eNotFound` if `CreateInstanceNetwork` was not called for the instance, `eInvalidArgument` if the network ID does not +match the created one and `eWrongState` if the instance network is still being created. 1. adds the instance to the runtime cache and checks that its hostname and aliases are unique within the network; 2. ensures the physical node network exists: if the bridge and VLAN links are not created yet, creates them (an - existing link left from a crashed SM is adopted, not recreated), installs the masquerade rule for the network - subnet on the uplink interface and creates the per-network DNS server; -3. creates the instance network namespace; -4. attaches the instance to the bridge: creates a veth pair, moves the peer end into the namespace, assigns IP and + existing link left from a crashed SM is adopted, not recreated) and installs the masquerade rule for the network + subnet on the uplink interface; +3. creates the per-network DNS server if the network has none yet, i.e. for the first running instance of the network; +4. creates the instance network namespace; +5. attaches the instance to the bridge: creates a veth pair, moves the peer end into the namespace, assigns IP and default route via the bridge IP, enables hairpin; -5. adds the per-instance firewall chain: exposed ports as input rules, CM firewall rules as output rules; -6. applies bandwidth shaping to the host-side veth if ingress or egress limit is set; -7. registers the instance IP with its hostname, aliases and instance identifier names on the network DNS server; -8. starts traffic monitoring for the instance IP with upload/download limits; -9. stores the host-side veth name in the instance network info (used for reconciliation after restart). +6. adds the per-instance firewall chain: exposed ports as input rules, CM firewall rules as output rules; +7. applies bandwidth shaping to the host-side veth if ingress or egress limit is set; +8. registers the instance IP with its hostname, aliases and instance identifier names on the network DNS server; +9. starts traffic monitoring for the instance IP with upload/download limits; +10. stores the host-side veth name in the instance network info (used for reconciliation after restart). -On any failure the completed steps are unwound in reverse order. +On any failure the completed steps are unwound in reverse order. The bridge/VLAN links are kept; the DNS server is +removed if it was created by this call and no other instance of the network is running. The hosts file and resolv.conf are not written by network manager. The caller obtains their content via `GetHosts` and `GetResolvServers` after `StartInstanceNetwork` and writes the files itself. @@ -302,6 +327,9 @@ sequenceDiagram alt physical network not created networkmanager ->> interfacefactory: CreateBridge / CreateVlan networkmanager ->> firewall: AddMasquerade(subnet, uplink) + end + + alt no DNS server for network networkmanager ->> dnsname: CreateServer(networkID) end @@ -331,8 +359,8 @@ CM. If the instance is not running (not in the runtime cache), it returns `eNone the namespace; 6. clears the host-side veth name in the instance network info; 7. removes the instance from the runtime cache; -8. if it was the last running instance on the network, clears the physical network: removes the DNS server, the - masquerade rule and the bridge/VLAN links. +8. if it was the last running instance on the network, removes the network DNS server. If the network is not a unit + network, also clears the physical network: removes the masquerade rule and the bridge/VLAN links. ```mermaid sequenceDiagram @@ -357,20 +385,25 @@ sequenceDiagram alt last running instance on network networkmanager ->> dnsname: RemoveServer(networkID) - networkmanager ->> firewall: RemoveMasquerade(subnet, uplink) - networkmanager ->> interfacemanager: DeleteLink(bridge), DeleteLink(vlan) + + alt not a unit network + networkmanager ->> firewall: RemoveMasquerade(subnet, uplink) + networkmanager ->> interfacemanager: DeleteLink(bridge), DeleteLink(vlan) + end end ``` ### Release instance network `ReleaseInstanceNetwork` performs the logical release (DB + CM). It requires `StopInstanceNetwork` to be called first -and returns `eInvalidArgument` if the instance is still running. +and returns `eInvalidArgument` if the instance is still running and `eWrongState` if the instance network is still +being created. 1. removes instance network info from the internal cache and the storage; 2. releases instance network on CM (`ReleaseInstanceNetwork`); -3. if it was the last created instance on the network, removes network info from the storage and releases node - network on CM (`ReleaseNodeNetwork`). +3. if it was the last created instance on the network and the network is not a unit network, clears the physical + network if it is still created, removes network info from the storage and releases node network on CM + (`ReleaseNodeNetwork`). Storage and CM failures are logged as warnings and do not fail the release. @@ -386,12 +419,69 @@ sequenceDiagram networkmanager ->> storage: RemoveInstanceNetworkInfo(instanceID) networkmanager ->> networkprovider: ReleaseInstanceNetwork(instanceIdent, nodeID) - alt last instance on network + alt last instance on network and not a unit network networkmanager ->> storage: RemoveNetworkInfo(networkID) networkmanager ->> networkprovider: ReleaseNodeNetwork(networkID, nodeID) end ``` +## Unit networks + +CM announces the IDs of all networks of the unit via `OnUnitNetworksUpdate` (see +[common network manager][common-networkmanager]). The set is complete: network manager replaces its unit networks +with it. On `OnUnitNetworksUpdate` network manager: + +1. ignores the update if the node ID does not match its own; +2. for every known network that is not in the set: if the node has no instances of it (neither created nor running), + clears its physical network, removes network info from the storage and releases node network on CM + (`ReleaseNodeNetwork`). A network that still has instances is kept and removed with its last instance (see + [Stop instance network](#stop-instance-network) and [Release instance network](#release-instance-network)); +3. for every network in the set: if the network is not known yet, requests node network parameters from CM + (`GetNodeNetworkParams`), generates bridge/VLAN interface names and stores the network info. Then creates the + missing bridge/VLAN links and installs the masquerade rule. No DNS server is created. + +A network that fails is logged and skipped without affecting the others. It is retried on the next unit networks +update, which CM sends again when SM reconnects. + +Node network creation and release towards CM are serialized, so a node network is never released on CM while it is +being requested for an instance on the same node. An instance network that is being created keeps its node network +from being released until the creation completes or fails. + +```mermaid +sequenceDiagram + participant networkprovider as networkprovider (CM) + participant networkmanager + participant storage + participant interfacefactory + participant firewall + participant interfacemanager + + networkprovider ->> networkmanager: OnUnitNetworksUpdate(nodeID, networkIDs) + + loop known networks not in set + alt no instances of network + networkmanager ->> firewall: RemoveMasquerade(subnet, uplink) + networkmanager ->> interfacemanager: DeleteLink(bridge), DeleteLink(vlan) + networkmanager ->> storage: RemoveNetworkInfo(networkID) + networkmanager ->> networkprovider: ReleaseNodeNetwork(networkID, nodeID) + end + end + + loop networks in set + alt network not known + networkmanager ->> networkprovider: GetNodeNetworkParams(networkID, nodeID) + networkprovider -->> networkmanager: NetworkParams + networkmanager ->> networkmanager: generate bridge/VLAN names + networkmanager ->> storage: AddNetworkInfo + end + + alt physical network not created + networkmanager ->> interfacefactory: CreateBridge / CreateVlan + networkmanager ->> firewall: AddMasquerade(subnet, uplink) + end + end +``` + ## Batch operations When many instances are started or stopped at once (e.g. on update instances), the caller can wrap the @@ -451,8 +541,8 @@ and allocated parameters in the storage. Returns `eAlreadyExist` if already crea ### StartInstanceNetwork -Starts instance network: creates bridge/VLAN if needed, namespace, veth, firewall chain, bandwidth shaping, DNS -registration and traffic monitoring. Does not call CM. +Starts instance network: creates bridge/VLAN if needed, the network DNS server for the first running instance of the +network, namespace, veth, firewall chain, bandwidth shaping, DNS registration and traffic monitoring. Does not call CM. ### GetResolvServers @@ -468,13 +558,15 @@ custom hosts from the instance network config. The caller writes the hosts file ### StopInstanceNetwork -Stops instance network: tears down traffic monitoring, DNS, bandwidth, firewall and namespace. Clears bridge/VLAN if -it was the last running instance on the network. Does not touch the storage and does not call CM. +Stops instance network: tears down traffic monitoring, DNS, bandwidth, firewall and namespace. If it was the last +running instance on the network, removes the network DNS server and, unless the network is a unit network, clears +bridge/VLAN. Does not touch the storage and does not call CM. ### ReleaseInstanceNetwork Releases instance network: removes it from the storage and releases it on CM. Releases node network on CM if it was -the last instance on the network. Requires `StopInstanceNetwork` to be called first. +the last instance on the network and the network is not a unit network. Requires `StopInstanceNetwork` to be called +first. ### BeginBatch / FlushBatch @@ -494,6 +586,11 @@ Sets the traffic accounting period. Applies resolved pending firewall rules to the instance, or defers them if the instance is not created yet. +### OnUnitNetworksUpdate + +Replaces the unit networks: creates the missing node networks without DNS servers and releases the networks that left +the set and have no instances on the node. + ## aos::sm::smclient::ConnectListenerItf ### OnConnect diff --git a/src/core/sm/networkmanager/tests/networkmanager.cpp b/src/core/sm/networkmanager/tests/networkmanager.cpp index 3033b710f..2d7433a33 100644 --- a/src/core/sm/networkmanager/tests/networkmanager.cpp +++ b/src/core/sm/networkmanager/tests/networkmanager.cpp @@ -3,6 +3,7 @@ * * SPDX-License-Identifier: Apache-2.0 */ +#include #include #include #include @@ -344,6 +345,27 @@ class NetworkManagerTest : public Test { EXPECT_CALL(mStorage, UpdateInstanceNetworkInfo(_)).Times(0); } + void ExpectStoredNetworkLinksCreated(const NetworkInfo& network) + { + EXPECT_CALL(mNetIfFactory, CreateBridge(network.mBridgeIfName, network.mIP, network.mSubnet)) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(network.mVlanIfName, network.mVlanID, network.mBridgeIfName)) + .WillOnce(Return(aos::ErrorEnum::eNone)); + } + + NetworkInfo CreateSecondTestNetworkInfo() + { + NetworkInfo network; + network.mNetworkID = "network2"; + network.mIP = "192.168.2.1"; + network.mSubnet = "192.168.2.0/24"; + network.mVlanID = 200ULL; + network.mVlanIfName = "vlan-22222222"; + network.mBridgeIfName = "br-33333333"; + + return network; + } + void ExpectStartInstanceOnStoredNetwork(const aos::String& instanceID, const aos::String& networkID) { EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) @@ -354,6 +376,27 @@ class NetworkManagerTest : public Test { aos::ErrorEnum::eNone); } + void UpdateUnitNetworks(std::initializer_list networkIDs) + { + aos::StaticArray, aos::cMaxNumOwners> ids; + + for (const auto& id : networkIDs) { + ASSERT_TRUE(ids.PushBack(id).IsNone()); + } + + mNetManager->OnUnitNetworksUpdate("test-node", ids); + } + + void ExpectStartInstanceCalls() + { + ExpectAddInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mTrafficMonitor, StartInstanceMonitoring(_, _, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, CreateNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, GetNetworkNamespacePath(_)) + .WillOnce(Return(aos::RetWithError> {{}, aos::ErrorEnum::eNone})); + } + void ExpectDeleteInstanceCalls(int times = 1) { EXPECT_CALL(mDNSServer, RemoveHost(_)).Times(times).WillRepeatedly(Return(aos::ErrorEnum::eNone)); @@ -1018,6 +1061,141 @@ TEST_F(NetworkManagerTest, StartInstanceNetwork_FailOnTrafficMonitorError) EXPECT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eRuntime); } +TEST_F(NetworkManagerTest, StartInstanceNetwork_CreatesDNSServerSeparatelyFromNetwork) +{ + const aos::String instanceID = "test-instance"; + const aos::String networkID = "test-network"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + + SetupEnsureNodeNetworkCreateMocks(networkID, allocatedParams.mSubnet, "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) + .WillOnce(DoAll(SetArgReferee<4>(allocatedParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID, networkID, params), aos::ErrorEnum::eNone); + + // The network links are created once and kept although the DNS server fails to start. + EXPECT_CALL(mNetIfFactory, CreateBridge(_, aos::String("192.168.1.1"), allocatedParams.mSubnet)) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(_, 100ULL, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mDNSName, CreateServer(networkID, _)) + .WillOnce(Return(aos::RetWithError {nullptr, aos::ErrorEnum::eFailed})) + .WillOnce(Return(aos::RetWithError {&mDNSServer, aos::ErrorEnum::eNone})); + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(0); + EXPECT_CALL(mNetns, CreateNetworkNamespace(_)).Times(0); + + EXPECT_TRUE(mNetManager->StartInstanceNetwork(instanceID, networkID).Is(aos::ErrorEnum::eFailed)); + + Mock::VerifyAndClearExpectations(&mNetns); + Mock::VerifyAndClearExpectations(&mNetIf); + + EXPECT_CALL(mNetIf, GetLink(_, _)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNotFound)); + EXPECT_CALL(mNetIf, GetUplinkInterface(_)) + .Times(AnyNumber()) + .WillRepeatedly(DoAll(SetArgReferee<0>(aos::String(cUplinkIfName)), Return(aos::ErrorEnum::eNone))); + + ExpectAddInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mTrafficMonitor, StartInstanceMonitoring(_, _, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, CreateNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, GetNetworkNamespacePath(_)) + .WillOnce(Return(aos::RetWithError> {{}, aos::ErrorEnum::eNone})); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, StartInstanceNetwork_RemovesCreatedDNSServerOnFailure) +{ + const aos::String instanceID = "test-instance"; + const aos::String networkID = "test-network"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + + SetupEnsureNodeNetworkCreateMocks(networkID, allocatedParams.mSubnet, "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) + .WillOnce(DoAll(SetArgReferee<4>(allocatedParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID, networkID, params), aos::ErrorEnum::eNone); + + SetupEnsureNodeNetworkPhysicalMocks("192.168.1.1", allocatedParams.mSubnet, 100ULL); + + EXPECT_CALL(mBridgeNetwork, Attach(_, _, _)).WillOnce(Return(aos::ErrorEnum::eInvalidArgument)); + EXPECT_CALL(mNetns, CreateNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, GetNetworkNamespacePath(_)) + .WillOnce(Return(aos::RetWithError> {{}, aos::ErrorEnum::eNone})); + EXPECT_CALL(mNetns, DeleteNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mDNSName, RemoveServer(networkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + + EXPECT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eInvalidArgument); + + EXPECT_CALL(mDNSName, RemoveServer(_)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + + // The next start recreates the removed DNS server. + EXPECT_CALL(mDNSName, CreateServer(networkID, _)) + .WillOnce(Return(aos::RetWithError {&mDNSServer, aos::ErrorEnum::eNone})); + + ExpectAddInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mTrafficMonitor, StartInstanceMonitoring(_, _, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, CreateNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, GetNetworkNamespacePath(_)) + .WillOnce(Return(aos::RetWithError> {{}, aos::ErrorEnum::eNone})); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, StartInstanceNetwork_KeepsDNSServerOfRunningInstanceOnFailure) +{ + const aos::String instanceID1 = "test-instance-1"; + const aos::String instanceID2 = "test-instance-2"; + const aos::String networkID = "test-network"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + + SetupEnsureNodeNetworkCreateMocks(networkID, allocatedParams.mSubnet, "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) + .Times(2) + .WillRepeatedly(DoAll(SetArgReferee<4>(allocatedParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).Times(2).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID1, networkID, params), aos::ErrorEnum::eNone); + + params.mHosts.Clear(); + params.mAliases.Clear(); + params.mHostname = "test-host-2"; + params.mInstanceIdent.mInstance = 1; + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID2, networkID, params), aos::ErrorEnum::eNone); + + // Only the first start creates the DNS server. + SetupEnsureNodeNetworkPhysicalMocks("192.168.1.1", allocatedParams.mSubnet, 100ULL); + + ExpectAddInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mTrafficMonitor, StartInstanceMonitoring(_, _, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, CreateNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, GetNetworkNamespacePath(_)) + .WillOnce(Return(aos::RetWithError> {{}, aos::ErrorEnum::eNone})); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID1, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mBridgeNetwork, Attach(instanceID2, _, _)).WillOnce(Return(aos::ErrorEnum::eInvalidArgument)); + EXPECT_CALL(mNetns, CreateNetworkNamespace(instanceID2)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, GetNetworkNamespacePath(_)) + .WillOnce(Return(aos::RetWithError> {{}, aos::ErrorEnum::eNone})); + EXPECT_CALL(mNetns, DeleteNetworkNamespace(instanceID2)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mDNSName, RemoveServer(_)).Times(0); + + EXPECT_EQ(mNetManager->StartInstanceNetwork(instanceID2, networkID), aos::ErrorEnum::eInvalidArgument); + + EXPECT_CALL(mDNSName, RemoveServer(_)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNone)); +} + TEST_F(NetworkManagerTest, CreateInstanceNetwork_Idempotent) { const aos::String instanceID = "test-instance"; @@ -2212,6 +2390,379 @@ TEST_F(NetworkManagerTest, OnPendingFirewallUpdate_DropsDeferredUpdateForPreviou EXPECT_TRUE(stored.mAllocatedParams.mFirewallRules.IsEmpty()); } +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_CreatesAnnouncedNetworkWithoutDNSServer) +{ + const aos::String networkID = "unit-network"; + + SetupEnsureNodeNetworkCreateMocks(networkID, "192.168.1.0/24", "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetIfFactory, CreateBridge(_, aos::String("192.168.1.1"), aos::String("192.168.1.0/24"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(_, 100ULL, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mFirewall, AddMasquerade(aos::String("192.168.1.0/24"), aos::String(cUplinkIfName))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mDNSName, CreateServer(_, _)).Times(0); + + UpdateUnitNetworks({"unit-network"}); + + UpdateUnitNetworks({"unit-network"}); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_KnownNetworkDoesNotAskCM) +{ + const auto network = CreateTestNetworkInfo(); + + InitWithStoredNetwork(network); + + EXPECT_CALL(mNetworkProvider, GetNodeNetworkParams(_, _, _)).Times(0); + EXPECT_CALL(mNetIfFactory, CreateBridge(network.mBridgeIfName, network.mIP, network.mSubnet)) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(network.mVlanIfName, network.mVlanID, network.mBridgeIfName)) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mDNSName, CreateServer(_, _)).Times(0); + + UpdateUnitNetworks({"network1"}); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_RemovesDroppedNetworkWithoutInstances) +{ + const aos::String networkID = "unit-network"; + + SetupEnsureNodeNetworkCreateMocks(networkID, "192.168.1.0/24", "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetIfFactory, CreateBridge(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({"unit-network"}); + + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(2).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mStorage, RemoveNetworkInfo(networkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(networkID, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({}); + + Mock::VerifyAndClearExpectations(&mNetIf); + Mock::VerifyAndClearExpectations(&mNetworkProvider); + + SetupEnsureNodeNetworkCreateMocks(networkID, "192.168.1.0/24", "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetIf, GetLink(_, _)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNotFound)); + EXPECT_CALL(mNetIf, GetUplinkInterface(_)) + .Times(AnyNumber()) + .WillRepeatedly(DoAll(SetArgReferee<0>(aos::String(cUplinkIfName)), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mNetIfFactory, CreateBridge(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({"unit-network"}); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_RemovesDroppedStoredNetwork) +{ + const auto network = CreateTestNetworkInfo(); + + InitWithStoredNetwork(network); + + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(0); + EXPECT_CALL(mStorage, RemoveNetworkInfo(network.mNetworkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(network.mNetworkID, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({}); + + Mock::VerifyAndClearExpectations(&mNetIf); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_KeepsDroppedNetworkWithInstances) +{ + const aos::String instanceID = "test-instance"; + const aos::String networkID = "test-network"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + + SetupEnsureNodeNetworkCreateMocks(networkID, allocatedParams.mSubnet, "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) + .WillOnce(DoAll(SetArgReferee<4>(allocatedParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID, networkID, params), aos::ErrorEnum::eNone); + + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(_, _)).Times(0); + EXPECT_CALL(mStorage, RemoveNetworkInfo(_)).Times(0); + + UpdateUnitNetworks({}); + + SetupEnsureNodeNetworkPhysicalMocks("192.168.1.1", allocatedParams.mSubnet, 100ULL); + ExpectStartInstanceCalls(); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(0); + + UpdateUnitNetworks({}); + + Mock::VerifyAndClearExpectations(&mNetIf); + Mock::VerifyAndClearExpectations(&mNetworkProvider); + Mock::VerifyAndClearExpectations(&mStorage); + + EXPECT_CALL(mNetIf, GetLink(_, _)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNotFound)); + EXPECT_CALL(mNetIf, GetUplinkInterface(_)) + .Times(AnyNumber()) + .WillRepeatedly(DoAll(SetArgReferee<0>(aos::String(cUplinkIfName)), Return(aos::ErrorEnum::eNone))); + + EXPECT_CALL(mTrafficMonitor, StopInstanceMonitoring(instanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + ExpectDeleteInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mNetns, DeleteNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(2).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + + EXPECT_EQ(mNetManager->StopInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mStorage, RemoveInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseInstanceNetwork(_, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mStorage, RemoveNetworkInfo(networkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(networkID, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + + EXPECT_EQ(mNetManager->ReleaseInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, StopInstanceNetwork_UnitNetworkKeepsLinks) +{ + const aos::String instanceID = "test-instance"; + const aos::String networkID = "test-network"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + + SetupEnsureNodeNetworkCreateMocks(networkID, allocatedParams.mSubnet, "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetIfFactory, CreateBridge(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({"test-network"}); + + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) + .WillOnce(DoAll(SetArgReferee<4>(allocatedParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID, networkID, params), aos::ErrorEnum::eNone); + + EXPECT_CALL(mDNSName, CreateServer(networkID, _)) + .Times(2) + .WillRepeatedly(Return(aos::RetWithError {&mDNSServer, aos::ErrorEnum::eNone})); + ExpectStartInstanceCalls(); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mTrafficMonitor, StopInstanceMonitoring(instanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + ExpectDeleteInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mNetns, DeleteNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mDNSName, RemoveServer(networkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(0); + EXPECT_CALL(mFirewall, RemoveMasquerade(_, _)).Times(0); + + EXPECT_EQ(mNetManager->StopInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mDNSName, RemoveServer(_)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mFirewall, RemoveMasquerade(_, _)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + + ExpectStartInstanceCalls(); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, ReleaseInstanceNetwork_KeepsUnitNetworkUntilDropped) +{ + const aos::String instanceID = "test-instance"; + const aos::String networkID = "test-network"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + + SetupEnsureNodeNetworkCreateMocks(networkID, allocatedParams.mSubnet, "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetIfFactory, CreateBridge(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(_, _, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({"test-network"}); + + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) + .Times(2) + .WillRepeatedly(DoAll(SetArgReferee<4>(allocatedParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).Times(2).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID, networkID, params), aos::ErrorEnum::eNone); + + EXPECT_CALL(mDNSName, CreateServer(networkID, _)) + .WillOnce(Return(aos::RetWithError {&mDNSServer, aos::ErrorEnum::eNone})); + ExpectStartInstanceCalls(); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mTrafficMonitor, StopInstanceMonitoring(instanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + ExpectDeleteInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mNetns, DeleteNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(0); + + EXPECT_EQ(mNetManager->StopInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mStorage, RemoveInstanceNetworkInfo(instanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseInstanceNetwork(_, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mStorage, RemoveNetworkInfo(_)).Times(0); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(_, _)).Times(0); + + EXPECT_EQ(mNetManager->ReleaseInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mNetworkProvider, GetNodeNetworkParams(_, _, _)).Times(0); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID, networkID, params), aos::ErrorEnum::eNone); + + EXPECT_CALL(mStorage, RemoveInstanceNetworkInfo(instanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseInstanceNetwork(_, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + + EXPECT_EQ(mNetManager->ReleaseInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(2).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mStorage, RemoveNetworkInfo(networkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(networkID, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({}); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_KeepsNetworkOfInstanceBeingCreated) +{ + const aos::String instanceID = "test-instance"; + const aos::String networkID = "test-network"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + + SetupEnsureNodeNetworkCreateMocks(networkID, allocatedParams.mSubnet, "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(_, _)).Times(0); + EXPECT_CALL(mStorage, RemoveNetworkInfo(_)).Times(0); + + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, networkID, aos::String("test-node"), _, _)) + .WillOnce(Invoke([&](const aos::InstanceIdent&, const aos::String&, const aos::String&, + const aos::UpdateItemNetworkParams&, aos::InstanceNetworkAllocation& result) { + UpdateUnitNetworks({}); + + EXPECT_TRUE(mNetManager->StartInstanceNetwork(instanceID, networkID).Is(aos::ErrorEnum::eWrongState)); + EXPECT_TRUE(mNetManager->ReleaseInstanceNetwork(instanceID, networkID).Is(aos::ErrorEnum::eWrongState)); + + result = allocatedParams; + + return aos::ErrorEnum::eNone; + })); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + ASSERT_EQ(mNetManager->CreateInstanceNetwork(instanceID, networkID, params), aos::ErrorEnum::eNone); + + SetupEnsureNodeNetworkPhysicalMocks("192.168.1.1", allocatedParams.mSubnet, 100ULL); + ExpectStartInstanceCalls(); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, networkID), aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_CreateWaitsForNodeNetworkRelease) +{ + const auto network = CreateTestNetworkInfo(); + const aos::String instanceID = "test-instance"; + auto params = CreateTestInstanceNetworkConfig(); + auto allocatedParams = CreateTestAllocatedParams(); + aos::Error createErr = aos::ErrorEnum::eFailed; + std::thread createThread; + + InitWithStoredNetwork(network); + + Sequence seq; + + EXPECT_CALL(mStorage, RemoveNetworkInfo(network.mNetworkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(network.mNetworkID, aos::String("test-node"))) + .InSequence(seq) + .WillOnce(Invoke([&](const aos::String&, const aos::String&) { + createThread = std::thread( + [&]() { createErr = mNetManager->CreateInstanceNetwork(instanceID, network.mNetworkID, params); }); + + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + return aos::ErrorEnum::eNone; + })); + + aos::NetworkParams netParams; + netParams.mNetworkID = network.mNetworkID; + netParams.mSubnet = network.mSubnet; + netParams.mIP = network.mIP; + netParams.mVlanID = network.mVlanID; + + EXPECT_CALL(mNetworkProvider, GetNodeNetworkParams(network.mNetworkID, aos::String("test-node"), _)) + .InSequence(seq) + .WillOnce(DoAll(SetArgReferee<2>(netParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mRandom, RandBuffer(_, 4)).Times(2).WillRepeatedly(Invoke([](aos::Array& buffer, size_t) { + static uint8_t counter = 0; + + buffer.Resize(4); + + for (size_t i = 0; i < buffer.Size(); i++) { + buffer[i] = static_cast(counter + i); + } + + counter += 4; + + return aos::ErrorEnum::eNone; + })); + EXPECT_CALL(mStorage, AddNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, AllocateInstanceNetwork(_, network.mNetworkID, aos::String("test-node"), _, _)) + .InSequence(seq) + .WillOnce(DoAll(SetArgReferee<4>(allocatedParams), Return(aos::ErrorEnum::eNone))); + EXPECT_CALL(mStorage, AddInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({}); + + ASSERT_TRUE(createThread.joinable()); + createThread.join(); + + EXPECT_EQ(createErr, aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_ContinuesAfterNetworkFailure) +{ + EXPECT_CALL(mNetworkProvider, GetNodeNetworkParams(aos::String("failed-network"), aos::String("test-node"), _)) + .WillOnce(Return(aos::ErrorEnum::eFailed)); + + SetupEnsureNodeNetworkCreateMocks("unit-network", "192.168.1.0/24", "192.168.1.1", 100ULL); + + EXPECT_CALL(mNetIfFactory, CreateBridge(_, aos::String("192.168.1.1"), aos::String("192.168.1.0/24"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIfFactory, CreateVlan(_, 100ULL, _)).WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({"failed-network", "unit-network"}); +} + +TEST_F(NetworkManagerTest, OnUnitNetworksUpdate_IgnoresUpdateForDifferentNode) +{ + const auto network = CreateTestNetworkInfo(); + + InitWithStoredNetwork(network); + + EXPECT_CALL(mNetworkProvider, GetNodeNetworkParams(_, _, _)).Times(0); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(_, _)).Times(0); + EXPECT_CALL(mStorage, RemoveNetworkInfo(_)).Times(0); + EXPECT_CALL(mNetIfFactory, CreateBridge(_, _, _)).Times(0); + + aos::StaticArray, aos::cMaxNumOwners> ids; + + ASSERT_TRUE(ids.PushBack("unit-network").IsNone()); + + mNetManager->OnUnitNetworksUpdate("other-node", ids); +} + TEST_F(NetworkManagerTest, OnConnect_SyncsNetworkStateWithCM) { const aos::String instanceID = "test-instance"; @@ -2267,6 +2818,7 @@ TEST_F(NetworkManagerTest, Start_CleansLeftoverInstanceWithMissingInterface) instances->PushBack(leftover); RestartWithStoredState(networks, *instances); + ExpectStoredNetworkLinksCreated(network); EXPECT_CALL(mDNSName, RemoveOrphans(_)) .WillOnce(Invoke([&](const aos::Array>& known) { @@ -2294,6 +2846,7 @@ TEST_F(NetworkManagerTest, Start_KeepsLeftoverInstanceWithLiveInterface) instances->PushBack(leftover); RestartWithStoredState(networks, *instances); + ExpectStoredNetworkLinksCreated(network); ExpectLinkExists(leftover.mHostIfName, LinkKindEnum::eVeth, network.mBridgeIfName); EXPECT_CALL(mNetns, IsNetworkNamespaceExist(leftover.mInstanceID)) @@ -2326,6 +2879,7 @@ TEST_F(NetworkManagerTest, Start_AdoptsDNSServerForRunningInstanceCleanedOnStop) instances->PushBack(leftover); RestartWithStoredState(networks, *instances); + ExpectStoredNetworkLinksCreated(network); ExpectLinkExists(leftover.mHostIfName, LinkKindEnum::eVeth, network.mBridgeIfName); EXPECT_CALL(mNetns, IsNetworkNamespaceExist(leftover.mInstanceID)) @@ -2365,6 +2919,7 @@ TEST_F(NetworkManagerTest, Start_CleansLeftoverInstanceWhenNamespaceMissing) instances->PushBack(leftover); RestartWithStoredState(networks, *instances); + ExpectStoredNetworkLinksCreated(network); ExpectLinkExists(leftover.mHostIfName, LinkKindEnum::eVeth, network.mBridgeIfName); EXPECT_CALL(mNetns, IsNetworkNamespaceExist(leftover.mInstanceID)) @@ -2389,6 +2944,7 @@ TEST_F(NetworkManagerTest, Start_CleansLeftoverInstanceAttachedToForeignBridge) instances->PushBack(leftover); RestartWithStoredState(networks, *instances); + ExpectStoredNetworkLinksCreated(network); ExpectLinkExists(leftover.mHostIfName, LinkKindEnum::eVeth, "br-someoneelse"); @@ -2511,13 +3067,17 @@ TEST_F(NetworkManagerTest, Start_ReassertsMasqueradeOnCurrentUplink) networks.PushBack(network); RestartWithStoredState(networks, *instances); + ExpectStoredNetworkLinksCreated(network); EXPECT_CALL(mDNSName, RemoveOrphans(_)).WillOnce(Return(aos::ErrorEnum::eNone)); aos::StaticString capturedOutIf; EXPECT_CALL(mFirewall, AddMasquerade(network.mSubnet, _)) - .WillOnce(Invoke([&](const aos::String&, const aos::String& outIf) { + .Times(2) + .WillRepeatedly(Invoke([&](const aos::String&, const aos::String& outIf) { + EXPECT_EQ(outIf, aos::String(cUplinkIfName)); + capturedOutIf = outIf; return aos::ErrorEnum::eNone; @@ -2528,6 +3088,184 @@ TEST_F(NetworkManagerTest, Start_ReassertsMasqueradeOnCurrentUplink) EXPECT_EQ(capturedOutIf, aos::String(cUplinkIfName)); } +TEST_F(NetworkManagerTest, Start_RestoresStoredNetworksWithoutDNSServer) +{ + const auto network1 = CreateTestNetworkInfo(); + const auto network2 = CreateSecondTestNetworkInfo(); + + aos::StaticArray networks; + auto instances + = std::make_unique>(); + networks.PushBack(network1); + networks.PushBack(network2); + + RestartWithStoredState(networks, *instances, false); + + EXPECT_CALL(mDNSName, RemoveOrphans(_)) + .WillOnce(Invoke([](const aos::Array>& known) { + EXPECT_TRUE(known.IsEmpty()); + + return aos::ErrorEnum::eNone; + })); + + EXPECT_CALL(mFirewall, RemoveOrphans(_, _)) + .WillOnce(Invoke([&](const aos::Array>&, + const aos::Array& knownMasquerades) { + EXPECT_EQ(knownMasquerades.Size(), 2U); + EXPECT_TRUE(knownMasquerades.ContainsIf([&](const MasqueradeParams& params) { + return params.mSubnet == network1.mSubnet && params.mOutIfName == cUplinkIfName; + })); + EXPECT_TRUE(knownMasquerades.ContainsIf([&](const MasqueradeParams& params) { + return params.mSubnet == network2.mSubnet && params.mOutIfName == cUplinkIfName; + })); + + return aos::ErrorEnum::eNone; + })); + EXPECT_CALL(mFirewall, AddMasquerade(network1.mSubnet, aos::String(cUplinkIfName))) + .Times(AtLeast(1)) + .WillRepeatedly(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mFirewall, AddMasquerade(network2.mSubnet, aos::String(cUplinkIfName))) + .Times(AtLeast(1)) + .WillRepeatedly(Return(aos::ErrorEnum::eNone)); + + ExpectStoredNetworkLinksCreated(network1); + ExpectStoredNetworkLinksCreated(network2); + EXPECT_CALL(mDNSName, CreateServer(_, _)).Times(0); + EXPECT_CALL(mNetworkProvider, GetNodeNetworkParams(_, _, _)).Times(0); + + ASSERT_EQ(mNetManager->Start(), aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, Start_ContinuesWhenStoredNetworkFails) +{ + const auto network1 = CreateTestNetworkInfo(); + const auto network2 = CreateSecondTestNetworkInfo(); + + aos::StaticArray networks; + auto instances + = std::make_unique>(); + networks.PushBack(network1); + networks.PushBack(network2); + + RestartWithStoredState(networks, *instances); + + EXPECT_CALL(mDNSName, RemoveOrphans(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + EXPECT_CALL(mNetIfFactory, CreateBridge(network1.mBridgeIfName, _, _)).WillOnce(Return(aos::ErrorEnum::eFailed)); + EXPECT_CALL(mNetIfFactory, CreateVlan(network1.mVlanIfName, _, _)).Times(0); + ExpectStoredNetworkLinksCreated(network2); + + ASSERT_EQ(mNetManager->Start(), aos::ErrorEnum::eNone); +} + +TEST_F(NetworkManagerTest, Start_StoredNetworkIsKeptAsUnitNetwork) +{ + const auto network = CreateTestNetworkInfo(); + const aos::String instanceID = "test-instance"; + + aos::StaticArray networks; + auto instances + = std::make_unique>(); + networks.PushBack(network); + + RestartWithStoredState(networks, *instances); + + EXPECT_CALL(mDNSName, RemoveOrphans(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + ExpectStoredNetworkLinksCreated(network); + + ASSERT_EQ(mNetManager->Start(), aos::ErrorEnum::eNone); + + EXPECT_CALL(mNetworkProvider, GetNodeNetworkParams(_, _, _)).Times(0); + + ExpectStartInstanceOnStoredNetwork(instanceID, network.mNetworkID); + + EXPECT_CALL(mDNSName, CreateServer(network.mNetworkID, _)) + .WillOnce(Return(aos::RetWithError {&mDNSServer, aos::ErrorEnum::eNone})); + ExpectStartInstanceCalls(); + + ASSERT_EQ(mNetManager->StartInstanceNetwork(instanceID, network.mNetworkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mTrafficMonitor, StopInstanceMonitoring(instanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + ExpectDeleteInstanceCalls(); + ExpectPersistInstanceCalls(); + EXPECT_CALL(mNetns, DeleteNetworkNamespace(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(0); + + EXPECT_EQ(mNetManager->StopInstanceNetwork(instanceID, network.mNetworkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mStorage, RemoveInstanceNetworkInfo(instanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseInstanceNetwork(_, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mStorage, RemoveNetworkInfo(_)).Times(0); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(_, _)).Times(0); + + EXPECT_EQ(mNetManager->ReleaseInstanceNetwork(instanceID, network.mNetworkID), aos::ErrorEnum::eNone); + + EXPECT_CALL(mNetIf, DeleteLink(_)).Times(2).WillRepeatedly(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mStorage, RemoveNetworkInfo(network.mNetworkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetworkProvider, ReleaseNodeNetwork(network.mNetworkID, aos::String("test-node"))) + .WillOnce(Return(aos::ErrorEnum::eNone)); + + UpdateUnitNetworks({}); +} + +TEST_F(NetworkManagerTest, Start_RemovesDNSServerOfNetworkWithoutRunningInstances) +{ + const auto network1 = CreateTestNetworkInfo(); + const auto network2 = CreateSecondTestNetworkInfo(); + const auto leftover = CreateLeftoverInstance(network1); + + auto alive = CreateLeftoverInstance(network2); + alive.mInstanceID = "alive-instance"; + alive.mNetworkConfig.mHostname = "alive-host"; + alive.mAllocatedParams.mIP = "192.168.2.5"; + alive.mHostIfName = "veth-alive"; + + aos::StaticArray networks; + auto instances + = std::make_unique>(); + networks.PushBack(network1); + networks.PushBack(network2); + instances->PushBack(leftover); + instances->PushBack(alive); + + RestartWithStoredState(networks, *instances); + + EXPECT_CALL(mDNSName, RemoveOrphans(_)) + .WillOnce(Invoke([&](const aos::Array>& known) { + EXPECT_EQ(known.Size(), 2U); + EXPECT_TRUE(known.Contains(network1.mNetworkID)); + EXPECT_TRUE(known.Contains(network2.mNetworkID)); + + return aos::ErrorEnum::eNone; + })); + + ExpectStoredNetworkLinksCreated(network1); + ExpectStoredNetworkLinksCreated(network2); + + ExpectLinkExists(alive.mHostIfName, LinkKindEnum::eVeth, network2.mBridgeIfName); + EXPECT_CALL(mNetns, IsNetworkNamespaceExist(alive.mInstanceID)) + .WillRepeatedly(Return(aos::RetWithError {true, aos::ErrorEnum::eNone})); + EXPECT_CALL(mTrafficMonitor, StartInstanceMonitoring(alive.mInstanceID, _, _, _)) + .WillOnce(Return(aos::ErrorEnum::eNone)); + + EXPECT_CALL(mDNSName, CreateServer(network1.mNetworkID, _)) + .WillOnce(Return(aos::RetWithError {&mDNSServer, aos::ErrorEnum::eNone})); + EXPECT_CALL(mDNSName, CreateServer(network2.mNetworkID, _)) + .WillOnce(Return(aos::RetWithError {&mDNSServer, aos::ErrorEnum::eNone})); + EXPECT_CALL(mDNSServer, RemoveHost(leftover.mInstanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mFirewall, RemoveInstance(leftover.mInstanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mNetns, DeleteNetworkNamespace(leftover.mInstanceID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mStorage, UpdateInstanceNetworkInfo(_)).WillOnce(Return(aos::ErrorEnum::eNone)); + + EXPECT_CALL(mDNSName, RemoveServer(network1.mNetworkID)).WillOnce(Return(aos::ErrorEnum::eNone)); + EXPECT_CALL(mDNSName, RemoveServer(network2.mNetworkID)).Times(0); + + ASSERT_EQ(mNetManager->Start(), aos::ErrorEnum::eNone); + + EXPECT_CALL(mDNSName, RemoveServer(_)).Times(AnyNumber()).WillRepeatedly(Return(aos::ErrorEnum::eNone)); +} + TEST_F(NetworkManagerTest, Start_FailsWhenNoDefaultRoute) { const auto network = CreateTestNetworkInfo(); diff --git a/src/core/sm/tests/mocks/networkmanagermock.hpp b/src/core/sm/tests/mocks/networkmanagermock.hpp index e2f8b3199..361cffe5e 100644 --- a/src/core/sm/tests/mocks/networkmanagermock.hpp +++ b/src/core/sm/tests/mocks/networkmanagermock.hpp @@ -32,6 +32,8 @@ class NetworkManagerMock : public NetworkManagerItf { MOCK_METHOD(Error, FlushBatch, (Array> & failedInstanceIDs), (override)); MOCK_METHOD(void, OnPendingFirewallUpdate, (const String& nodeID, const aos::networkmanager::PendingFirewallUpdate& update), (override)); + MOCK_METHOD( + void, OnUnitNetworksUpdate, (const String& nodeID, const Array>& networkIDs), (override)); MOCK_METHOD(void, OnConnect, (), (override)); };