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.Matchers.eq;
14 import static org.mockito.Mockito.doAnswer;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.timeout;
19 import static org.mockito.Mockito.times;
20 import static org.mockito.Mockito.verify;
22 import com.google.common.base.Optional;
23 import com.google.common.collect.HashMultimap;
24 import com.google.common.collect.Iterables;
25 import com.google.common.collect.Lists;
26 import com.google.common.collect.Sets;
27 import com.google.common.util.concurrent.Futures;
28 import java.io.InputStream;
29 import java.net.InetSocketAddress;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import org.junit.Test;
37 import org.mockito.Mockito;
38 import org.mockito.invocation.InvocationOnMock;
39 import org.mockito.stubbing.Answer;
40 import org.opendaylight.controller.config.util.xml.XmlUtil;
41 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
44 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
45 import org.opendaylight.netconf.api.NetconfMessage;
46 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
47 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
48 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
49 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
50 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
51 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
52 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
53 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
54 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
55 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.model.api.Module;
60 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
64 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
68 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
69 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
70 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
73 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
74 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
75 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
76 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
78 public class NetconfDeviceTest {
80 private static final NetconfMessage notification;
82 private static final ContainerNode compositeNode;
86 compositeNode = mockClass(ContainerNode.class);
87 } catch (final Exception e) {
88 throw new RuntimeException(e);
91 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
92 } catch (Exception e) {
93 throw new ExceptionInInitializerError(e);
97 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
99 public static final String TEST_NAMESPACE = "test:namespace";
100 public static final String TEST_MODULE = "test-module";
101 public static final String TEST_REVISION = "2013-07-22";
102 public static final SourceIdentifier TEST_SID =
103 RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
104 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
106 public static final SourceIdentifier TEST_SID2 =
107 RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
108 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
110 private static final NetconfDeviceSchemasResolver stateSchemasResolver = new NetconfDeviceSchemasResolver() {
113 public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
114 return NetconfStateSchemas.EMPTY;
119 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
120 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
122 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
123 final NetconfDeviceCommunicator listener = getListener();
125 final SchemaContextFactory schemaFactory = getSchemaFactory();
126 final SchemaRepository schemaRepository = getSchemaRepository();
128 // Make fallback attempt to fail due to empty resolved sources
129 final SchemaResolutionException schemaResolutionException
130 = new SchemaResolutionException("fail first",
131 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
132 doReturn(Futures.immediateFailedCheckedFuture(
133 schemaResolutionException))
134 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
136 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
137 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
138 final NetconfDevice device = new NetconfDeviceBuilder()
139 .setReconnectOnSchemasChange(true)
140 .setSchemaResourcesDTO(schemaResourcesDTO)
141 .setGlobalProcessingExecutor(getExecutor())
143 .setSalFacade(facade)
146 // Monitoring not supported
147 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
148 device.onRemoteSessionUp(sessionCaps, listener);
150 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
151 Mockito.verify(listener, Mockito.timeout(5000)).close();
152 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
156 public void testNetconfDeviceMissingSource() throws Exception {
157 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
158 final NetconfDeviceCommunicator listener = getListener();
159 final SchemaContext schema = getSchema();
161 final SchemaContextFactory schemaFactory = getSchemaFactory();
162 final SchemaRepository schemaRepository = getSchemaRepository();
164 // Make fallback attempt to fail due to empty resolved sources
165 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
166 doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)).when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
167 doAnswer(new Answer<Object>() {
169 public Object answer(final InvocationOnMock invocation) throws Throwable {
170 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
171 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
173 return Futures.immediateCheckedFuture(schema);
176 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
178 final NetconfDeviceSchemasResolver stateSchemasResolver = new NetconfDeviceSchemasResolver() {
180 public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
181 final Module first = Iterables.getFirst(schema.getModules(), null);
182 final QName qName = QName.create(first.getQNameModule(), first.getName());
183 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
184 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
185 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
189 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
190 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
192 final NetconfDevice device = new NetconfDeviceBuilder()
193 .setReconnectOnSchemasChange(true)
194 .setSchemaResourcesDTO(schemaResourcesDTO)
195 .setGlobalProcessingExecutor(getExecutor())
197 .setSalFacade(facade)
199 // Monitoring supported
200 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
201 device.onRemoteSessionUp(sessionCaps, listener);
203 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
204 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
207 private SchemaSourceRegistry getSchemaRegistry() {
208 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
209 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
210 doNothing().when(mockReg).close();
211 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
215 private SchemaRepository getSchemaRepository() {
216 final SchemaRepository mock = mock(SchemaRepository.class);
217 final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
218 doReturn(Futures.immediateCheckedFuture(mockRep)).when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
223 public void testNotificationBeforeSchema() throws Exception {
224 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
225 final NetconfDeviceCommunicator listener = getListener();
227 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
228 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), stateSchemasResolver);
229 final NetconfDevice device = new NetconfDeviceBuilder()
230 .setReconnectOnSchemasChange(true)
231 .setSchemaResourcesDTO(schemaResourcesDTO)
232 .setGlobalProcessingExecutor(getExecutor())
234 .setSalFacade(facade)
237 device.onNotification(notification);
238 device.onNotification(notification);
240 verify(facade, times(0)).onNotification(any(DOMNotification.class));
242 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
243 Lists.newArrayList(TEST_CAPABILITY));
245 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
247 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
249 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
251 device.onNotification(notification);
252 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
256 public void testNetconfDeviceReconnect() throws Exception {
257 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
258 final NetconfDeviceCommunicator listener = getListener();
260 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
262 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
263 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
264 final NetconfDevice device = new NetconfDeviceBuilder()
265 .setReconnectOnSchemasChange(true)
266 .setSchemaResourcesDTO(schemaResourcesDTO)
267 .setGlobalProcessingExecutor(getExecutor())
269 .setSalFacade(facade)
271 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
272 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
273 device.onRemoteSessionUp(sessionCaps, listener);
275 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
276 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
278 device.onRemoteSessionDown();
279 verify(facade, timeout(5000)).onDeviceDisconnected();
281 device.onRemoteSessionUp(sessionCaps, listener);
283 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
284 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
287 private SchemaContextFactory getSchemaFactory() {
288 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
289 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
290 return schemaFactory;
293 private static SchemaContext parseYangStreams(final List<InputStream> streams) {
294 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
296 final SchemaContext schemaContext;
298 schemaContext = reactor.buildEffective(streams);
299 } catch (ReactorException e) {
300 throw new RuntimeException("Unable to build schema context from " + streams, e);
302 return schemaContext;
305 public static SchemaContext getSchema() {
306 final List<InputStream> modelsToParse = Lists.newArrayList(
307 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
309 return parseYangStreams(modelsToParse);
312 private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
313 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
314 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
315 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
316 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
317 return remoteDeviceHandler;
320 private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
321 final T mock = mockClass(remoteDeviceHandlerClass);
322 doNothing().when(mock).close();
326 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
327 final T mock = mock(remoteDeviceHandlerClass);
328 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
332 public RemoteDeviceId getId() {
333 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
336 public ExecutorService getExecutor() {
337 return Executors.newSingleThreadExecutor();
340 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
341 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
342 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
343 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
344 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
345 return messageTransformer;
348 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
349 final ArrayList<String> capabilities = Lists.newArrayList(
350 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
351 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
354 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
357 capabilities.addAll(additionalCapabilities);
359 return NetconfSessionPreferences.fromStrings(
363 public NetconfDeviceCommunicator getListener() throws Exception {
364 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
365 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
366 return remoteDeviceCommunicator;