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.controller.sal.connect.netconf.listener;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.eq;
16 import static org.mockito.Matchers.same;
17 import static org.mockito.Mockito.doNothing;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.never;
21 import static org.mockito.Mockito.reset;
22 import static org.mockito.Mockito.spy;
23 import static org.mockito.Mockito.timeout;
24 import static org.mockito.Mockito.verify;
25 import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
26 import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
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.Collection;
42 import java.util.Collections;
43 import java.util.UUID;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.TimeoutException;
46 import javax.xml.parsers.DocumentBuilderFactory;
47 import javax.xml.parsers.ParserConfigurationException;
48 import org.apache.commons.lang3.StringUtils;
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.netconf.api.NetconfMessage;
55 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
56 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
57 import org.opendaylight.controller.netconf.client.NetconfClientSession;
58 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
59 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
60 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
61 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
62 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
63 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
64 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
65 import org.opendaylight.protocol.framework.ReconnectStrategy;
66 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
67 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
68 import org.opendaylight.yangtools.yang.common.QName;
69 import org.opendaylight.yangtools.yang.common.RpcError;
70 import org.opendaylight.yangtools.yang.common.RpcResult;
71 import org.w3c.dom.Document;
72 import org.w3c.dom.Element;
74 public class NetconfDeviceCommunicatorTest {
77 NetconfClientSession mockSession;
80 RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> mockDevice;
82 NetconfDeviceCommunicator communicator;
85 public void setUp() throws Exception {
86 MockitoAnnotations.initMocks( this );
88 communicator = new NetconfDeviceCommunicator( new RemoteDeviceId( "test" ), mockDevice);
91 @SuppressWarnings("unchecked")
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() );
103 @SuppressWarnings("unchecked")
104 private ListenableFuture<RpcResult<NetconfMessage>> sendRequest( String messageID ) 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 );
124 public void testOnSessionUp() {
125 String testCapability = "urn:opendaylight:params:xml:ns:test?module=test-module&revision=2014-06-02";
126 Collection<String> serverCapabilities =
127 Sets.newHashSet( NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
128 NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
130 doReturn( serverCapabilities ).when( mockSession ).getServerCapabilities();
132 ArgumentCaptor<NetconfSessionPreferences> NetconfSessionPreferences =
133 ArgumentCaptor.forClass( NetconfSessionPreferences.class );
134 doNothing().when( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
136 communicator.onSessionUp( mockSession );
138 verify( mockSession ).getServerCapabilities();
139 verify( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
141 NetconfSessionPreferences actualCapabilites = NetconfSessionPreferences.getValue();
142 assertEquals( "containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
143 NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()) );
144 assertEquals( "containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability) );
145 assertEquals( "getModuleBasedCaps", Sets.newHashSet(
146 QName.create( "urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module" )),
147 actualCapabilites.getModuleBasedCaps() );
148 assertEquals( "isRollbackSupported", true, actualCapabilites.isRollbackSupported() );
149 assertEquals( "isMonitoringSupported", true, actualCapabilites.isMonitoringSupported() );
152 @SuppressWarnings("unchecked")
154 public void testOnSessionDown() throws Exception {
157 ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest();
158 ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
160 doNothing().when( mockDevice ).onRemoteSessionDown();
162 communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
164 verifyErrorRpcResult( resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
165 verifyErrorRpcResult( resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
167 verify( mockDevice ).onRemoteSessionDown();
171 communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
173 verify( mockDevice, never() ).onRemoteSessionDown();
177 public void testOnSessionTerminated() throws Exception {
180 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest();
182 doNothing().when( mockDevice ).onRemoteSessionDown();
184 String reasonText = "testing terminate";
185 NetconfTerminationReason reason = new NetconfTerminationReason( reasonText );
186 communicator.onSessionTerminated( mockSession, reason );
188 RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.TRANSPORT,
189 "operation-failed" );
190 assertEquals( "RpcError message", reasonText, rpcError.getMessage() );
192 verify( mockDevice ).onRemoteSessionDown();
196 public void testClose() throws Exception {
197 communicator.close();
198 verify( mockDevice, never() ).onRemoteSessionDown();
201 @SuppressWarnings({ "rawtypes", "unchecked" })
203 public void testSendRequest() throws Exception {
206 NetconfMessage message = new NetconfMessage(
207 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
208 QName rpc = QName.create( "mock rpc" );
210 ArgumentCaptor<GenericFutureListener> futureListener =
211 ArgumentCaptor.forClass( GenericFutureListener.class );
213 ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
214 doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
215 doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
217 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
219 verify( mockSession ).sendMessage( same( message ) );
221 assertNotNull( "ListenableFuture is null", resultFuture );
223 verify( mockChannelFuture ).addListener( futureListener.capture() );
224 Future<Void> operationFuture = mock( Future.class );
225 doReturn( true ).when( operationFuture ).isSuccess();
226 doReturn( true ).when( operationFuture ).isDone();
227 futureListener.getValue().operationComplete( operationFuture );
230 resultFuture.get( 1, TimeUnit.MILLISECONDS ); // verify it's not cancelled or has an error set
232 catch( TimeoutException e ) {} // expected
236 public void testSendRequestWithNoSession() throws Exception {
237 NetconfMessage message = new NetconfMessage(
238 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
239 QName rpc = QName.create( "mock rpc" );
241 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
243 assertNotNull( "ListenableFuture is null", resultFuture );
245 // Should have an immediate result
246 RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
248 verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
251 @SuppressWarnings({ "rawtypes", "unchecked" })
253 public void testSendRequestWithWithSendFailure() throws Exception {
256 NetconfMessage message = new NetconfMessage(
257 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
258 QName rpc = QName.create( "mock rpc" );
260 ArgumentCaptor<GenericFutureListener> futureListener =
261 ArgumentCaptor.forClass( GenericFutureListener.class );
263 ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
264 doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
265 doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
267 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
269 assertNotNull( "ListenableFuture is null", resultFuture );
271 verify( mockChannelFuture ).addListener( futureListener.capture() );
273 Future<Void> operationFuture = mock( Future.class );
274 doReturn( false ).when( operationFuture ).isSuccess();
275 doReturn( true ).when( operationFuture ).isDone();
276 doReturn( new Exception( "mock error" ) ).when( operationFuture ).cause();
277 futureListener.getValue().operationComplete( operationFuture );
279 // Should have an immediate result
280 RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
282 RpcError rpcError = verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
283 assertEquals( "RpcError message contains \"mock error\"", true,
284 rpcError.getMessage().contains( "mock error" ) );
287 private NetconfMessage createSuccessResponseMessage( String messageID ) throws ParserConfigurationException {
288 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
289 Element rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_REPLY_KEY );
290 rpcReply.setAttribute( "message-id", messageID );
291 Element element = doc.createElementNS( "ns", "data" );
292 element.setTextContent( messageID );
293 rpcReply.appendChild( element );
294 doc.appendChild( rpcReply );
296 return new NetconfMessage( doc );
300 public void testOnSuccessfulResponseMessage() throws Exception {
303 String messageID1 = UUID.randomUUID().toString();
304 ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1 );
306 String messageID2 = UUID.randomUUID().toString();
307 ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2 );
309 communicator.onMessage( mockSession, createSuccessResponseMessage( messageID1 ) );
310 communicator.onMessage( mockSession, createSuccessResponseMessage( messageID2 ) );
312 verifyResponseMessage( resultFuture1.get(), messageID1 );
313 verifyResponseMessage( resultFuture2.get(), messageID2 );
317 public void testOnResponseMessageWithError() throws Exception {
320 String messageID = UUID.randomUUID().toString();
321 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID );
323 communicator.onMessage( mockSession, createErrorResponseMessage( messageID ) );
325 RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.RPC,
326 "missing-attribute" );
327 assertEquals( "RpcError message", "Missing attribute", rpcError.getMessage() );
329 String errorInfo = rpcError.getInfo();
330 assertNotNull( "RpcError info is null", errorInfo );
331 assertEquals( "Error info contains \"foo\"", true,
332 errorInfo.contains( "<bad-attribute>foo</bad-attribute>" ) );
333 assertEquals( "Error info contains \"bar\"", true,
334 errorInfo.contains( "<bad-element>bar</bad-element>" ) );
338 * Test whether reconnect is scheduled properly
341 public void testNetconfDeviceReconnectInCommunicator() throws Exception {
342 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(RemoteDevice.class);
344 final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
345 final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {
347 public int getConnectTimeout() throws Exception {
348 return timedReconnectStrategy.getConnectTimeout();
352 public Future<Void> scheduleReconnect(final Throwable cause) {
353 return timedReconnectStrategy.scheduleReconnect(cause);
357 public void reconnectSuccessful() {
358 timedReconnectStrategy.reconnectSuccessful();
362 final EventLoopGroup group = new NioEventLoopGroup();
363 final Timer time = new HashedWheelTimer();
365 final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(new RemoteDeviceId("test"), device);
366 final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create()
367 .withAddress(new InetSocketAddress("localhost", 65000))
368 .withReconnectStrategy(reconnectStrategy)
369 .withConnectStrategyFactory(new ReconnectStrategyFactory() {
371 public ReconnectStrategy createReconnectStrategy() {
372 return reconnectStrategy;
375 .withAuthHandler(new LoginPassword("admin", "admin"))
376 .withConnectionTimeoutMillis(10000)
377 .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
378 .withSessionListener(listener)
381 listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);
383 verify(reconnectStrategy, timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
386 group.shutdownGracefully();
391 public void testOnResponseMessageWithWrongMessageID() throws Exception {
394 String messageID = UUID.randomUUID().toString();
395 ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID );
397 communicator.onMessage( mockSession, createSuccessResponseMessage( UUID.randomUUID().toString() ) );
399 RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.PROTOCOL,
401 assertEquals( "RpcError message non-empty", true,
402 !Strings.isNullOrEmpty( rpcError.getMessage() ) );
404 String errorInfo = rpcError.getInfo();
405 assertNotNull( "RpcError info is null", errorInfo );
406 assertEquals( "Error info contains \"actual-message-id\"", true,
407 errorInfo.contains( "actual-message-id" ) );
408 assertEquals( "Error info contains \"expected-message-id\"", true,
409 errorInfo.contains( "expected-message-id" ) );
412 private NetconfMessage createErrorResponseMessage( String messageID ) throws Exception {
414 "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"" +
415 " message-id=\"" + messageID + "\">" +
417 " <error-type>rpc</error-type>" +
418 " <error-tag>missing-attribute</error-tag>" +
419 " <error-severity>error</error-severity>" +
420 " <error-message>Missing attribute</error-message>" +
422 " <bad-attribute>foo</bad-attribute>" +
423 " <bad-element>bar</bad-element>" +
428 ByteArrayInputStream bis = new ByteArrayInputStream( xmlStr.getBytes() );
429 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( bis );
430 return new NetconfMessage( doc );
433 private void verifyResponseMessage( RpcResult<NetconfMessage> rpcResult, String dataText ) {
434 assertNotNull( "RpcResult is null", rpcResult );
435 assertEquals( "isSuccessful", true, rpcResult.isSuccessful() );
436 NetconfMessage messageResult = rpcResult.getResult();
437 assertNotNull( "getResult", messageResult );
438 // List<SimpleNode<?>> nodes = messageResult.getSimpleNodesByName(
439 // QName.create( URI.create( "ns" ), null, "data" ) );
440 // assertNotNull( "getSimpleNodesByName", nodes );
441 // assertEquals( "List<SimpleNode<?>> size", 1, nodes.size() );
442 // assertEquals( "SimpleNode value", dataText, nodes.iterator().next().getValue() );
445 private RpcError verifyErrorRpcResult( RpcResult<NetconfMessage> rpcResult,
446 RpcError.ErrorType expErrorType, String expErrorTag ) {
447 assertNotNull( "RpcResult is null", rpcResult );
448 assertEquals( "isSuccessful", false, rpcResult.isSuccessful() );
449 assertNotNull( "RpcResult errors is null", rpcResult.getErrors() );
450 assertEquals( "Errors size", 1, rpcResult.getErrors().size() );
451 RpcError rpcError = rpcResult.getErrors().iterator().next();
452 assertEquals( "getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity() );
453 assertEquals( "getErrorType", expErrorType, rpcError.getErrorType() );
454 assertEquals( "getErrorTag", expErrorTag, rpcError.getTag() );
455 assertTrue( "getMessage is empty", StringUtils.isNotEmpty( rpcError.getMessage() ) );