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