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