Fix NetconfNodeHandler.connect() accounting
[netconf.git] / apps / netconf-topology / src / test / java / org / opendaylight / netconf / topology / spi / NetconfNodeHandlerTest.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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.netconf.topology.spi;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.mockito.ArgumentMatchers.any;
12 import static org.mockito.ArgumentMatchers.eq;
13 import static org.mockito.Mockito.doNothing;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.times;
16 import static org.mockito.Mockito.verify;
17 import static org.mockito.Mockito.verifyNoInteractions;
18
19 import com.google.common.net.InetAddresses;
20 import io.netty.util.concurrent.DefaultPromise;
21 import io.netty.util.concurrent.EventExecutor;
22 import io.netty.util.concurrent.ImmediateEventExecutor;
23 import io.netty.util.concurrent.ScheduledFuture;
24 import io.netty.util.concurrent.SucceededFuture;
25 import java.net.InetSocketAddress;
26 import java.util.concurrent.Executor;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.TimeUnit;
29 import org.junit.Before;
30 import org.junit.BeforeClass;
31 import org.junit.Test;
32 import org.junit.runner.RunWith;
33 import org.mockito.ArgumentCaptor;
34 import org.mockito.Captor;
35 import org.mockito.Mock;
36 import org.mockito.junit.MockitoJUnitRunner;
37 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
38 import org.opendaylight.netconf.client.NetconfClientDispatcher;
39 import org.opendaylight.netconf.client.NetconfClientSession;
40 import org.opendaylight.netconf.client.mdsal.NetconfDeviceSchema;
41 import org.opendaylight.netconf.client.mdsal.api.BaseNetconfSchemas;
42 import org.opendaylight.netconf.client.mdsal.api.CredentialProvider;
43 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
44 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
45 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceHandler;
46 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
47 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
48 import org.opendaylight.netconf.client.mdsal.api.SchemaResourceManager;
49 import org.opendaylight.netconf.client.mdsal.api.SslHandlerFactoryProvider;
50 import org.opendaylight.netconf.client.mdsal.impl.DefaultBaseNetconfSchemas;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.credentials.credentials.LoginPasswordBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNodeBuilder;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
58 import org.opendaylight.yangtools.yang.common.Decimal64;
59 import org.opendaylight.yangtools.yang.common.Uint16;
60 import org.opendaylight.yangtools.yang.common.Uint32;
61 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
62
63
64 @RunWith(MockitoJUnitRunner.StrictStubs.class)
65 public class NetconfNodeHandlerTest {
66     private static final RemoteDeviceId DEVICE_ID = new RemoteDeviceId("netconf-topology",
67         new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
68     private static final NodeId NODE_ID = new NodeId("testing-node");
69
70     private static BaseNetconfSchemas BASE_SCHEMAS;
71
72     // Core setup
73     @Mock
74     private ScheduledExecutorService keepaliveExecutor;
75     @Mock
76     private SchemaResourceManager schemaManager;
77     @Mock
78     private Executor processingExecutor;
79     @Mock
80     private DeviceActionFactory deviceActionFactory;
81     @Mock
82     private RemoteDeviceHandler delegate;
83
84     // DefaultNetconfClientConfigurationBuilderFactory setup
85     @Mock
86     private SslHandlerFactoryProvider sslHandlerFactoryProvider;
87     @Mock
88     private AAAEncryptionService encryptionService;
89     @Mock
90     private CredentialProvider credentialProvider;
91
92     // Mock client dispatcher-related things
93     @Mock
94     private NetconfClientDispatcher clientDispatcher;
95     @Mock
96     private NetconfClientSession clientSession;
97     @Captor
98     private ArgumentCaptor<NetconfDeviceSchema> schemaCaptor;
99     @Captor
100     private ArgumentCaptor<NetconfSessionPreferences> prefsCaptor;
101     @Captor
102     private ArgumentCaptor<RemoteDeviceServices> servicesCaptor;
103
104     // Mock eventExecutor-related things
105     @Mock
106     private EventExecutor eventExecutor;
107     @Mock
108     private ScheduledFuture<?> scheduleFuture;
109     @Captor
110     private ArgumentCaptor<Runnable> scheduleCaptor;
111
112     private NetconfNodeHandler handler;
113
114     @BeforeClass
115     public static final void beforeClass() throws Exception {
116         BASE_SCHEMAS = new DefaultBaseNetconfSchemas(new DefaultYangParserFactory());
117     }
118
119     @BeforeClass
120     public static final void afterClass() throws Exception {
121         BASE_SCHEMAS = null;
122     }
123
124     @Before
125     public void setUp() {
126         // Instantiate the handler
127         handler = new NetconfNodeHandler(clientDispatcher, eventExecutor, keepaliveExecutor, BASE_SCHEMAS,
128             schemaManager, processingExecutor,
129             new DefaultNetconfClientConfigurationBuilderFactory(encryptionService, credentialProvider,
130                 sslHandlerFactoryProvider),
131             deviceActionFactory, delegate, DEVICE_ID, NODE_ID, new NetconfNodeBuilder()
132                 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
133                 .setPort(new PortNumber(Uint16.valueOf(9999)))
134                 .setReconnectOnChangedSchema(true)
135                 .setSchemaless(true)
136                 .setTcpOnly(true)
137                 .setSleepFactor(Decimal64.valueOf("1.5"))
138                 .setConcurrentRpcLimit(Uint16.ONE)
139                 // One reconnection attempt
140                 .setMaxConnectionAttempts(Uint32.TWO)
141                 .setDefaultRequestTimeoutMillis(Uint32.valueOf(1000))
142                 .setBetweenAttemptsTimeoutMillis(Uint16.valueOf(100))
143                 .setKeepaliveDelay(Uint32.valueOf(1000))
144                 .setConnectionTimeoutMillis(Uint32.valueOf(1000))
145                 .setCredentials(new LoginPasswordBuilder().setUsername("testuser").setPassword("testpassword").build())
146                 .build(), null);
147     }
148
149     @Test
150     public void successfullOnDeviceConnectedPropagates() {
151         assertSuccessfulConnect();
152         assertEquals(1, handler.attempts());
153
154         // when the device is connected, we propagate the information
155         // TODO: create non-null values
156         doNothing().when(delegate).onDeviceConnected(null, null, null);
157         handler.onDeviceConnected(null, null, null);
158         assertEquals(0, handler.attempts());
159     }
160
161     @Test
162     public void downAfterUpCausesReconnect() {
163         // Let's borrow common bits
164         successfullOnDeviceConnectedPropagates();
165
166         // when the device is connected, we propagate the information and initiate reconnect
167         doNothing().when(delegate).onDeviceDisconnected();
168         doReturn(scheduleFuture).when(eventExecutor).schedule(scheduleCaptor.capture(), eq(100L),
169             eq(TimeUnit.MILLISECONDS));
170         handler.onDeviceDisconnected();
171
172         assertEquals(1, handler.attempts());
173
174         // and when we run the task, we get a clientDispatcher invocation, but attempts are still the same
175         scheduleCaptor.getValue().run();
176         verify(clientDispatcher, times(2)).createClient(any());
177         assertEquals(1, handler.attempts());
178     }
179
180     @Test
181     public void socketFailuresAreRetried() {
182         final var firstPromise = new DefaultPromise<NetconfClientSession>(ImmediateEventExecutor.INSTANCE);
183         final var secondPromise = new DefaultPromise<NetconfClientSession>(ImmediateEventExecutor.INSTANCE);
184         doReturn(firstPromise, secondPromise).when(clientDispatcher).createClient(any());
185         handler.connect();
186         assertEquals(1, handler.attempts());
187
188         // FIXME: NETCONF-1097 remove this stubbing
189         final var firstFailure = new AssertionError("first");
190         doNothing().when(delegate).onDeviceFailed(firstFailure);
191         doReturn(scheduleFuture).when(eventExecutor).schedule(scheduleCaptor.capture(), eq(150L),
192             eq(TimeUnit.MILLISECONDS));
193         firstPromise.setFailure(firstFailure);
194
195         assertEquals(2, handler.attempts());
196
197         // and when we run the task, we get a clientDispatcher invocation, but attempts are still the same
198         scheduleCaptor.getValue().run();
199         verify(clientDispatcher, times(2)).createClient(any());
200         assertEquals(2, handler.attempts());
201
202         // now report the second failure
203         final var secondFailure = new AssertionError("second");
204         doNothing().when(delegate).onDeviceFailed(secondFailure);
205         secondPromise.setFailure(secondFailure);
206
207         // but nothing else happens
208         assertEquals(2, handler.attempts());
209     }
210
211     // Initiate a connect() which results in immediate clientDispatcher report. No interactions with delegate may occur,
212     // as this is just a prelude to a follow-up callback
213     private void assertSuccessfulConnect() {
214         doReturn(new SucceededFuture<>(ImmediateEventExecutor.INSTANCE, clientSession))
215             .when(clientDispatcher).createClient(any());
216         handler.connect();
217         verify(clientDispatcher).createClient(any());
218         verifyNoInteractions(delegate);
219     }
220 }