Modernize codebase a bit
[bgpcep.git] / bgp / openconfig-state / src / test / java / org / opendaylight / protocol / bgp / state / StateProviderImplTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bgp.state;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertTrue;
12 import static org.mockito.ArgumentMatchers.any;
13 import static org.mockito.ArgumentMatchers.anyBoolean;
14 import static org.mockito.ArgumentMatchers.anyLong;
15 import static org.mockito.ArgumentMatchers.eq;
16 import static org.mockito.Mockito.doAnswer;
17 import static org.mockito.Mockito.doNothing;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.spy;
21 import static org.mockito.Mockito.times;
22 import static org.mockito.Mockito.verify;
23 import static org.opendaylight.protocol.util.CheckUtil.checkNotPresentOperational;
24 import static org.opendaylight.protocol.util.CheckUtil.readDataOperational;
25
26 import com.google.common.collect.ImmutableList;
27 import com.google.common.collect.ImmutableSet;
28 import com.google.common.util.concurrent.Futures;
29 import com.google.common.util.concurrent.ListeningExecutorService;
30 import com.google.common.util.concurrent.MoreExecutors;
31 import java.math.BigDecimal;
32 import java.math.BigInteger;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Collections;
36 import java.util.List;
37 import java.util.Optional;
38 import java.util.Set;
39 import java.util.concurrent.ScheduledExecutorService;
40 import java.util.concurrent.ScheduledFuture;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.atomic.LongAdder;
43 import org.junit.Assert;
44 import org.junit.Before;
45 import org.junit.Test;
46 import org.mockito.ArgumentCaptor;
47 import org.mockito.Mock;
48 import org.mockito.MockitoAnnotations;
49 import org.opendaylight.infrautils.testutils.LogCapture;
50 import org.opendaylight.infrautils.testutils.internal.RememberingLogger;
51 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractDataBrokerTest;
52 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractDataBrokerTestCustomizer;
53 import org.opendaylight.mdsal.binding.dom.adapter.test.ConcurrentDataBrokerTestCustomizer;
54 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
55 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
56 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
57 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
58 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
59 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
60 import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore;
61 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
62 import org.opendaylight.protocol.bgp.rib.spi.State;
63 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
64 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
65 import org.opendaylight.protocol.bgp.rib.spi.state.BGPGracelfulRestartState;
66 import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerMessagesState;
67 import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState;
68 import org.opendaylight.protocol.bgp.rib.spi.state.BGPRibState;
69 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
70 import org.opendaylight.protocol.bgp.rib.spi.state.BGPStateConsumer;
71 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
72 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
73 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafi;
74 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafiBuilder;
75 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.afi.safi.GracefulRestartBuilder;
76 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.afi.safi.graceful.restart.StateBuilder;
77 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.operational.rev151009.BgpAfiSafiGracefulRestartState;
78 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.operational.rev151009.BgpNeighborState;
79 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.operational.rev151009.bgp.neighbor.prefix.counters_state.PrefixesBuilder;
80 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.graceful.restart.GracefulRestart;
81 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafis;
82 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafisBuilder;
83 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ErrorHandling;
84 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ErrorHandlingBuilder;
85 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.Timers;
86 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.TimersBuilder;
87 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.Transport;
88 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.TransportBuilder;
89 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
90 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.peer.group.PeerGroup;
91 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.peer.group.PeerGroupBuilder;
92 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.Bgp;
93 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Global;
94 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.GlobalBuilder;
95 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Neighbors;
96 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ADDPATHS;
97 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ASN32;
98 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.BgpCapability;
99 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.CommunityType;
100 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.GRACEFULRESTART;
101 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.IPV4UNICAST;
102 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.MPBGP;
103 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.ROUTEREFRESH;
104 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.NetworkInstances;
105 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.NetworkInstance;
106 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.NetworkInstanceKey;
107 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.Protocols;
108 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.protocols.Protocol;
109 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.protocols.ProtocolKey;
110 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.policy.types.rev151009.BGP;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
112 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
113 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
114 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
115 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Timeticks;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.BgpNeighborStateAugmentation;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.BgpNeighborStateAugmentationBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.GlobalAfiSafiStateAugmentation;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.GlobalAfiSafiStateAugmentationBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborAfiSafiGracefulRestartStateAugmentation;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborAfiSafiGracefulRestartStateAugmentationBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborAfiSafiStateAugmentation;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborAfiSafiStateAugmentationBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborErrorHandlingStateAugmentation;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborErrorHandlingStateAugmentationBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborGracefulRestartStateAugmentation;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborGracefulRestartStateAugmentationBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborStateAugmentation;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborTimersStateAugmentation;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborTimersStateAugmentationBuilder;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborTransportStateAugmentation;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NeighborTransportStateAugmentationBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.NetworkInstanceProtocol;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.PeerGroupStateAugmentation;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.PeerGroupStateAugmentationBuilder;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instances.network.instance.protocols.protocol.bgp.neighbors.neighbor.state.MessagesBuilder;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instances.network.instance.protocols.protocol.bgp.neighbors.neighbor.state.messages.ReceivedBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180329.network.instances.network.instance.protocols.protocol.bgp.neighbors.neighbor.state.messages.SentBuilder;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.BgpRib;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.RibId;
141 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.Rib;
142 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.RibKey;
143 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
144 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.BgpId;
145 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv4AddressFamily;
146 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.UnicastSubsequentAddressFamily;
147 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
148 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
149 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
150 import org.slf4j.LoggerFactory;
151
152 public class StateProviderImplTest extends AbstractDataBrokerTest {
153     private final LongAdder totalPathsCounter = new LongAdder();
154     private final LongAdder totalPrefixesCounter = new LongAdder();
155     private final PortNumber localPort = new PortNumber(1790);
156     private final PortNumber remotePort = new PortNumber(179);
157     private final int restartTime = 15;
158     private final String ribId = "identifier-test";
159     private final InstanceIdentifier<Bgp> bgpInstanceIdentifier = InstanceIdentifier.create(NetworkInstances.class)
160         .child(NetworkInstance.class, new NetworkInstanceKey("global-bgp")).child(Protocols.class)
161         .child(Protocol.class, new ProtocolKey(BGP.class, this.ribId)).augmentation(NetworkInstanceProtocol.class)
162             .child(Bgp.class);
163     static final TablesKey TABLES_KEY = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
164     private final AsNumber as = new AsNumber(72L);
165     private final BgpId bgpId = new BgpId("127.0.0.1");
166     private final IpAddress neighborAddress = new IpAddress(new Ipv4Address("127.0.0.2"));
167     private final List<Class<? extends BgpCapability>> supportedCap = Arrays.asList(ASN32.class, ROUTEREFRESH.class,
168             MPBGP.class, ADDPATHS.class, GRACEFULRESTART.class);
169     @Mock
170     private BGPStateConsumer stateCollector;
171     @Mock
172     private BGPTableTypeRegistryConsumer tableTypeRegistry;
173     @Mock
174     private BGPRibState bgpRibState;
175     @Mock
176     private BGPPeerState bgpPeerState;
177     @Mock
178     private BGPSessionState bgpSessionState;
179     @Mock
180     private BGPPeerMessagesState bgpPeerMessagesState;
181     @Mock
182     private BGPTimersState timersState;
183     @Mock
184     private BGPTransportState bgpTransportState;
185     @Mock
186     private BGPErrorHandlingState bgpErrorHandlingState;
187     @Mock
188     private BGPGracelfulRestartState bgpGracelfulRestartState;
189     @Mock
190     private BGPAfiSafiState bgpAfiSafiState;
191
192     private final List<BGPPeerState> bgpPeerStates = new ArrayList<>();
193     private final List<BGPRibState> bgpRibStates = new ArrayList<>();
194
195     private InMemoryDOMDataStore realOperStore;
196     private InMemoryDOMDataStore spiedOperStore;
197
198     @Before
199     public void setUp() {
200         MockitoAnnotations.initMocks(this);
201
202         doReturn(Optional.of(IPV4UNICAST.class))
203             .when(this.tableTypeRegistry).getAfiSafiType(eq(TABLES_KEY));
204
205         doReturn(this.bgpRibStates).when(this.stateCollector).getRibStats();
206         doReturn(this.bgpPeerStates).when(this.stateCollector).getPeerStats();
207
208         final KeyedInstanceIdentifier<Rib, RibKey> iid = InstanceIdentifier.create(BgpRib.class)
209             .child(Rib.class, new RibKey(new RibId(this.ribId)));
210         doReturn(iid).when(this.bgpRibState).getInstanceIdentifier();
211         doReturn(this.as).when(this.bgpRibState).getAs();
212         doReturn(this.bgpId).when(this.bgpRibState).getRouteId();
213
214         doAnswer(invocation -> this.totalPathsCounter.longValue())
215                 .when(this.bgpRibState).getTotalPathsCount();
216         doAnswer(invocation -> this.totalPrefixesCounter.longValue())
217                 .when(this.bgpRibState).getTotalPrefixesCount();
218         doAnswer(invocation -> this.totalPathsCounter.longValue())
219                 .when(this.bgpRibState).getPathCount(eq(TABLES_KEY));
220         doAnswer(invocation -> this.totalPrefixesCounter.longValue())
221                 .when(this.bgpRibState).getPrefixesCount(eq(TABLES_KEY));
222         doAnswer(invocation -> Collections.singletonMap(TABLES_KEY,
223             this.totalPrefixesCounter.longValue())).when(this.bgpRibState).getTablesPrefixesCount();
224         doAnswer(invocation -> Collections.singletonMap(TABLES_KEY,
225             this.totalPathsCounter.longValue())).when(this.bgpRibState).getPathsCount();
226
227         // Mock Peer
228         doReturn("test-group").when(this.bgpPeerState).getGroupId();
229         doReturn(iid).when(this.bgpPeerState).getInstanceIdentifier();
230         doAnswer(invocation -> this.totalPrefixesCounter.longValue()).when(this.bgpPeerState).getTotalPrefixes();
231         doAnswer(invocation -> this.totalPathsCounter.longValue()).when(this.bgpPeerState).getTotalPathsCount();
232         doReturn(this.neighborAddress).when(this.bgpPeerState).getNeighborAddress();
233         doReturn(this.bgpSessionState).when(this.bgpPeerState).getBGPSessionState();
234         doReturn(this.bgpPeerMessagesState).when(this.bgpPeerState).getBGPPeerMessagesState();
235
236         doReturn(1L).when(this.bgpPeerMessagesState).getNotificationMessagesReceivedCount();
237         doReturn(1L).when(this.bgpPeerMessagesState).getNotificationMessagesSentCount();
238         doReturn(1L).when(this.bgpPeerMessagesState).getUpdateMessagesReceivedCount();
239         doReturn(1L).when(this.bgpPeerMessagesState).getUpdateMessagesSentCount();
240         doReturn(State.UP).when(this.bgpSessionState).getSessionState();
241         doReturn(true).when(this.bgpSessionState).isAddPathCapabilitySupported();
242         doReturn(true).when(this.bgpSessionState).isAsn32CapabilitySupported();
243         doReturn(true).when(this.bgpSessionState).isGracefulRestartCapabilitySupported();
244         doReturn(true).when(this.bgpSessionState).isMultiProtocolCapabilitySupported();
245         doReturn(true).when(this.bgpSessionState).isRouterRefreshCapabilitySupported();
246
247         doReturn(this.timersState).when(this.bgpPeerState).getBGPTimersState();
248         doReturn(10L).when(this.timersState).getNegotiatedHoldTime();
249         doReturn(10L).when(this.timersState).getUpTime();
250
251         doReturn(this.bgpTransportState).when(this.bgpPeerState).getBGPTransportState();
252         doReturn(this.localPort).when(this.bgpTransportState).getLocalPort();
253         doReturn(this.neighborAddress).when(this.bgpTransportState).getRemoteAddress();
254         doReturn(this.remotePort).when(this.bgpTransportState).getRemotePort();
255
256         doReturn(this.bgpErrorHandlingState).when(this.bgpPeerState).getBGPErrorHandlingState();
257         doReturn(1L).when(this.bgpErrorHandlingState).getErroneousUpdateReceivedCount();
258
259         doReturn(this.bgpGracelfulRestartState).when(this.bgpPeerState).getBGPGracelfulRestart();
260         doReturn(true).when(this.bgpGracelfulRestartState).isGracefulRestartAdvertized(any());
261         doReturn(true).when(this.bgpGracelfulRestartState).isGracefulRestartReceived(any());
262         doReturn(true).when(this.bgpGracelfulRestartState).isLocalRestarting();
263         doReturn(true).when(this.bgpGracelfulRestartState).isPeerRestarting();
264         doReturn(this.restartTime).when(this.bgpGracelfulRestartState).getPeerRestartTime();
265         doReturn(BgpAfiSafiGracefulRestartState.Mode.BILATERAL).when(this.bgpGracelfulRestartState).getMode();
266
267         doReturn(this.bgpAfiSafiState).when(this.bgpPeerState).getBGPAfiSafiState();
268         doReturn(Collections.singleton(TABLES_KEY)).when(this.bgpAfiSafiState).getAfiSafisAdvertized();
269         doReturn(Collections.singleton(TABLES_KEY)).when(this.bgpAfiSafiState).getAfiSafisReceived();
270         doReturn(1L).when(this.bgpAfiSafiState).getPrefixesInstalledCount(any());
271         doReturn(2L).when(this.bgpAfiSafiState).getPrefixesReceivedCount(any());
272         doReturn(1L).when(this.bgpAfiSafiState).getPrefixesSentCount(any());
273         doReturn(true).when(this.bgpAfiSafiState).isAfiSafiSupported(any());
274         doReturn(true).when(this.bgpAfiSafiState).isGracefulRestartAdvertized(any());
275         doReturn(true).when(this.bgpAfiSafiState).isGracefulRestartReceived(any());
276         doReturn(true).when(this.bgpAfiSafiState).isLlGracefulRestartAdvertised(any());
277         doReturn(true).when(this.bgpAfiSafiState).isLlGracefulRestartReceived(any());
278         doReturn(60).when(this.bgpAfiSafiState).getLlGracefulRestartTimer(any());
279     }
280
281     @Override
282     protected Set<YangModuleInfo> getModuleInfos() throws Exception {
283         return ImmutableSet.of(BindingReflections.getModuleInfo(NetworkInstances.class),
284                 BindingReflections.getModuleInfo(NetworkInstanceProtocol.class));
285     }
286
287     @Override
288     protected AbstractDataBrokerTestCustomizer createDataBrokerTestCustomizer() {
289         return new ConcurrentDataBrokerTestCustomizer(true) {
290             @Override
291             public DOMStore createOperationalDatastore() {
292                 realOperStore = new InMemoryDOMDataStore("OPER", getDataTreeChangeListenerExecutor());
293                 spiedOperStore = spy(realOperStore);
294                 getSchemaService().registerSchemaContextListener(spiedOperStore);
295                 return spiedOperStore;
296             }
297
298             @Override
299             public ListeningExecutorService getCommitCoordinatorExecutor() {
300                 return MoreExecutors.newDirectExecutorService();
301             }
302         };
303     }
304
305     @Test
306     public void testActiveStateProvider() throws Exception {
307         doReturn(true).when(this.bgpRibState).isActive();
308         doReturn(true).when(this.bgpPeerState).isActive();
309
310         final StateProviderImpl stateProvider = new StateProviderImpl(getDataBroker(), 1, this.tableTypeRegistry,
311             this.stateCollector, "global-bgp");
312         stateProvider.init();
313
314         final Global globalExpected = buildGlobalExpected(0);
315         this.bgpRibStates.add(this.bgpRibState);
316         readDataOperational(getDataBroker(), this.bgpInstanceIdentifier, bgpRib -> {
317             final Global global = bgpRib.getGlobal();
318             assertEquals(globalExpected, global);
319             return bgpRib;
320         });
321
322         this.totalPathsCounter.increment();
323         this.totalPrefixesCounter.increment();
324
325         final Global globalExpected2 = buildGlobalExpected(1);
326         readDataOperational(getDataBroker(), this.bgpInstanceIdentifier, bgpRib -> {
327             final Global global = bgpRib.getGlobal();
328             assertEquals(globalExpected2, global);
329             return bgpRib;
330         });
331
332         this.totalPathsCounter.decrement();
333         this.totalPrefixesCounter.decrement();
334
335         final Global globalExpected3 = buildGlobalExpected(0);
336         readDataOperational(getDataBroker(), this.bgpInstanceIdentifier, bgpRib -> {
337             final Global global = bgpRib.getGlobal();
338             assertEquals(globalExpected3, global);
339             Assert.assertNull(bgpRib.getNeighbors());
340             Assert.assertNull(bgpRib.getPeerGroups());
341             return bgpRib;
342         });
343
344         this.bgpPeerStates.add(this.bgpPeerState);
345         final PeerGroup peerGroupExpected = buildGroupExpected();
346
347         this.totalPathsCounter.increment();
348         this.totalPrefixesCounter.increment();
349
350         final AfiSafis expectedAfiSafis = buildAfiSafis();
351         final ErrorHandling expectedErrorHandling = buildErrorHandling();
352         final GracefulRestart expectedGracefulRestart = buildGracefulRestart();
353         final Transport expectedTransport = buildTransport();
354         final Timers expectedTimers = buildTimers();
355         final BgpNeighborStateAugmentation expectedBgpNeighborState = buildBgpNeighborStateAugmentation();
356
357         readDataOperational(getDataBroker(), this.bgpInstanceIdentifier, bgpRib -> {
358             final Neighbors neighbors = bgpRib.getNeighbors();
359             Assert.assertNotNull(neighbors);
360             assertEquals(peerGroupExpected, bgpRib.getPeerGroups().getPeerGroup().get(0));
361             final Neighbor neighborResult = neighbors.getNeighbor().get(0);
362             assertEquals(this.neighborAddress, neighborResult.getNeighborAddress());
363             assertEquals(expectedAfiSafis, neighborResult.getAfiSafis());
364             assertEquals(expectedErrorHandling, neighborResult.getErrorHandling());
365             assertEquals(expectedGracefulRestart, neighborResult.getGracefulRestart());
366             assertEquals(expectedTransport, neighborResult.getTransport());
367             assertEquals(expectedTimers, neighborResult.getTimers());
368             final org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group
369                     .State stateResult = neighborResult.getState();
370             assertEquals(expectedBgpNeighborState, stateResult.augmentation(BgpNeighborStateAugmentation.class));
371             assertEquals(BgpNeighborState.SessionState.ESTABLISHED, stateResult
372                     .augmentation(NeighborStateAugmentation.class).getSessionState());
373             final List<Class<? extends BgpCapability>> supportedCapabilitiesResult = stateResult
374                     .augmentation(NeighborStateAugmentation.class).getSupportedCapabilities();
375             Assert.assertTrue(supportedCapabilitiesResult.containsAll(this.supportedCap));
376             return bgpRib;
377         });
378
379         this.bgpRibStates.clear();
380         checkNotPresentOperational(getDataBroker(), this.bgpInstanceIdentifier);
381
382         stateProvider.close();
383     }
384
385     @Test
386     public void testInactiveStateProvider() throws Exception {
387         doReturn(false).when(this.bgpRibState).isActive();
388         doReturn(false).when(this.bgpPeerState).isActive();
389
390         final StateProviderImpl stateProvider = new StateProviderImpl(getDataBroker(), 1, this.tableTypeRegistry,
391             this.stateCollector, "global-bgp");
392         stateProvider.init();
393
394         this.bgpRibStates.add(this.bgpRibState);
395         checkNotPresentOperational(getDataBroker(), this.bgpInstanceIdentifier);
396
397         this.bgpPeerStates.add(this.bgpPeerState);
398         checkNotPresentOperational(getDataBroker(), this.bgpInstanceIdentifier);
399
400         this.bgpRibStates.clear();
401         checkNotPresentOperational(getDataBroker(), this.bgpInstanceIdentifier);
402
403         stateProvider.close();
404     }
405
406     @Test
407     public void testTransactionChainFailure() throws Exception {
408         if (!(LoggerFactory.getLogger(StateProviderImpl.class) instanceof RememberingLogger)) {
409             throw new IllegalStateException("infrautils-testutils must be on the classpath BEFORE other logger impls"
410                 + LoggerFactory.getLogger(StateProviderImpl.class).getClass());
411         }
412
413         doReturn(true).when(this.bgpRibState).isActive();
414
415         this.bgpRibStates.add(this.bgpRibState);
416
417         ScheduledFuture<?> mockScheduledFuture = mock(ScheduledFuture.class);
418         doReturn(true).when(mockScheduledFuture).cancel(anyBoolean());
419
420         ScheduledExecutorService mockScheduler = mock(ScheduledExecutorService.class);
421         doReturn(mockScheduledFuture).when(mockScheduler).scheduleAtFixedRate(any(Runnable.class), anyLong(),
422                 anyLong(), any(TimeUnit.class));
423         doNothing().when(mockScheduler).shutdown();
424
425         DOMStoreTransactionChain mockTxChain = mock(DOMStoreTransactionChain.class);
426         doNothing().when(mockTxChain).close();
427
428         Throwable mockCommitEx = new Exception("mock commit failure");
429         doAnswer(invocation -> {
430             DOMStoreThreePhaseCommitCohort mockCohort = mock(DOMStoreThreePhaseCommitCohort.class);
431             doReturn(Futures.immediateFailedFuture(mockCommitEx)).when(mockCohort).canCommit();
432             doReturn(Futures.immediateFuture(null)).when(mockCohort).abort();
433
434             doAnswer(notused -> {
435                 DOMStoreWriteTransaction mockWriteTx = mock(DOMStoreReadWriteTransaction .class);
436                 doNothing().when(mockWriteTx).write(any(), any());
437                 doNothing().when(mockWriteTx).merge(any(), any());
438                 doNothing().when(mockWriteTx).delete(any());
439                 doReturn(mockCohort).when(mockWriteTx).ready();
440                 return mockWriteTx;
441             }).when(mockTxChain).newReadWriteTransaction();
442
443             return mockTxChain;
444         }).doAnswer(invocation -> realOperStore.createTransactionChain()).when(spiedOperStore).createTransactionChain();
445
446         int timerInterval = 1;
447         try (StateProviderImpl stateProvider = new StateProviderImpl(getDataBroker(), timerInterval, tableTypeRegistry,
448                 stateCollector, "global-bgp", mockScheduler)) {
449             stateProvider.init();
450
451             ArgumentCaptor<Runnable> timerTask = ArgumentCaptor.forClass(Runnable.class);
452             verify(mockScheduler).scheduleAtFixedRate(timerTask.capture(), eq(0L), eq((long)timerInterval),
453                     eq(TimeUnit.SECONDS));
454
455             timerTask.getValue().run();
456
457             String lastError = RememberingLogger.getLastErrorThrowable().orElseThrow(
458                 () -> new AssertionError("Expected logged ERROR")).toString();
459             assertTrue("Last logged ERROR didn't contain expected string: " + lastError,
460                     lastError.contains(mockCommitEx.getMessage()));
461
462             RememberingLogger.resetLastError();
463
464             timerTask.getValue().run();
465
466             ImmutableList<LogCapture> loggedErrors = RememberingLogger.getErrorLogCaptures();
467             assertTrue("Expected no logged ERRORs: " + loggedErrors, loggedErrors.isEmpty());
468
469             verify(spiedOperStore, times(2)).createTransactionChain();
470         }
471     }
472
473     private static BgpNeighborStateAugmentation buildBgpNeighborStateAugmentation() {
474         final BgpNeighborStateAugmentation augmentation = new BgpNeighborStateAugmentationBuilder()
475                 .setMessages(new MessagesBuilder().setReceived(new ReceivedBuilder()
476                         .setNOTIFICATION(BigInteger.ONE).setUPDATE(BigInteger.ONE).build())
477                         .setSent(new SentBuilder().setNOTIFICATION(BigInteger.ONE).setUPDATE(BigInteger.ONE).build())
478                         .build()).build();
479         return augmentation;
480     }
481
482     private static AfiSafis buildAfiSafis() {
483         final NeighborAfiSafiStateAugmentationBuilder neighborAfiSafiStateAugmentation =
484                 new NeighborAfiSafiStateAugmentationBuilder().setActive(true).setPrefixes(
485                         new PrefixesBuilder().setSent(1L).setReceived(2L).setInstalled(1L).build());
486         final AfiSafi afiSafi = new AfiSafiBuilder()
487                 .setAfiSafiName(IPV4UNICAST.class)
488                 .setGracefulRestart(new GracefulRestartBuilder().setState(new StateBuilder().setEnabled(false)
489                         .addAugmentation(NeighborAfiSafiGracefulRestartStateAugmentation.class,
490                                 new NeighborAfiSafiGracefulRestartStateAugmentationBuilder()
491                                         .setAdvertised(true)
492                                         .setReceived(true)
493                                         .setLlStaleTimer(60L)
494                                         .setLlAdvertised(true)
495                                         .setLlReceived(true)
496                                         .build())
497                         .build()).build())
498                 .setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp
499                         .common.afi.safi.list.afi.safi.StateBuilder().setEnabled(false).addAugmentation(
500                                 NeighborAfiSafiStateAugmentation.class, neighborAfiSafiStateAugmentation.build())
501                         .build())
502                 .build();
503
504         return new AfiSafisBuilder().setAfiSafi(Collections.singletonList(afiSafi)).build();
505     }
506
507     private static ErrorHandling buildErrorHandling() {
508         final ErrorHandling errorHandling = new ErrorHandlingBuilder().setState(
509                 new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.error
510                         .handling.StateBuilder().setTreatAsWithdraw(false)
511                         .addAugmentation(NeighborErrorHandlingStateAugmentation.class,
512                                 new NeighborErrorHandlingStateAugmentationBuilder()
513                                         .setErroneousUpdateMessages(1L).build()).build()).build();
514         return errorHandling;
515     }
516
517     private static Timers buildTimers() {
518         final Timers timers = new TimersBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang
519                 .bgp.rev151009.bgp.neighbor.group.timers.StateBuilder()
520                 .setConnectRetry(BigDecimal.valueOf(30))
521                 .setHoldTime(BigDecimal.valueOf(90))
522                 .setKeepaliveInterval(BigDecimal.valueOf(30))
523                 .setMinimumAdvertisementInterval(BigDecimal.valueOf(30))
524                 .addAugmentation(NeighborTimersStateAugmentation.class, new NeighborTimersStateAugmentationBuilder()
525                         .setNegotiatedHoldTime(BigDecimal.TEN).setUptime(new Timeticks(1L)).build())
526                 .build()).build();
527         return timers;
528     }
529
530     private Transport buildTransport() {
531         final Transport transport = new TransportBuilder().setState(new org.opendaylight.yang.gen.v1.http.openconfig
532                 .net.yang.bgp.rev151009.bgp.neighbor.group.transport.StateBuilder()
533                 .setMtuDiscovery(false)
534                 .setPassiveMode(false)
535                 .addAugmentation(NeighborTransportStateAugmentation.class,
536                         new NeighborTransportStateAugmentationBuilder().setLocalPort(this.localPort)
537                                 .setRemotePort(this.remotePort)
538                                 .setRemoteAddress(this.neighborAddress).build())
539                 .build()).build();
540         return transport;
541     }
542
543     private GracefulRestart buildGracefulRestart() {
544         final NeighborGracefulRestartStateAugmentationBuilder gracefulAugmentation
545                 = new NeighborGracefulRestartStateAugmentationBuilder();
546         gracefulAugmentation.setPeerRestarting(false);
547         gracefulAugmentation.setLocalRestarting(false);
548         gracefulAugmentation.setPeerRestartTime(0);
549         gracefulAugmentation.setLocalRestarting(true)
550                 .setPeerRestarting(true)
551                 .setPeerRestartTime(this.restartTime)
552                 .setMode(BgpAfiSafiGracefulRestartState.Mode.BILATERAL);
553         final GracefulRestart gracefulRestart = new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp
554                 .rev151009.bgp.graceful.restart.GracefulRestartBuilder().setState(new org.opendaylight.yang.gen.v1.http
555                 .openconfig.net.yang.bgp.rev151009.bgp.graceful.restart.graceful.restart.StateBuilder()
556                 .addAugmentation(NeighborGracefulRestartStateAugmentation.class,
557                         gracefulAugmentation.build()).build()).build();
558         return gracefulRestart;
559     }
560
561     private Global buildGlobalExpected(final long prefixesAndPaths) {
562         return new GlobalBuilder()
563                 .setState(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.global.base
564                         .StateBuilder().setRouterId(new Ipv4Address(this.bgpId.getValue()))
565                         .setTotalPrefixes(prefixesAndPaths).setTotalPaths(prefixesAndPaths).setAs(this.as).build())
566                 .setAfiSafis(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.global.base
567                         .AfiSafisBuilder().setAfiSafi(Collections.singletonList(new AfiSafiBuilder()
568                         .setAfiSafiName(IPV4UNICAST.class).setState(new org.opendaylight.yang.gen.v1.http.openconfig
569                                 .net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.afi.safi.StateBuilder()
570                                 .setEnabled(false)
571                                 .addAugmentation(GlobalAfiSafiStateAugmentation.class,
572                                         new GlobalAfiSafiStateAugmentationBuilder()
573                                                 .setTotalPaths(prefixesAndPaths).setTotalPrefixes(prefixesAndPaths)
574                                                 .build()).build()).build()))
575                         .build()).build();
576     }
577
578     private static PeerGroup buildGroupExpected() {
579         return new PeerGroupBuilder().setPeerGroupName("test-group").setState(new org.opendaylight.yang.gen.v1.http
580             .openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.StateBuilder()
581             .setSendCommunity(CommunityType.NONE)
582             .setRouteFlapDamping(false)
583             .addAugmentation(PeerGroupStateAugmentation.class,
584                 new PeerGroupStateAugmentationBuilder().setTotalPaths(1L).setTotalPrefixes(1L)
585                     .build()).build())
586             .build();
587     }
588 }