2 * Copyright (c) 2014 Brocade Communications Systems, Inc. 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
9 package org.opendaylight.netconf.sal.connect.netconf.listener;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
15 import static org.mockito.Matchers.any;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Matchers.same;
18 import static org.mockito.Mockito.doNothing;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.never;
22 import static org.mockito.Mockito.reset;
23 import static org.mockito.Mockito.spy;
24 import static org.mockito.Mockito.timeout;
25 import static org.mockito.Mockito.verify;
26 import static org.opendaylight.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
27 import com.google.common.base.CharMatcher;
28 import com.google.common.base.Strings;
29 import com.google.common.collect.Sets;
30 import com.google.common.util.concurrent.ListenableFuture;
31 import io.netty.channel.ChannelFuture;
32 import io.netty.channel.EventLoopGroup;
33 import io.netty.channel.nio.NioEventLoopGroup;
34 import io.netty.util.HashedWheelTimer;
35 import io.netty.util.Timer;
36 import io.netty.util.concurrent.Future;
37 import io.netty.util.concurrent.GenericFutureListener;
38 import io.netty.util.concurrent.GlobalEventExecutor;
39 import java.io.ByteArrayInputStream;
40 import java.net.InetSocketAddress;
41 import java.util.ArrayList;
42 import java.util.Collection;
43 import java.util.Collections;
44 import java.util.UUID;
45 import java.util.concurrent.TimeUnit;
46 import java.util.concurrent.TimeoutException;
47 import javax.xml.parsers.DocumentBuilderFactory;
48 import javax.xml.parsers.ParserConfigurationException;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.mockito.ArgumentCaptor;
52 import org.mockito.Mock;
53 import org.mockito.MockitoAnnotations;
54 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
55 import org.opendaylight.netconf.api.NetconfMessage;
56 import org.opendaylight.netconf.api.NetconfTerminationReason;
57 import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
58 import org.opendaylight.netconf.client.NetconfClientSession;
59 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
60 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
61 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
62 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
63 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
64 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
65 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
66 import org.opendaylight.protocol.framework.ReconnectStrategy;
67 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
68 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.common.RpcError;
71 import org.opendaylight.yangtools.yang.common.RpcResult;
72 import org.w3c.dom.Document;
73 import org.w3c.dom.Element;
75 public class NetconfDeviceCommunicatorTest {
78 NetconfClientSession mockSession;
81 RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> mockDevice;
83 NetconfDeviceCommunicator communicator;
86 public void setUp() throws Exception {
87 MockitoAnnotations.initMocks( this );
89 communicator = new NetconfDeviceCommunicator( new RemoteDeviceId( "test", InetSocketAddress.createUnresolved("localhost", 22)), mockDevice, 10);
93 doReturn(Collections.<String>emptySet()).when(mockSession).getServerCapabilities();
94 doNothing().when(mockDevice).onRemoteSessionUp(any(NetconfSessionPreferences.class),
95 any(NetconfDeviceCommunicator.class));
96 communicator.onSessionUp(mockSession);
99 private ListenableFuture<RpcResult<NetconfMessage>> sendRequest() throws Exception {
100 return sendRequest( UUID.randomUUID().toString(), true );
103 @SuppressWarnings("unchecked")
104 private ListenableFuture<RpcResult<NetconfMessage>> sendRequest( final String messageID, final boolean doLastTest ) throws Exception {
105 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
106 Element element = doc.createElement( "request" );
107 element.setAttribute( "message-id", messageID );
108 doc.appendChild( element );
109 NetconfMessage message = new NetconfMessage( doc );
111 ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
112 doReturn( mockChannelFuture ).when( mockChannelFuture )
113 .addListener( any( (GenericFutureListener.class ) ) );
114 doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
116 ListenableFuture<RpcResult<NetconfMessage>> resultFuture =
117 communicator.sendRequest( message, QName.create( "mock rpc" ) );
119 assertNotNull("ListenableFuture is null", resultFuture);
125 public void testOnSessionUp() {
126 String testCapability = "urn:opendaylight:params:xml:ns:test?module=test-module&revision=2014-06-02";
127 Collection<String> serverCapabilities =
128 Sets.newHashSet( NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
129 NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
131 doReturn( serverCapabilities ).when( mockSession ).getServerCapabilities();
133 ArgumentCaptor<NetconfSessionPreferences> NetconfSessionPreferences =
134 ArgumentCaptor.forClass( NetconfSessionPreferences.class );
135 doNothing().when( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
137 communicator.onSessionUp( mockSession );
139 verify( mockSession ).getServerCapabilities();
140 verify( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
142 NetconfSessionPreferences actualCapabilites = NetconfSessionPreferences.getValue();
143 assertEquals( "containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
144 NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()) );
145 assertEquals( "containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability) );
146 assertEquals( "getModuleBasedCaps", Sets.newHashSet(
147 QName.create( "urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module" )),
148 actualCapabilites.getModuleBasedCaps() );
149 assertEquals( "isRollbackSupported", true, actualCapabilites.isRollbackSupported() );
150 assertEquals( "isMonitoringSupported", true, actualCapabilites.isMonitoringSupported() );
153 @SuppressWarnings("unchecked")
155 public void testOnSessionDown() throws Exception {
158 ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest();
159 ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
161 doNothing().when( mockDevice ).onRemoteSessionDown();
163 communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
165 verifyErrorRpcResult( resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
166 verifyErrorRpcResult( resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
168 verify( mockDevice ).onRemoteSessionDown();
172 communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
174 verify( mockDevice, never() ).onRemoteSessionDown();
178 public void testOnSessionTerminated() throws Exception {
181 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest();
183 doNothing().when( mockDevice ).onRemoteSessionDown();
185 String reasonText = "testing terminate";
186 NetconfTerminationReason reason = new NetconfTerminationReason( reasonText );
187 communicator.onSessionTerminated( mockSession, reason );
189 RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.TRANSPORT,
190 "operation-failed" );
191 assertEquals( "RpcError message", reasonText, rpcError.getMessage() );
193 verify( mockDevice ).onRemoteSessionDown();
197 public void testClose() throws Exception {
198 communicator.close();
199 verify( mockDevice, never() ).onRemoteSessionDown();
202 @SuppressWarnings({ "rawtypes", "unchecked" })
204 public void testSendRequest() throws Exception {
207 NetconfMessage message = new NetconfMessage(
208 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
209 QName rpc = QName.create( "mock rpc" );
211 ArgumentCaptor<GenericFutureListener> futureListener =
212 ArgumentCaptor.forClass( GenericFutureListener.class );
214 ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
215 doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
216 doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
218 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
220 verify( mockSession ).sendMessage( same( message ) );
222 assertNotNull( "ListenableFuture is null", resultFuture );
224 verify( mockChannelFuture ).addListener( futureListener.capture() );
225 Future<Void> operationFuture = mock( Future.class );
226 doReturn( true ).when( operationFuture ).isSuccess();
227 doReturn( true ).when( operationFuture ).isDone();
228 futureListener.getValue().operationComplete( operationFuture );
231 resultFuture.get( 1, TimeUnit.MILLISECONDS ); // verify it's not cancelled or has an error set
233 catch( TimeoutException e ) {} // expected
237 public void testSendRequestWithNoSession() throws Exception {
238 NetconfMessage message = new NetconfMessage(
239 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
240 QName rpc = QName.create( "mock rpc" );
242 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
244 assertNotNull( "ListenableFuture is null", resultFuture );
246 // Should have an immediate result
247 RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
249 verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
252 @SuppressWarnings({ "rawtypes", "unchecked" })
254 public void testSendRequestWithWithSendFailure() throws Exception {
257 NetconfMessage message = new NetconfMessage(
258 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
259 QName rpc = QName.create( "mock rpc" );
261 ArgumentCaptor<GenericFutureListener> futureListener =
262 ArgumentCaptor.forClass( GenericFutureListener.class );
264 ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
265 doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
266 doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
268 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
270 assertNotNull( "ListenableFuture is null", resultFuture );
272 verify( mockChannelFuture ).addListener( futureListener.capture() );
274 Future<Void> operationFuture = mock( Future.class );
275 doReturn( false ).when( operationFuture ).isSuccess();
276 doReturn( true ).when( operationFuture ).isDone();
277 doReturn( new Exception( "mock error" ) ).when( operationFuture ).cause();
278 futureListener.getValue().operationComplete( operationFuture );
280 // Should have an immediate result
281 RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
283 RpcError rpcError = verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
284 assertEquals( "RpcError message contains \"mock error\"", true,
285 rpcError.getMessage().contains( "mock error" ) );
288 private static NetconfMessage createSuccessResponseMessage( final String messageID ) throws ParserConfigurationException {
289 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
290 Element rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
291 rpcReply.setAttribute( "message-id", messageID );
292 Element element = doc.createElementNS( "ns", "data" );
293 element.setTextContent( messageID );
294 rpcReply.appendChild( element );
295 doc.appendChild( rpcReply );
297 return new NetconfMessage( doc );
300 //Test scenario verifying whether missing message is handled
302 public void testOnMissingResponseMessage() throws Exception {
306 String messageID1 = UUID.randomUUID().toString();
307 ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
309 String messageID2 = UUID.randomUUID().toString();
310 ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
312 String messageID3 = UUID.randomUUID().toString();
313 ListenableFuture<RpcResult<NetconfMessage>> resultFuture3 = sendRequest( messageID3, true );
315 //response messages 1,2 are omitted
316 communicator.onMessage( mockSession, createSuccessResponseMessage( messageID3 ) );
318 verifyResponseMessage( resultFuture3.get(), messageID3 );
322 public void testOnSuccessfulResponseMessage() throws Exception {
325 String messageID1 = UUID.randomUUID().toString();
326 ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
328 String messageID2 = UUID.randomUUID().toString();
329 ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
331 communicator.onMessage( mockSession, createSuccessResponseMessage( messageID1 ) );
332 communicator.onMessage( mockSession, createSuccessResponseMessage( messageID2 ) );
334 verifyResponseMessage( resultFuture1.get(), messageID1 );
335 verifyResponseMessage( resultFuture2.get(), messageID2 );
339 public void testOnResponseMessageWithError() throws Exception {
342 String messageID = UUID.randomUUID().toString();
343 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
345 communicator.onMessage( mockSession, createErrorResponseMessage( messageID ) );
347 RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.RPC,
348 "missing-attribute" );
349 assertEquals( "RpcError message", "Missing attribute", rpcError.getMessage() );
351 String errorInfo = rpcError.getInfo();
352 assertNotNull( "RpcError info is null", errorInfo );
353 assertEquals( "Error info contains \"foo\"", true,
354 errorInfo.contains( "<bad-attribute>foo</bad-attribute>" ) );
355 assertEquals( "Error info contains \"bar\"", true,
356 errorInfo.contains( "<bad-element>bar</bad-element>" ) );
360 * Test whether reconnect is scheduled properly
363 public void testNetconfDeviceReconnectInCommunicator() throws Exception {
364 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(RemoteDevice.class);
366 final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
367 final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {
369 public int getConnectTimeout() throws Exception {
370 return timedReconnectStrategy.getConnectTimeout();
374 public Future<Void> scheduleReconnect(final Throwable cause) {
375 return timedReconnectStrategy.scheduleReconnect(cause);
379 public void reconnectSuccessful() {
380 timedReconnectStrategy.reconnectSuccessful();
384 final EventLoopGroup group = new NioEventLoopGroup();
385 final Timer time = new HashedWheelTimer();
387 final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
388 final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create()
389 .withAddress(new InetSocketAddress("localhost", 65000))
390 .withReconnectStrategy(reconnectStrategy)
391 .withConnectStrategyFactory(new ReconnectStrategyFactory() {
393 public ReconnectStrategy createReconnectStrategy() {
394 return reconnectStrategy;
397 .withAuthHandler(new LoginPassword("admin", "admin"))
398 .withConnectionTimeoutMillis(10000)
399 .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
400 .withSessionListener(listener)
403 listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);
405 verify(reconnectStrategy, timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
408 group.shutdownGracefully();
413 public void testOnResponseMessageWithWrongMessageID() throws Exception {
416 String messageID = UUID.randomUUID().toString();
417 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
419 communicator.onMessage( mockSession, createSuccessResponseMessage( UUID.randomUUID().toString() ) );
421 RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.PROTOCOL,
423 assertEquals( "RpcError message non-empty", true,
424 !Strings.isNullOrEmpty( rpcError.getMessage() ) );
426 String errorInfo = rpcError.getInfo();
427 assertNotNull( "RpcError info is null", errorInfo );
428 assertEquals( "Error info contains \"actual-message-id\"", true,
429 errorInfo.contains( "actual-message-id" ) );
430 assertEquals( "Error info contains \"expected-message-id\"", true,
431 errorInfo.contains( "expected-message-id" ) );
435 public void testConcurrentMessageLimit() throws Exception {
437 ArrayList<String> messageID = new ArrayList<>();
439 for (int i = 0; i < 10; i++) {
440 messageID.add(UUID.randomUUID().toString());
441 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(messageID.get(i), false);
442 assertEquals("ListenableFuture is null", true, resultFuture instanceof UncancellableFuture);
445 final String notWorkingMessageID = UUID.randomUUID().toString();
446 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(notWorkingMessageID, false);
447 assertEquals("ListenableFuture is null", false, resultFuture instanceof UncancellableFuture);
449 communicator.onMessage(mockSession, createSuccessResponseMessage(messageID.get(0)));
451 resultFuture = sendRequest(messageID.get(0), false);
452 assertNotNull("ListenableFuture is null", resultFuture);
455 private static NetconfMessage createErrorResponseMessage( final String messageID ) throws Exception {
457 "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"" +
458 " message-id=\"" + messageID + "\">" +
460 " <error-type>rpc</error-type>" +
461 " <error-tag>missing-attribute</error-tag>" +
462 " <error-severity>error</error-severity>" +
463 " <error-message>Missing attribute</error-message>" +
465 " <bad-attribute>foo</bad-attribute>" +
466 " <bad-element>bar</bad-element>" +
471 ByteArrayInputStream bis = new ByteArrayInputStream( xmlStr.getBytes() );
472 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( bis );
473 return new NetconfMessage( doc );
476 private static void verifyResponseMessage( final RpcResult<NetconfMessage> rpcResult, final String dataText ) {
477 assertNotNull( "RpcResult is null", rpcResult );
478 assertEquals( "isSuccessful", true, rpcResult.isSuccessful() );
479 NetconfMessage messageResult = rpcResult.getResult();
480 assertNotNull( "getResult", messageResult );
481 // List<SimpleNode<?>> nodes = messageResult.getSimpleNodesByName(
482 // QName.create( URI.create( "ns" ), null, "data" ) );
483 // assertNotNull( "getSimpleNodesByName", nodes );
484 // assertEquals( "List<SimpleNode<?>> size", 1, nodes.size() );
485 // assertEquals( "SimpleNode value", dataText, nodes.iterator().next().getValue() );
488 private static RpcError verifyErrorRpcResult( final RpcResult<NetconfMessage> rpcResult,
489 final RpcError.ErrorType expErrorType, final String expErrorTag ) {
490 assertNotNull( "RpcResult is null", rpcResult );
491 assertEquals( "isSuccessful", false, rpcResult.isSuccessful() );
492 assertNotNull( "RpcResult errors is null", rpcResult.getErrors() );
493 assertEquals( "Errors size", 1, rpcResult.getErrors().size() );
494 RpcError rpcError = rpcResult.getErrors().iterator().next();
495 assertEquals( "getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity() );
496 assertEquals( "getErrorType", expErrorType, rpcError.getErrorType() );
497 assertEquals( "getErrorTag", expErrorTag, rpcError.getTag() );
499 final String msg = rpcError.getMessage();
500 assertNotNull("getMessage is null", msg);
501 assertFalse("getMessage is empty", msg.isEmpty());
502 assertFalse("getMessage is blank", CharMatcher.WHITESPACE.matchesAllOf(msg));