From 4a43bc7559d2c6c7ec9281ee6f9f0ff1a9780626 Mon Sep 17 00:00:00 2001 From: Mitch <25337396+MitchDrage@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:36:39 +0000 Subject: [PATCH 1/2] Add a minimum BGP hold time setting for virtual routers --- .../main/java/com/cloud/bgp/BGPService.java | 13 +- .../agent/api/routing/SetBgpPeersCommand.java | 9 + .../facade/SetBgpPeersConfigItem.java | 2 +- .../virtualnetwork/model/BgpPeers.java | 14 ++ .../facade/SetBgpPeersMinHoldtimeTest.java | 84 ++++++++ .../java/com/cloud/bgp/BGPServiceImpl.java | 11 ++ .../ConfigurationManagerImpl.java | 4 + .../network/router/CommandSetupHelper.java | 2 + .../com/cloud/bgp/BGPServiceImplTest.java | 12 ++ .../ConfigurationManagerImplTest.java | 15 ++ ...andSetupHelperBgpPeersMinHoldtimeTest.java | 187 ++++++++++++++++++ .../debian/opt/cloud/bin/cs/CsBgpPeers.py | 8 +- systemvm/debian/opt/cloud/bin/cs_bgppeers.py | 3 + systemvm/test/TestCsBgpPeers.py | 1 + systemvm/test/TestCsBgpPeersFrr.py | 110 +++++++++++ systemvm/test/__init__.py | 2 + .../test/fixtures/router/cmdline-natted.json | 14 ++ .../test/fixtures/router/cmdline-routed.json | 14 ++ systemvm/test/fixtures/router/ips.json | 146 ++++++++++++++ systemvm/test/frr-bgppeers-ipv4-ipv6.conf | 1 + systemvm/test/vr_test_helpers.py | 133 +++++++++++++ 21 files changed, 782 insertions(+), 3 deletions(-) create mode 100644 core/src/test/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersMinHoldtimeTest.java create mode 100644 server/src/test/java/com/cloud/network/router/CommandSetupHelperBgpPeersMinHoldtimeTest.java create mode 100644 systemvm/test/TestCsBgpPeersFrr.py create mode 100644 systemvm/test/fixtures/router/cmdline-natted.json create mode 100644 systemvm/test/fixtures/router/cmdline-routed.json create mode 100644 systemvm/test/fixtures/router/ips.json create mode 100644 systemvm/test/vr_test_helpers.py diff --git a/api/src/main/java/com/cloud/bgp/BGPService.java b/api/src/main/java/com/cloud/bgp/BGPService.java index 61d149f28470..a230d9f653d2 100644 --- a/api/src/main/java/com/cloud/bgp/BGPService.java +++ b/api/src/main/java/com/cloud/bgp/BGPService.java @@ -21,11 +21,22 @@ import com.cloud.network.vpc.Vpc; import com.cloud.utils.Pair; import org.apache.cloudstack.api.command.user.bgp.ListASNumbersCmd; +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.network.BgpPeer; import java.util.List; -public interface BGPService { +public interface BGPService extends Configurable { + + ConfigKey MinHoldtime = new ConfigKey<>(ConfigKey.CATEGORY_NETWORK, Integer.class, + "routed.bgp.min.holdtime", + "3", + "The lowest BGP hold time, in seconds, that a virtual router accepts. " + + "It applies to every BGP peer on the router. " + + "A session that negotiates a lower hold time, including 0, is refused.", + true, + ConfigKey.Scope.Account); ASNumberRange createASNumberRange(long zoneId, long startASNumber, long endASNumber); List listASNumberRanges(Long zoneId); diff --git a/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersCommand.java b/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersCommand.java index 36371a196c81..25c122039029 100644 --- a/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersCommand.java +++ b/core/src/main/java/com/cloud/agent/api/routing/SetBgpPeersCommand.java @@ -25,6 +25,7 @@ public class SetBgpPeersCommand extends NetworkElementCommand { BgpPeerTO[] bpgPeers; + Integer minHoldtime; protected SetBgpPeersCommand() { } @@ -36,4 +37,12 @@ public SetBgpPeersCommand(List bpgPeers) { public BgpPeerTO[] getBpgPeers() { return bpgPeers; } + + public Integer getMinHoldtime() { + return minHoldtime; + } + + public void setMinHoldtime(Integer minHoldtime) { + this.minHoldtime = minHoldtime; + } } diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItem.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItem.java index 68f4275bb6be..e2a4c745c77f 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItem.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersConfigItem.java @@ -34,7 +34,7 @@ public class SetBgpPeersConfigItem extends AbstractConfigItemFacade { @Override public List generateConfig(final NetworkElementCommand cmd) { final SetBgpPeersCommand command = (SetBgpPeersCommand) cmd; - return generateConfigItems(new BgpPeers(Arrays.asList(command.getBpgPeers()))); + return generateConfigItems(new BgpPeers(Arrays.asList(command.getBpgPeers()), command.getMinHoldtime())); } @Override diff --git a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeers.java b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeers.java index 54a1ab2e0915..c2eaa14621c4 100644 --- a/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeers.java +++ b/core/src/main/java/com/cloud/agent/resource/virtualnetwork/model/BgpPeers.java @@ -25,6 +25,7 @@ public class BgpPeers extends ConfigBase { private List peers; + private Integer minHoldtime; public BgpPeers() { super(ConfigBase.BGP_PEERS); @@ -35,6 +36,11 @@ public BgpPeers(List bgpPeers) { this.peers = bgpPeers; } + public BgpPeers(List bgpPeers, Integer minHoldtime) { + this(bgpPeers); + this.minHoldtime = minHoldtime; + } + public List getPeers() { return peers; } @@ -42,4 +48,12 @@ public List getPeers() { public void setPeers(List bgpPeers) { this.peers = bgpPeers; } + + public Integer getMinHoldtime() { + return minHoldtime; + } + + public void setMinHoldtime(Integer minHoldtime) { + this.minHoldtime = minHoldtime; + } } diff --git a/core/src/test/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersMinHoldtimeTest.java b/core/src/test/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersMinHoldtimeTest.java new file mode 100644 index 000000000000..9ca7662ecca0 --- /dev/null +++ b/core/src/test/java/com/cloud/agent/resource/virtualnetwork/facade/SetBgpPeersMinHoldtimeTest.java @@ -0,0 +1,84 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.agent.resource.virtualnetwork.facade; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.apache.cloudstack.network.BgpPeerTO; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.cloud.agent.api.routing.SetBgpPeersCommand; +import com.cloud.agent.resource.virtualnetwork.ConfigItem; +import com.cloud.agent.resource.virtualnetwork.FileConfigItem; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +/** + * The BGP peers command carries the minimum hold time to the router. The push file + * holds it as min_holdtime beside the peers, so a router with BGP peers renders + * bgp minimum-holdtime. + */ +public class SetBgpPeersMinHoldtimeTest { + + private SetBgpPeersCommand cmd; + + @Before + public void setUp() { + BgpPeerTO peer = new BgpPeerTO(1L, "198.51.100.1", null, 65100L, null, 10L, 64600L, + "172.16.10.0/24", null, new HashMap<>()); + cmd = new SetBgpPeersCommand(Collections.singletonList(peer)); + } + + private JsonObject pushFile() { + List items = new SetBgpPeersConfigItem().generateConfig(cmd); + for (ConfigItem item : items) { + if (item instanceof FileConfigItem) { + return JsonParser.parseString(((FileConfigItem) item).getFileContents()).getAsJsonObject(); + } + } + throw new AssertionError("no push file in " + items); + } + + @Test + public void commandCarriesMinHoldtime() { + cmd.setMinHoldtime(3); + Assert.assertEquals(Integer.valueOf(3), cmd.getMinHoldtime()); + } + + // The push file holds the default minimum hold time next to the peers. + @Test + public void pushFileCarriesMinHoldtime() { + cmd.setMinHoldtime(3); + JsonObject file = pushFile(); + Assert.assertTrue("push file should hold min_holdtime: " + file, file.has("min_holdtime")); + Assert.assertEquals(3, file.get("min_holdtime").getAsInt()); + Assert.assertEquals(1, file.getAsJsonArray("peers").size()); + } + + // A raised minimum hold time reaches the router as set. + @Test + public void pushFileCarriesRaisedMinHoldtime() { + cmd.setMinHoldtime(9); + Assert.assertEquals(9, pushFile().get("min_holdtime").getAsInt()); + } +} diff --git a/server/src/main/java/com/cloud/bgp/BGPServiceImpl.java b/server/src/main/java/com/cloud/bgp/BGPServiceImpl.java index c003bd05a518..f2fe4fcb080e 100644 --- a/server/src/main/java/com/cloud/bgp/BGPServiceImpl.java +++ b/server/src/main/java/com/cloud/bgp/BGPServiceImpl.java @@ -55,6 +55,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.api.command.user.bgp.ListASNumbersCmd; import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.network.BgpPeer; import org.apache.cloudstack.network.BgpPeerVO; import org.apache.cloudstack.network.RoutedIpv4Manager; @@ -108,6 +109,16 @@ public class BGPServiceImpl implements BGPService { public BGPServiceImpl() { } + @Override + public String getConfigComponentName() { + return BGPService.class.getSimpleName(); + } + + @Override + public ConfigKey[] getConfigKeys() { + return new ConfigKey[] {MinHoldtime}; + } + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_AS_RANGE_CREATE, eventDescription = "AS Range creation") diff --git a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java index cca2ea1ae7d2..724bb7eddffb 100644 --- a/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/main/java/com/cloud/configuration/ConfigurationManagerImpl.java @@ -160,6 +160,7 @@ import com.cloud.api.ApiDBUtils; import com.cloud.api.query.dao.NetworkOfferingJoinDao; import com.cloud.api.query.vo.NetworkOfferingJoinVO; +import com.cloud.bgp.BGPService; import com.cloud.capacity.CapacityManager; import com.cloud.capacity.dao.CapacityDao; import com.cloud.cluster.ManagementServerHostVO; @@ -1531,6 +1532,9 @@ protected String validateValueRange(String name, String value, Class type, Co return String.format("[%s] value should be between 0 and 255. 0 value will disable this feature.", name); } } + if (BGPService.MinHoldtime.key().equalsIgnoreCase(name) && (val < 0 || val > 65535)) { + return String.format("[%s] value should be between 0 and 65535. 0 turns off the minimum.", name); + } if (UnmanagedVMsManager.ThreadsOnMSToImportVMwareVMFiles.key().equalsIgnoreCase(name) || UnmanagedVMsManager.ThreadsOnKVMHostToImportVMwareVMFiles.key().equalsIgnoreCase(name)) { if (val < -1 || val > 10) { diff --git a/server/src/main/java/com/cloud/network/router/CommandSetupHelper.java b/server/src/main/java/com/cloud/network/router/CommandSetupHelper.java index 0bf46893c791..20409f9a1697 100644 --- a/server/src/main/java/com/cloud/network/router/CommandSetupHelper.java +++ b/server/src/main/java/com/cloud/network/router/CommandSetupHelper.java @@ -78,6 +78,7 @@ import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.manager.Commands; +import com.cloud.bgp.BGPService; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.ASNumberVO; @@ -1630,6 +1631,7 @@ public void createBgpPeersCommands(final List bgpPeers, final } final SetBgpPeersCommand cmd = new SetBgpPeersCommand(bgpPeerTOs); + cmd.setMinHoldtime(BGPService.MinHoldtime.valueIn(router.getAccountId())); cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId())); cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId()); diff --git a/server/src/test/java/com/cloud/bgp/BGPServiceImplTest.java b/server/src/test/java/com/cloud/bgp/BGPServiceImplTest.java index be31a1c6502c..627f6fcc3d93 100644 --- a/server/src/test/java/com/cloud/bgp/BGPServiceImplTest.java +++ b/server/src/test/java/com/cloud/bgp/BGPServiceImplTest.java @@ -28,6 +28,7 @@ import com.cloud.network.vpc.dao.VpcServiceMapDao; import com.cloud.user.AccountVO; import com.cloud.user.dao.AccountDao; +import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.network.BgpPeerVO; import org.apache.cloudstack.network.RoutedIpv4Manager; import org.apache.cloudstack.network.dao.BgpPeerDao; @@ -43,6 +44,7 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import static org.mockito.ArgumentMatchers.any; @@ -173,4 +175,14 @@ public void testApplyBgpPeersForVpcWithBgpPeers() throws ResourceUnavailableExce verify(vpcVirtualRouterElement).applyBgpPeers(eq(vpc), eq(null), any()); } + + // The minimum hold time is a dynamic account setting registered by this service. + @Test + public void minHoldtimeIsDynamicAccountSettingDefaulting3() { + Assert.assertEquals("routed.bgp.min.holdtime", BGPService.MinHoldtime.key()); + Assert.assertEquals("3", BGPService.MinHoldtime.defaultValue()); + Assert.assertTrue(BGPService.MinHoldtime.isDynamic()); + Assert.assertEquals(Collections.singletonList(ConfigKey.Scope.Account), BGPService.MinHoldtime.getScopes()); + Assert.assertTrue(Arrays.asList(bGPServiceImplSpy.getConfigKeys()).contains(BGPService.MinHoldtime)); + } } diff --git a/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java b/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java index 9a0b150780e4..01a567af087e 100644 --- a/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java +++ b/server/src/test/java/com/cloud/configuration/ConfigurationManagerImplTest.java @@ -17,6 +17,7 @@ package com.cloud.configuration; import com.cloud.alert.AlertManager; +import com.cloud.bgp.BGPService; import com.cloud.capacity.dao.CapacityDao; import com.cloud.dc.DataCenterVO; import com.cloud.dc.VlanVO; @@ -861,6 +862,20 @@ public void validateValueRangeTestReturnsNotNullWhenConfigKeyHasRangeAndValueIsI Assert.assertNotNull(configurationManagerImplSpy.validateValueRange(NetworkModel.MACIdentifier.key(), "-1", Integer.class, null)); } + @Test + public void validateValueRangeTestAcceptsBgpMinHoldtimeWithinRange() { + for (String value : new String[] {"0", "3", "65535"}) { + Assert.assertNull(configurationManagerImplSpy.validateValueRange(BGPService.MinHoldtime.key(), value, Integer.class, null)); + } + } + + @Test + public void validateValueRangeTestRejectsBgpMinHoldtimeOutsideRange() { + for (String value : new String[] {"-1", "65536"}) { + Assert.assertNotNull(configurationManagerImplSpy.validateValueRange(BGPService.MinHoldtime.key(), value, Integer.class, null)); + } + } + @Test public void validateValueRangeTestValidatesValueWhenConfigHasRange() { Config config = Config.SecStorageEncryptCopy; diff --git a/server/src/test/java/com/cloud/network/router/CommandSetupHelperBgpPeersMinHoldtimeTest.java b/server/src/test/java/com/cloud/network/router/CommandSetupHelperBgpPeersMinHoldtimeTest.java new file mode 100644 index 000000000000..82ff3c6173f3 --- /dev/null +++ b/server/src/test/java/com/cloud/network/router/CommandSetupHelperBgpPeersMinHoldtimeTest.java @@ -0,0 +1,187 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package com.cloud.network.router; + +import java.util.Collections; +import java.util.HashMap; + +import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.impl.ConfigDepotImpl; +import org.apache.cloudstack.network.BgpPeer; +import org.apache.cloudstack.network.dao.BgpPeerDetailsDao; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.agent.api.Command; +import com.cloud.agent.api.routing.SetBgpPeersCommand; +import com.cloud.agent.manager.Commands; +import com.cloud.dc.ASNumberVO; +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenterVO; +import com.cloud.dc.dao.ASNumberDao; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.network.Network; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; +import com.cloud.offering.NetworkOffering; +import com.cloud.offerings.NetworkOfferingVO; +import com.cloud.offerings.dao.NetworkOfferingDao; + +/** + * The BGP peers command carries the minimum hold time to the router, so a network or + * VPC with BGP peers gets bgp minimum-holdtime. The value is the setting + * routed.bgp.min.holdtime (BGPService.MinHoldtime). + */ +@RunWith(MockitoJUnitRunner.class) +public class CommandSetupHelperBgpPeersMinHoldtimeTest { + + private static final long ROUTER_ID = 14L; + private static final long ZONE_ID = 1L; + private static final long ACCOUNT_ID = 2L; + private static final long VPC_ID = 30L; + private static final long TIER_ID = 31L; + private static final long OFFERING_ID = 32L; + private static final long PEER_ID = 40L; + private static final String MIN_HOLDTIME = "routed.bgp.min.holdtime"; + + @InjectMocks + protected CommandSetupHelper commandSetupHelper = new CommandSetupHelper(); + @Mock + ASNumberDao asNumberDao; + @Mock + NetworkDao networkDao; + @Mock + NetworkOfferingDao networkOfferingDao; + @Mock + BgpPeerDetailsDao bgpPeerDetailsDao; + @Mock + RouterControlHelper routerControlHelper; + @Mock + DataCenterDao dcDao; + @Mock + ConfigDepotImpl configDepot; + @Mock + VirtualRouter router; + @Mock + NetworkVO tier; + @Mock + NetworkOfferingVO tierOffering; + @Mock + ASNumberVO asNumber; + @Mock + BgpPeer operatorPeer; + @Mock + Network network; + + private Object previousDepot; + + @Before + public void setUp() { + ReflectionTestUtils.setField(commandSetupHelper, "asNumberDao", asNumberDao); + ReflectionTestUtils.setField(commandSetupHelper, "_networkDao", networkDao); + ReflectionTestUtils.setField(commandSetupHelper, "_networkOfferingDao", networkOfferingDao); + ReflectionTestUtils.setField(commandSetupHelper, "bgpPeerDetailsDao", bgpPeerDetailsDao); + ReflectionTestUtils.setField(commandSetupHelper, "_routerControlHelper", routerControlHelper); + ReflectionTestUtils.setField(commandSetupHelper, "_dcDao", dcDao); + previousDepot = ReflectionTestUtils.getField(ConfigKey.class, "s_depot"); + ConfigKey.init(configDepot); + + DataCenterVO dc = new DataCenterVO(ZONE_ID, null, null, null, null, null, null, null, null, null, DataCenter.NetworkType.Advanced, null, null); + + Mockito.lenient().when(router.getId()).thenReturn(ROUTER_ID); + Mockito.lenient().when(router.getDataCenterId()).thenReturn(ZONE_ID); + Mockito.lenient().when(router.getAccountId()).thenReturn(ACCOUNT_ID); + Mockito.lenient().when(router.getVpcId()).thenReturn(VPC_ID); + Mockito.lenient().when(router.getInstanceName()).thenReturn("r-14-VM"); + Mockito.lenient().when(asNumber.getAsNumber()).thenReturn(64600L); + Mockito.lenient().when(asNumberDao.findByZoneAndVpcId(ZONE_ID, VPC_ID)).thenReturn(asNumber); + Mockito.lenient().when(tier.getId()).thenReturn(TIER_ID); + Mockito.lenient().when(tier.getCidr()).thenReturn("172.16.10.0/24"); + Mockito.lenient().when(tier.getNetworkOfferingId()).thenReturn(OFFERING_ID); + Mockito.lenient().when(networkDao.listByVpc(VPC_ID)).thenReturn(Collections.singletonList(tier)); + Mockito.lenient().when(tierOffering.getRoutingMode()).thenReturn(NetworkOffering.RoutingMode.Dynamic); + Mockito.lenient().when(networkOfferingDao.findByIdIncludingRemoved(OFFERING_ID)).thenReturn(tierOffering); + Mockito.lenient().when(operatorPeer.getId()).thenReturn(PEER_ID); + Mockito.lenient().when(operatorPeer.getIp4Address()).thenReturn("198.51.100.1"); + Mockito.lenient().when(operatorPeer.getAsNumber()).thenReturn(65100L); + Mockito.lenient().when(bgpPeerDetailsDao.getBgpPeerDetails(PEER_ID)).thenReturn(new HashMap<>()); + Mockito.lenient().when(routerControlHelper.getRouterControlIp(ROUTER_ID)).thenReturn("192.0.2.10"); + Mockito.lenient().when(dcDao.findById(ZONE_ID)).thenReturn(dc); + } + + @After + public void tearDown() { + ConfigKey.init((ConfigDepotImpl) previousDepot); + } + + private void setting(String key, String value) { + Mockito.lenient().when(configDepot.getConfigStringValue(ArgumentMatchers.eq(key), ArgumentMatchers.any(ConfigKey.Scope.class), + ArgumentMatchers.nullable(Long.class))).thenReturn(value); + } + + private void settingIn(String key, ConfigKey.Scope scope, Long scopeId, String value) { + Mockito.lenient().when(configDepot.getConfigStringValue(ArgumentMatchers.eq(key), ArgumentMatchers.eq(scope), + scopeId == null ? ArgumentMatchers.isNull() : ArgumentMatchers.eq(scopeId))).thenReturn(value); + } + + private SetBgpPeersCommand sent() { + Commands cmds = new Commands(Command.OnError.Stop); + commandSetupHelper.createBgpPeersCommands(Collections.singletonList(operatorPeer), router, cmds, network); + Assert.assertEquals(1, cmds.size()); + Command cmd = cmds.toCommands()[0]; + Assert.assertTrue(cmd instanceof SetBgpPeersCommand); + return (SetBgpPeersCommand) cmd; + } + + // The default minimum hold time is 3 s. + @Test + public void operatorBgpCommandCarriesDefaultMinHoldtime() { + Assert.assertEquals(Integer.valueOf(3), sent().getMinHoldtime()); + } + + // A raised minimum hold time reaches the command as set. + @Test + public void operatorBgpCommandCarriesRaisedMinHoldtime() { + setting(MIN_HOLDTIME, "9"); + Assert.assertEquals(Integer.valueOf(9), sent().getMinHoldtime()); + } + + // The value of the router's account is used when the account has one. + @Test + public void operatorBgpCommandUsesAccountMinHoldtime() { + settingIn(MIN_HOLDTIME, ConfigKey.Scope.Global, null, "5"); + settingIn(MIN_HOLDTIME, ConfigKey.Scope.Account, ACCOUNT_ID, "9"); + Assert.assertEquals(Integer.valueOf(9), sent().getMinHoldtime()); + } + + // An account without its own value uses the global value. + @Test + public void operatorBgpCommandFallsBackToGlobalMinHoldtime() { + settingIn(MIN_HOLDTIME, ConfigKey.Scope.Global, null, "5"); + Assert.assertEquals(Integer.valueOf(5), sent().getMinHoldtime()); + } +} diff --git a/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py b/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py index 38d85f4626fc..db629baae0b8 100755 --- a/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py +++ b/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py @@ -37,9 +37,10 @@ def process(self): else: self.public_ip = self.cl.get_eth2_ip() + self.min_holdtime = self.dbag.get("min_holdtime") self.peers = {} for item in self.dbag: - if item == "id": + if item in ("id", "min_holdtime"): continue self._process_dbag_item(self.dbag[item]) @@ -108,6 +109,11 @@ def _process_peers(self): for as_number in self.peers.keys(): self.frr_conf.add("router bgp {}".format(as_number)) self.frr_conf.add(" bgp router-id {}".format(self.public_ip)) + # FRR accepts 1-65535 here. 0 turns off the minimum and renders no line. + if self.min_holdtime and 1 <= int(self.min_holdtime) <= 65535: + self.frr_conf.add(" bgp minimum-holdtime {}".format(self.min_holdtime)) + elif self.min_holdtime: + logging.error("Ignoring minimum hold time %s, which is outside 1-65535" % self.min_holdtime) if self.peers[as_number]['ip6_peers']: self.frr_conf.add(" bgp default ipv6-unicast") for ip4_peer in self.peers[as_number]['ip4_peers']: diff --git a/systemvm/debian/opt/cloud/bin/cs_bgppeers.py b/systemvm/debian/opt/cloud/bin/cs_bgppeers.py index b284a74f8708..c2563b45e468 100755 --- a/systemvm/debian/opt/cloud/bin/cs_bgppeers.py +++ b/systemvm/debian/opt/cloud/bin/cs_bgppeers.py @@ -23,4 +23,7 @@ def merge(dbag, peers): if 'peer_id' in peer: key = "{}-{}".format(peer['peer_id'], peer['network_id']) dbag[key] = peer + # The minimum hold time applies to every peer, so it sits beside them. + if peers.get('min_holdtime') is not None: + dbag['min_holdtime'] = peers['min_holdtime'] return dbag diff --git a/systemvm/test/TestCsBgpPeers.py b/systemvm/test/TestCsBgpPeers.py index f6de192976e4..3822392ba1fe 100644 --- a/systemvm/test/TestCsBgpPeers.py +++ b/systemvm/test/TestCsBgpPeers.py @@ -33,6 +33,7 @@ def setUp(self): self.csbgppeers = CsBgpPeers("bgppeers", {}) self.csbgppeers.peers = {} self.csbgppeers.public_ip = "100.64.0.10" + self.csbgppeers.min_holdtime = 3 self.csbgppeers.frr_conf = CsFile("frr.conf.test") self.csbgppeers.frr_conf.repopulate() diff --git a/systemvm/test/TestCsBgpPeersFrr.py b/systemvm/test/TestCsBgpPeersFrr.py new file mode 100644 index 000000000000..4cbea78f6fe1 --- /dev/null +++ b/systemvm/test/TestCsBgpPeersFrr.py @@ -0,0 +1,110 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Tests for how CsBgpPeers renders bgp minimum-holdtime on a router with BGP peers. + +CsBgpPeers renders bgp minimum-holdtime from the min_holdtime key of the +bgppeers databag, which cs_bgppeers.merge keeps beside the peer entries. +""" + +import os +import unittest +try: + import mock +except ImportError: + from unittest import mock + +from vr_test_helpers import VrSandbox, FakeShell + +from cs.CsBgpPeers import CsBgpPeers +from cs import CsBgpPeers as bgppeers_module +import cs_bgppeers + +OPERATOR_PEER = {'peer_id': 1, 'network_id': 100, 'network_as_number': 64600, 'peer_as_number': 65100, + 'ip4_address': '198.51.100.1', 'guest_ip4_cidr': '172.16.10.0/24', 'details': {}} + + +class OperatorFrrTestCase(unittest.TestCase): + """Runs CsBgpPeers.process() in a sandbox and records the shell commands.""" + + def run_operator(self, min_holdtime=None, peer=None, bgpd_running=True): + # None leaves the min_holdtime key out of the databag. + bag = {"id": "bgppeers", "1-100": dict(peer or OPERATOR_PEER)} + if min_holdtime is not None: + bag["min_holdtime"] = min_holdtime + sandbox = VrSandbox(mode="routed", extra={"bgppeers.json": bag}) + self.addCleanup(sandbox.close) + self.shell = FakeShell() + self.conf = sandbox.path("frr.conf") + daemons = sandbox.path("daemons") + with open(daemons, "w") as f: + f.write("bgpd=%s\nbfdd=no\n" % ("yes" if bgpd_running else "no")) + patches = [mock.patch('cs.CsHelper.execute', side_effect=self.shell.execute), + mock.patch('cs.CsHelper.mkdir'), + mock.patch('cs.CsHelper.get_hostname', return_value="r-1001-VM"), + mock.patch.object(bgppeers_module, "FRR_DIR", sandbox.dir + os.sep), + mock.patch.object(bgppeers_module, "FRR_CONFIG", self.conf), + mock.patch.object(bgppeers_module, "FRR_DAEMONS", daemons)] + for p in patches: + p.start() + self.addCleanup(p.stop) + try: + CsBgpPeers("bgppeers", sandbox.config).process() + except (TypeError, KeyError, AttributeError, ValueError) as e: + self.fail("CsBgpPeers failed on databag %r: %r" % (bag, e)) + with open(self.conf) as f: + return [line.rstrip('\n') for line in f] + + def router_block(self, lines): + start = [i for i, x in enumerate(lines) if x.startswith("router bgp ")] + self.assertEqual(len(start), 1, lines) + end = next((i for i in range(start[0] + 1, len(lines)) if not lines[i].startswith(" ")), len(lines)) + return lines[start[0]:end] + + +class TestCsBgpPeersMinimumHoldtime(OperatorFrrTestCase): + """A router with BGP peers renders bgp minimum-holdtime from the databag.""" + + def test_databag_merge_keeps_min_holdtime(self): + dbag = cs_bgppeers.merge({"id": "bgppeers"}, {"peers": [dict(OPERATOR_PEER)], "min_holdtime": 3}) + self.assertEqual(dbag.get("min_holdtime"), 3) + self.assertEqual(dbag.get("1-100", {}).get("ip4_address"), "198.51.100.1") + + def test_operator_only_vr_renders_minimum_holdtime(self): + block = self.router_block(self.run_operator(3)) + self.assertEqual([x for x in block if "minimum-holdtime" in x], [" bgp minimum-holdtime 3"]) + first_neighbour = min(i for i, x in enumerate(block) if x.startswith(" neighbor ")) + self.assertLess(block.index(" bgp minimum-holdtime 3"), first_neighbour) + + def test_operator_only_vr_renders_raised_minimum_holdtime(self): + block = self.router_block(self.run_operator(9)) + self.assertEqual([x for x in block if "minimum-holdtime" in x], [" bgp minimum-holdtime 9"]) + + def test_operator_only_vr_renders_no_minimum_holdtime_for_zero(self): + # A minimum of 0 lets peers turn keepalives off with hold time 0. + block = self.router_block(self.run_operator(0)) + self.assertEqual([x for x in block if "minimum-holdtime" in x], []) + + def test_operator_only_vr_skips_minimum_holdtime_outside_frr_range(self): + # FRR rejects these values, so the router renders no line for them. + for value in (-1, 65536): + block = self.router_block(self.run_operator(value)) + self.assertEqual([x for x in block if "minimum-holdtime" in x], [], value) + + +if __name__ == '__main__': + unittest.main() diff --git a/systemvm/test/__init__.py b/systemvm/test/__init__.py index e408e0ca0fef..d60eec2704e4 100755 --- a/systemvm/test/__init__.py +++ b/systemvm/test/__init__.py @@ -18,3 +18,5 @@ import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..", "debian/opt/cloud/bin")) +# Shared test helpers sit beside the tests. +sys.path.append(os.path.dirname(os.path.abspath(__file__))) diff --git a/systemvm/test/fixtures/router/cmdline-natted.json b/systemvm/test/fixtures/router/cmdline-natted.json new file mode 100644 index 000000000000..d479443ca17c --- /dev/null +++ b/systemvm/test/fixtures/router/cmdline-natted.json @@ -0,0 +1,14 @@ +{ + "config": { + "dns1": "203.0.113.53", + "domain": "cs1cloud.internal", + "has_public_network": "true", + "is_routed": "false", + "name": "r-1001-VM", + "redundant_router": "false", + "source_nat_ip": "198.51.100.10", + "type": "vpcrouter", + "vpccidr": "172.16.0.0/16" + }, + "id": "cmdline" +} diff --git a/systemvm/test/fixtures/router/cmdline-routed.json b/systemvm/test/fixtures/router/cmdline-routed.json new file mode 100644 index 000000000000..3420a34c1fe1 --- /dev/null +++ b/systemvm/test/fixtures/router/cmdline-routed.json @@ -0,0 +1,14 @@ +{ + "config": { + "dns1": "203.0.113.53", + "domain": "cs1cloud.internal", + "has_public_network": "true", + "is_routed": "true", + "name": "r-1001-VM", + "redundant_router": "false", + "source_nat_ip": "198.51.100.10", + "type": "vpcrouter", + "vpccidr": "172.16.0.0/16" + }, + "id": "cmdline" +} diff --git a/systemvm/test/fixtures/router/ips.json b/systemvm/test/fixtures/router/ips.json new file mode 100644 index 000000000000..bf9469c8ae0f --- /dev/null +++ b/systemvm/test/fixtures/router/ips.json @@ -0,0 +1,146 @@ +{ + "eth0": [ + { + "add": true, + "broadcast": "169.254.255.255", + "cidr": "169.254.10.20/16", + "device": "eth0", + "gateway": null, + "is_private_gateway": false, + "netmask": "255.255.0.0", + "network": "169.254.0.0/16", + "nw_type": "control", + "one_to_one_nat": false, + "public_ip": "169.254.10.20", + "size": "16", + "source_nat": false + } + ], + "eth1": [ + { + "add": true, + "broadcast": "198.51.100.255", + "cidr": "198.51.100.10/24", + "device": "eth1", + "gateway": "198.51.100.1", + "is_private_gateway": false, + "mtu": "1500", + "netmask": "255.255.255.0", + "network": "198.51.100.0/24", + "nw_type": "public", + "one_to_one_nat": false, + "public_ip": "198.51.100.10", + "size": "24", + "source_nat": true + } + ], + "eth2": [ + { + "add": true, + "broadcast": "172.16.10.255", + "cidr": "172.16.10.1/24", + "device": "eth2", + "gateway": "172.16.10.1", + "is_private_gateway": false, + "mtu": "1500", + "netmask": "255.255.255.0", + "network": "172.16.10.0/24", + "nw_type": "guest", + "one_to_one_nat": false, + "public_ip": "172.16.10.1", + "size": "24", + "source_nat": false + } + ], + "eth3": [ + { + "add": true, + "broadcast": "100.64.0.3", + "cidr": "100.64.0.1/30", + "device": "eth3", + "gateway": "100.64.0.2", + "is_private_gateway": true, + "mtu": "9000", + "netmask": "255.255.255.252", + "network": "100.64.0.0/30", + "nw_type": "public", + "one_to_one_nat": false, + "public_ip": "100.64.0.1", + "size": "30", + "source_nat": false + } + ], + "eth4": [ + { + "add": true, + "broadcast": "172.16.20.255", + "cidr": "172.16.20.1/24", + "device": "eth4", + "gateway": "172.16.20.1", + "is_private_gateway": false, + "mtu": "1500", + "netmask": "255.255.255.0", + "network": "172.16.20.0/24", + "nw_type": "guest", + "one_to_one_nat": false, + "public_ip": "172.16.20.1", + "size": "24", + "source_nat": false + } + ], + "eth5": [ + { + "add": true, + "broadcast": "100.64.0.7", + "cidr": "100.64.0.5/30", + "device": "eth5", + "gateway": "100.64.0.6", + "is_private_gateway": true, + "mtu": "9000", + "netmask": "255.255.255.252", + "network": "100.64.0.4/30", + "nw_type": "public", + "one_to_one_nat": false, + "public_ip": "100.64.0.5", + "size": "30", + "source_nat": false + } + ], + "eth6": [ + { + "add": true, + "broadcast": "100.64.0.11", + "cidr": "100.64.0.9/30", + "device": "eth6", + "gateway": "100.64.0.10", + "is_private_gateway": true, + "mtu": "9000", + "netmask": "255.255.255.252", + "network": "100.64.0.8/30", + "nw_type": "public", + "one_to_one_nat": false, + "public_ip": "100.64.0.9", + "size": "30", + "source_nat": false + } + ], + "eth7": [ + { + "add": true, + "broadcast": "100.64.0.15", + "cidr": "100.64.0.13/30", + "device": "eth7", + "gateway": "100.64.0.14", + "is_private_gateway": true, + "mtu": "9000", + "netmask": "255.255.255.252", + "network": "100.64.0.12/30", + "nw_type": "public", + "one_to_one_nat": false, + "public_ip": "100.64.0.13", + "size": "30", + "source_nat": false + } + ], + "id": "ips" +} diff --git a/systemvm/test/frr-bgppeers-ipv4-ipv6.conf b/systemvm/test/frr-bgppeers-ipv4-ipv6.conf index 9881e1c87dc1..e5f0ab823a4d 100644 --- a/systemvm/test/frr-bgppeers-ipv4-ipv6.conf +++ b/systemvm/test/frr-bgppeers-ipv4-ipv6.conf @@ -27,6 +27,7 @@ ip prefix-list local-v4 seq 1 permit 10.1.1.0/24 ipv6 prefix-list local-v6 seq 1 permit 2001:db8:100::/64 router bgp 64512 bgp router-id 100.64.0.10 + bgp minimum-holdtime 3 bgp default ipv6-unicast neighbor 100.64.0.1 remote-as 64496 neighbor 2001:db8::1 remote-as 64496 diff --git a/systemvm/test/vr_test_helpers.py b/systemvm/test/vr_test_helpers.py new file mode 100644 index 000000000000..bdf9a67abb9a --- /dev/null +++ b/systemvm/test/vr_test_helpers.py @@ -0,0 +1,133 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Helpers for systemvm tests that run the VR scripts against a temporary databag directory. + +VrSandbox copies a cmdline databag and an ips databag from fixtures/router +into a temporary folder and points the databag path at it, so the tests never +read or write /etc/cloudstack. It also resets the cached cmdline on CsConfig, +which other tests share. close() restores both. + +FakeShell records the commands the scripts pass to CsHelper.execute and +CsHelper.execute2. +""" + +import json +import os +import shutil +import tempfile + +from cs.CsConfig import CsConfig +import merge + +# Folders searched in order by fixture_path(). +FIXTURE_DIRS = [os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "router")] + + +def fixture_path(name): + for directory in FIXTURE_DIRS: + path = os.path.join(directory, name) + if os.path.exists(path): + return path + return os.path.join(FIXTURE_DIRS[0], name) + + +def load_json(name): + with open(fixture_path(name)) as f: + return json.load(f) + + +def load_conf(name): + """Read an expected frr.conf fixture. Lines starting with # are the licence header and notes.""" + with open(fixture_path(name)) as f: + return [line.rstrip('\n') for line in f if not line.startswith("#")] + + +class VrSandbox(object): + """A VR databag directory in a temporary folder. + + mode is "natted" or "routed" and picks the cmdline fixture. + ips is a fixture name or a dict. extra maps databag file names to their contents. + """ + + def __init__(self, mode="natted", ips="ips.json", extra=None): + self.dir = tempfile.mkdtemp(prefix="vr-test-") + self.old_dpath = merge.DataBag.DPATH + self.old_cl = CsConfig.cl + self.old_gn = CsConfig.gn + shutil.copy(fixture_path("cmdline-%s.json" % mode), os.path.join(self.dir, "cmdline.json")) + if isinstance(ips, dict): + self.write("ips.json", ips) + else: + shutil.copy(fixture_path(ips), os.path.join(self.dir, "ips.json")) + for name, data in (extra or {}).items(): + self.write(name, data) + merge.DataBag.DPATH = self.dir + CsConfig.cl = None + CsConfig.gn = None + self.config = CsConfig() + self.config.cmdline() + self.config.set_address() + + def write(self, name, data): + with open(os.path.join(self.dir, name), "w") as f: + json.dump(data, f) + + def path(self, name): + return os.path.join(self.dir, name) + + def close(self): + merge.DataBag.DPATH = self.old_dpath + CsConfig.cl = self.old_cl + CsConfig.gn = self.old_gn + shutil.rmtree(self.dir, ignore_errors=True) + + +class FakeShell(object): + """Records CsHelper.execute and CsHelper.execute2 commands. execute returns no output. + + execute2 returns a process result with the given return code. waited lists the + execute2 commands run with wait=True, and communicated those whose output was read. + """ + + def __init__(self, returncode=0): + self.commands = [] + self.returncode = returncode + self.waited = [] + self.communicated = [] + + def execute(self, command): + self.commands.append(command) + return [] + + def execute2(self, command, wait=True): + self.commands.append(command) + if wait: + self.waited.append(command) + shell = self + shell_returncode = self.returncode + + class Result(object): + returncode = shell_returncode + + def communicate(self): + shell.communicated.append(command) + return (b"", b"") + + def wait(self): + return self.returncode + return Result() From c3c5d3920c5dd509fb1b2952405d2840707df888 Mon Sep 17 00:00:00 2001 From: Mitch <25337396+MitchDrage@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:19:31 +0000 Subject: [PATCH 2/2] Skip a non-numeric minimum hold time and apply the rest of the BGP config --- .../debian/opt/cloud/bin/cs/CsBgpPeers.py | 25 ++++++++++++--- systemvm/test/TestCsBgpPeersFrr.py | 31 +++++++++++++++++-- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py b/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py index db629baae0b8..ed2fa54fba61 100755 --- a/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py +++ b/systemvm/debian/opt/cloud/bin/cs/CsBgpPeers.py @@ -105,15 +105,30 @@ def _access_list_set(self): return + def _minimum_holdtime(self): + # FRR accepts 1-65535 here. 0 turns off the minimum and renders no line. + # A value FRR would reject renders no line, so the rest of the file still applies. + if not self.min_holdtime: + return None + try: + value = int(self.min_holdtime) + except (TypeError, ValueError): + logging.error("Ignoring minimum hold time %s, which is not a whole number" % self.min_holdtime) + return None + if value == 0: + return None + if not 1 <= value <= 65535: + logging.error("Ignoring minimum hold time %s, which is outside 1-65535" % self.min_holdtime) + return None + return value + def _process_peers(self): for as_number in self.peers.keys(): self.frr_conf.add("router bgp {}".format(as_number)) self.frr_conf.add(" bgp router-id {}".format(self.public_ip)) - # FRR accepts 1-65535 here. 0 turns off the minimum and renders no line. - if self.min_holdtime and 1 <= int(self.min_holdtime) <= 65535: - self.frr_conf.add(" bgp minimum-holdtime {}".format(self.min_holdtime)) - elif self.min_holdtime: - logging.error("Ignoring minimum hold time %s, which is outside 1-65535" % self.min_holdtime) + min_holdtime = self._minimum_holdtime() + if min_holdtime: + self.frr_conf.add(" bgp minimum-holdtime {}".format(min_holdtime)) if self.peers[as_number]['ip6_peers']: self.frr_conf.add(" bgp default ipv6-unicast") for ip4_peer in self.peers[as_number]['ip4_peers']: diff --git a/systemvm/test/TestCsBgpPeersFrr.py b/systemvm/test/TestCsBgpPeersFrr.py index 4cbea78f6fe1..e18bd47a4514 100644 --- a/systemvm/test/TestCsBgpPeersFrr.py +++ b/systemvm/test/TestCsBgpPeersFrr.py @@ -38,13 +38,16 @@ 'ip4_address': '198.51.100.1', 'guest_ip4_cidr': '172.16.10.0/24', 'details': {}} +ABSENT = object() + + class OperatorFrrTestCase(unittest.TestCase): """Runs CsBgpPeers.process() in a sandbox and records the shell commands.""" - def run_operator(self, min_holdtime=None, peer=None, bgpd_running=True): - # None leaves the min_holdtime key out of the databag. + def run_operator(self, min_holdtime=ABSENT, peer=None, bgpd_running=True): + # ABSENT leaves the min_holdtime key out of the databag. bag = {"id": "bgppeers", "1-100": dict(peer or OPERATOR_PEER)} - if min_holdtime is not None: + if min_holdtime is not ABSENT: bag["min_holdtime"] = min_holdtime sandbox = VrSandbox(mode="routed", extra={"bgppeers.json": bag}) self.addCleanup(sandbox.close) @@ -105,6 +108,28 @@ def test_operator_only_vr_skips_minimum_holdtime_outside_frr_range(self): block = self.router_block(self.run_operator(value)) self.assertEqual([x for x in block if "minimum-holdtime" in x], [], value) + def test_operator_only_vr_skips_minimum_holdtime_that_is_not_a_number(self): + # A value int() cannot read is logged and skipped, and the rest of the file still applies. + for value in ("abc", "None", "null", "3s", [3]): + with self.assertLogs(level="ERROR") as logs: + lines = self.run_operator(value) + block = self.router_block(lines) + self.assertEqual([x for x in block if "minimum-holdtime" in x], [], value) + self.assertIn(" neighbor 198.51.100.1 remote-as 65100", block, value) + self.assertEqual(lines[-1], "line vty", value) + self.assertTrue([m for m in logs.output if "Ignoring minimum hold time" in m], logs.output) + + def test_operator_only_vr_renders_no_minimum_holdtime_for_empty_values(self): + # A null or empty value means no minimum, as when the key is missing. + for value in (None, ""): + block = self.router_block(self.run_operator(value)) + self.assertEqual([x for x in block if "minimum-holdtime" in x], [], value) + self.assertIn(" neighbor 198.51.100.1 remote-as 65100", block, value) + + def test_operator_only_vr_renders_minimum_holdtime_from_a_string(self): + block = self.router_block(self.run_operator("3")) + self.assertEqual([x for x in block if "minimum-holdtime" in x], [" bgp minimum-holdtime 3"]) + if __name__ == '__main__': unittest.main()