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.junit.Assert.assertEquals;
12 import static org.mockito.Matchers.any;
13 import static org.mockito.Matchers.anyCollectionOf;
14 import static org.mockito.Matchers.eq;
15 import static org.mockito.Mockito.doAnswer;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.timeout;
20 import static org.mockito.Mockito.times;
21 import static org.mockito.Mockito.verify;
23 import com.google.common.base.Optional;
24 import com.google.common.collect.HashMultimap;
25 import com.google.common.collect.Iterables;
26 import com.google.common.collect.Lists;
27 import com.google.common.collect.Sets;
28 import com.google.common.util.concurrent.Futures;
29 import java.io.InputStream;
30 import java.net.InetSocketAddress;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.List;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import org.junit.Test;
40 import org.mockito.ArgumentCaptor;
41 import org.mockito.Mockito;
42 import org.opendaylight.controller.config.util.xml.XmlUtil;
43 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
44 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
46 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
47 import org.opendaylight.netconf.api.NetconfMessage;
48 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
49 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
50 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
51 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
52 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
53 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
54 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
55 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
56 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
57 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
59 import org.opendaylight.yangtools.yang.common.QName;
60 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.model.api.Module;
63 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
66 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
67 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
68 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
69 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
70 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
71 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
72 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
75 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
76 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
77 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
79 public class NetconfDeviceTest {
81 private static final NetconfMessage notification;
83 private static final ContainerNode compositeNode;
87 compositeNode = mockClass(ContainerNode.class);
88 } catch (final Exception e) {
89 throw new RuntimeException(e);
92 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
93 } catch (Exception e) {
94 throw new ExceptionInInitializerError(e);
98 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
100 public static final String TEST_NAMESPACE = "test:namespace";
101 public static final String TEST_MODULE = "test-module";
102 public static final String TEST_REVISION = "2013-07-22";
103 public static final SourceIdentifier TEST_SID =
104 RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
105 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
107 public static final SourceIdentifier TEST_SID2 =
108 RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
109 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
111 private static final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> NetconfStateSchemas.EMPTY;
114 public void testNetconfDeviceFlawedModelFailedResolution() throws Exception {
115 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
116 final NetconfDeviceCommunicator listener = getListener();
118 final SchemaContextFactory schemaFactory = getSchemaFactory();
119 final SchemaContext schema = getSchema();
120 final SchemaRepository schemaRepository = getSchemaRepository();
122 final SchemaResolutionException schemaResolutionException =
123 new SchemaResolutionException("fail first", TEST_SID, new Throwable("YangTools parser fail"));
124 doAnswer(invocation -> {
125 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
126 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
128 return Futures.immediateCheckedFuture(schema);
130 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
132 final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> {
133 final Module first = Iterables.getFirst(schema.getModules(), null);
134 final QName qName = QName.create(first.getQNameModule(), first.getName());
135 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
136 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
137 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
140 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
141 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
143 final NetconfDevice device = new NetconfDeviceBuilder()
144 .setReconnectOnSchemasChange(true)
145 .setSchemaResourcesDTO(schemaResourcesDTO)
146 .setGlobalProcessingExecutor(getExecutor())
148 .setSalFacade(facade)
150 // Monitoring supported
151 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
152 device.onRemoteSessionUp(sessionCaps, listener);
154 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
155 Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
159 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
160 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
162 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
163 final NetconfDeviceCommunicator listener = getListener();
165 final SchemaContextFactory schemaFactory = getSchemaFactory();
166 final SchemaRepository schemaRepository = getSchemaRepository();
168 // Make fallback attempt to fail due to empty resolved sources
169 final SchemaResolutionException schemaResolutionException
170 = new SchemaResolutionException("fail first",
171 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
172 doReturn(Futures.immediateFailedCheckedFuture(
173 schemaResolutionException))
174 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
176 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
177 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
178 final NetconfDevice device = new NetconfDeviceBuilder()
179 .setReconnectOnSchemasChange(true)
180 .setSchemaResourcesDTO(schemaResourcesDTO)
181 .setGlobalProcessingExecutor(getExecutor())
183 .setSalFacade(facade)
186 // Monitoring not supported
187 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
188 device.onRemoteSessionUp(sessionCaps, listener);
190 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
191 Mockito.verify(listener, Mockito.timeout(5000)).close();
192 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
196 public void testNetconfDeviceMissingSource() throws Exception {
197 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
198 final NetconfDeviceCommunicator listener = getListener();
199 final SchemaContext schema = getSchema();
201 final SchemaContextFactory schemaFactory = getSchemaFactory();
202 final SchemaRepository schemaRepository = getSchemaRepository();
204 // Make fallback attempt to fail due to empty resolved sources
205 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
206 doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)).when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
207 doAnswer(invocation -> {
208 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
209 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
211 return Futures.immediateCheckedFuture(schema);
213 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
215 final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> {
216 final Module first = Iterables.getFirst(schema.getModules(), null);
217 final QName qName = QName.create(first.getQNameModule(), first.getName());
218 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
219 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
220 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
223 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
224 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
226 final NetconfDevice device = new NetconfDeviceBuilder()
227 .setReconnectOnSchemasChange(true)
228 .setSchemaResourcesDTO(schemaResourcesDTO)
229 .setGlobalProcessingExecutor(getExecutor())
231 .setSalFacade(facade)
233 // Monitoring supported
234 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
235 device.onRemoteSessionUp(sessionCaps, listener);
237 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
238 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
241 private static SchemaSourceRegistry getSchemaRegistry() {
242 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
243 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
244 doNothing().when(mockReg).close();
245 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
249 private static SchemaRepository getSchemaRepository() {
250 final SchemaRepository mock = mock(SchemaRepository.class);
251 final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
252 doReturn(Futures.immediateCheckedFuture(mockRep)).when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
257 public void testNotificationBeforeSchema() throws Exception {
258 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
259 final NetconfDeviceCommunicator listener = getListener();
261 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
262 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), stateSchemasResolver);
263 final NetconfDevice device = new NetconfDeviceBuilder()
264 .setReconnectOnSchemasChange(true)
265 .setSchemaResourcesDTO(schemaResourcesDTO)
266 .setGlobalProcessingExecutor(getExecutor())
268 .setSalFacade(facade)
271 device.onNotification(notification);
272 device.onNotification(notification);
274 verify(facade, times(0)).onNotification(any(DOMNotification.class));
276 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
277 Lists.newArrayList(TEST_CAPABILITY));
279 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
281 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
283 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
285 device.onNotification(notification);
286 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
290 public void testNetconfDeviceReconnect() throws Exception {
291 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
292 final NetconfDeviceCommunicator listener = getListener();
294 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
296 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
297 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
298 final NetconfDevice device = new NetconfDeviceBuilder()
299 .setReconnectOnSchemasChange(true)
300 .setSchemaResourcesDTO(schemaResourcesDTO)
301 .setGlobalProcessingExecutor(getExecutor())
303 .setSalFacade(facade)
305 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
306 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
307 device.onRemoteSessionUp(sessionCaps, listener);
309 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
310 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
312 device.onRemoteSessionDown();
313 verify(facade, timeout(5000)).onDeviceDisconnected();
315 device.onRemoteSessionUp(sessionCaps, listener);
317 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
318 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
322 public void testNetconfDeviceAvailableCapabilitiesBuilding() throws Exception {
323 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
324 final NetconfDeviceCommunicator listener = getListener();
326 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
328 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
329 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
330 final NetconfDevice device = new NetconfDeviceBuilder()
331 .setReconnectOnSchemasChange(true)
332 .setSchemaResourcesDTO(schemaResourcesDTO)
333 .setGlobalProcessingExecutor(getExecutor())
335 .setSalFacade(facade)
337 NetconfDevice netconfSpy = Mockito.spy(device);
339 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
340 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
341 Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
342 moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
343 moduleBasedCaps.put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
345 netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
347 ArgumentCaptor argument = ArgumentCaptor.forClass(NetconfSessionPreferences.class);
348 verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
349 NetconfDeviceCapabilities netconfDeviceCaps = ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
351 netconfDeviceCaps.getResolvedCapabilities().forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
352 moduleBasedCaps.get(QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
355 private static SchemaContextFactory getSchemaFactory() throws Exception {
356 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
357 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
358 return schemaFactory;
361 public static SchemaContext getSchema() throws Exception {
362 final List<InputStream> modelsToParse = Lists.newArrayList(
363 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
365 return YangParserTestUtils.parseYangStreams(modelsToParse);
368 private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
369 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
370 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
371 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
372 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
373 return remoteDeviceHandler;
376 private static <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass)
378 final T mock = mockClass(remoteDeviceHandlerClass);
379 doNothing().when(mock).close();
383 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
384 final T mock = mock(remoteDeviceHandlerClass);
385 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
389 public RemoteDeviceId getId() {
390 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
393 public ExecutorService getExecutor() {
394 return Executors.newSingleThreadExecutor();
397 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
398 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
399 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
400 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
401 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
402 return messageTransformer;
405 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
406 final ArrayList<String> capabilities = Lists.newArrayList(
407 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
408 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
411 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
414 capabilities.addAll(additionalCapabilities);
416 return NetconfSessionPreferences.fromStrings(
420 public NetconfDeviceCommunicator getListener() throws Exception {
421 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
422 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
423 return remoteDeviceCommunicator;