2 * Copyright (c) 2014, 2015 Cisco 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;
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Matchers.anyCollectionOf;
13 import static org.mockito.Mockito.doAnswer;
14 import static org.mockito.Mockito.doNothing;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.timeout;
18 import static org.mockito.Mockito.times;
19 import static org.mockito.Mockito.verify;
21 import com.google.common.base.Optional;
22 import com.google.common.collect.HashMultimap;
23 import com.google.common.collect.Iterables;
24 import com.google.common.collect.Lists;
25 import com.google.common.collect.Sets;
26 import com.google.common.util.concurrent.Futures;
27 import java.io.InputStream;
28 import java.net.InetSocketAddress;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import org.junit.Test;
36 import org.mockito.Mockito;
37 import org.mockito.invocation.InvocationOnMock;
38 import org.mockito.stubbing.Answer;
39 import org.opendaylight.controller.config.util.xml.XmlUtil;
40 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
43 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
44 import org.opendaylight.netconf.api.NetconfMessage;
45 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
46 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
47 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
51 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
52 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.model.api.Module;
57 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
60 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
61 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
67 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
69 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
70 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
72 public class NetconfDeviceTest {
74 private static final NetconfMessage notification;
76 private static final ContainerNode compositeNode;
80 compositeNode = mockClass(ContainerNode.class);
81 } catch (final Exception e) {
82 throw new RuntimeException(e);
85 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
86 } catch (Exception e) {
87 throw new ExceptionInInitializerError(e);
91 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
93 public static final String TEST_NAMESPACE = "test:namespace";
94 public static final String TEST_MODULE = "test-module";
95 public static final String TEST_REVISION = "2013-07-22";
96 public static final SourceIdentifier TEST_SID =
97 RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
98 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
100 public static final SourceIdentifier TEST_SID2 =
101 RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
102 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
104 private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
107 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
108 return NetconfStateSchemas.EMPTY;
113 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
114 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
116 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
117 final NetconfDeviceCommunicator listener = getListener();
119 final SchemaContextFactory schemaFactory = getSchemaFactory();
121 // Make fallback attempt to fail due to empty resolved sources
122 final SchemaResolutionException schemaResolutionException
123 = new SchemaResolutionException("fail first",
124 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
125 doReturn(Futures.immediateFailedCheckedFuture(
126 schemaResolutionException))
127 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
129 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
130 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
131 final NetconfDevice device = new NetconfDeviceBuilder()
132 .setReconnectOnSchemasChange(true)
133 .setSchemaResourcesDTO(schemaResourcesDTO)
134 .setGlobalProcessingExecutor(getExecutor())
136 .setSalFacade(facade)
139 // Monitoring not supported
140 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
141 device.onRemoteSessionUp(sessionCaps, listener);
143 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
144 Mockito.verify(listener, Mockito.timeout(5000)).close();
145 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
149 public void testNetconfDeviceMissingSource() throws Exception {
150 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
151 final NetconfDeviceCommunicator listener = getListener();
152 final SchemaContext schema = getSchema();
154 final SchemaContextFactory schemaFactory = getSchemaFactory();
156 // Make fallback attempt to fail due to empty resolved sources
157 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
158 doAnswer(new Answer<Object>() {
160 public Object answer(final InvocationOnMock invocation) throws Throwable {
161 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
162 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
164 return Futures.immediateCheckedFuture(schema);
167 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
169 final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
171 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
172 final Module first = Iterables.getFirst(schema.getModules(), null);
173 final QName qName = QName.create(first.getQNameModule(), first.getName());
174 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
175 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
176 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
180 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
181 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
183 final NetconfDevice device = new NetconfDeviceBuilder()
184 .setReconnectOnSchemasChange(true)
185 .setSchemaResourcesDTO(schemaResourcesDTO)
186 .setGlobalProcessingExecutor(getExecutor())
188 .setSalFacade(facade)
190 // Monitoring supported
191 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
192 device.onRemoteSessionUp(sessionCaps, listener);
194 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
195 Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
198 private SchemaSourceRegistry getSchemaRegistry() {
199 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
200 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
201 doNothing().when(mockReg).close();
202 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
207 public void testNotificationBeforeSchema() throws Exception {
208 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
209 final NetconfDeviceCommunicator listener = getListener();
211 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
212 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaFactory(), stateSchemasResolver);
213 final NetconfDevice device = new NetconfDeviceBuilder()
214 .setReconnectOnSchemasChange(true)
215 .setSchemaResourcesDTO(schemaResourcesDTO)
216 .setGlobalProcessingExecutor(getExecutor())
218 .setSalFacade(facade)
221 device.onNotification(notification);
222 device.onNotification(notification);
224 verify(facade, times(0)).onNotification(any(DOMNotification.class));
226 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
227 Lists.newArrayList(TEST_CAPABILITY));
229 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
231 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
233 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
235 device.onNotification(notification);
236 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
240 public void testNetconfDeviceReconnect() throws Exception {
241 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
242 final NetconfDeviceCommunicator listener = getListener();
244 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
246 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
247 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaContextProviderFactory, stateSchemasResolver);
248 final NetconfDevice device = new NetconfDeviceBuilder()
249 .setReconnectOnSchemasChange(true)
250 .setSchemaResourcesDTO(schemaResourcesDTO)
251 .setGlobalProcessingExecutor(getExecutor())
253 .setSalFacade(facade)
255 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
256 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
257 device.onRemoteSessionUp(sessionCaps, listener);
259 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
260 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
262 device.onRemoteSessionDown();
263 verify(facade, timeout(5000)).onDeviceDisconnected();
265 device.onRemoteSessionUp(sessionCaps, listener);
267 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
268 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
271 private SchemaContextFactory getSchemaFactory() {
272 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
273 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
274 return schemaFactory;
277 private static SchemaContext parseYangStreams(final List<InputStream> streams) {
278 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
280 final SchemaContext schemaContext;
282 schemaContext = reactor.buildEffective(streams);
283 } catch (ReactorException e) {
284 throw new RuntimeException("Unable to build schema context from " + streams, e);
286 return schemaContext;
289 public static SchemaContext getSchema() {
290 final List<InputStream> modelsToParse = Lists.newArrayList(
291 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
293 return parseYangStreams(modelsToParse);
296 private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
297 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
298 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
299 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
300 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
301 return remoteDeviceHandler;
304 private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
305 final T mock = mockClass(remoteDeviceHandlerClass);
306 doNothing().when(mock).close();
310 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
311 final T mock = mock(remoteDeviceHandlerClass);
312 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
316 public RemoteDeviceId getId() {
317 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
320 public ExecutorService getExecutor() {
321 return Executors.newSingleThreadExecutor();
324 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
325 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
326 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
327 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
328 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
329 return messageTransformer;
332 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
333 final ArrayList<String> capabilities = Lists.newArrayList(
334 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
335 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
338 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
341 capabilities.addAll(additionalCapabilities);
343 return NetconfSessionPreferences.fromStrings(
347 public NetconfDeviceCommunicator getListener() throws Exception {
348 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
349 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
350 return remoteDeviceCommunicator;