2 * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.netconf.topology.spi;
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;
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;
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");
72 private static BaseNetconfSchemas BASE_SCHEMAS;
76 private ScheduledExecutorService keepaliveExecutor;
78 private SchemaResourceManager schemaManager;
80 private Executor processingExecutor;
82 private DeviceActionFactory deviceActionFactory;
84 private RemoteDeviceHandler delegate;
86 // DefaultNetconfClientConfigurationBuilderFactory setup
88 private SslHandlerFactoryProvider sslHandlerFactoryProvider;
90 private AAAEncryptionService encryptionService;
92 private CredentialProvider credentialProvider;
94 // Mock client dispatcher-related things
96 private NetconfClientDispatcher clientDispatcher;
98 private NetconfClientSession clientSession;
100 private ArgumentCaptor<NetconfDeviceSchema> schemaCaptor;
102 private ArgumentCaptor<NetconfSessionPreferences> prefsCaptor;
104 private ArgumentCaptor<RemoteDeviceServices> servicesCaptor;
106 // Mock eventExecutor-related things
108 private EventExecutor eventExecutor;
110 private ScheduledFuture<?> scheduleFuture;
112 private ArgumentCaptor<Runnable> scheduleCaptor;
114 private NetconfNodeHandler handler;
117 public static final void beforeClass() throws Exception {
118 BASE_SCHEMAS = new DefaultBaseNetconfSchemas(new DefaultYangParserFactory());
122 public static final void afterClass() throws Exception {
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)
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())
152 public void successfullOnDeviceConnectedPropagates() {
153 assertSuccessfulConnect();
154 assertEquals(1, handler.attempts());
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());
164 public void failedSchemaCausesReconnect() {
165 assertSuccessfulConnect();
166 assertEquals(1, handler.attempts());
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"));
173 assertEquals(2, handler.attempts());
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());
182 public void downAfterUpCausesReconnect() {
183 // Let's borrow common bits
184 successfullOnDeviceConnectedPropagates();
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();
192 assertEquals(1, handler.attempts());
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());
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());
206 assertEquals(1, handler.attempts());
208 doReturn(scheduleFuture).when(eventExecutor).schedule(scheduleCaptor.capture(), eq(150L),
209 eq(TimeUnit.MILLISECONDS));
210 firstPromise.setFailure(new AssertionError("first"));
212 assertEquals(2, handler.attempts());
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());
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));
225 // but nothing else happens
226 assertEquals(2, handler.attempts());
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());
235 verify(clientDispatcher).createClient(any());
236 verifyNoInteractions(delegate);