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.mockito.invocation.InvocationOnMock;
43 import org.mockito.stubbing.Answer;
44 import org.opendaylight.controller.config.util.xml.XmlUtil;
45 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
47 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
48 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
49 import org.opendaylight.netconf.api.NetconfMessage;
50 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
51 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
52 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
53 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
54 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
55 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
56 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
57 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
58 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
59 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
60 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.model.api.Module;
66 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
70 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
71 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
72 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
73 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
75 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
76 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
77 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
78 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
79 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
80 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
81 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
82 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
84 public class NetconfDeviceTest {
86 private static final NetconfMessage notification;
88 private static final ContainerNode compositeNode;
92 compositeNode = mockClass(ContainerNode.class);
93 } catch (final Exception e) {
94 throw new RuntimeException(e);
97 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
98 } catch (Exception e) {
99 throw new ExceptionInInitializerError(e);
103 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
105 public static final String TEST_NAMESPACE = "test:namespace";
106 public static final String TEST_MODULE = "test-module";
107 public static final String TEST_REVISION = "2013-07-22";
108 public static final SourceIdentifier TEST_SID =
109 RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
110 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
112 public static final SourceIdentifier TEST_SID2 =
113 RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
114 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
116 private static final NetconfDeviceSchemasResolver stateSchemasResolver = new NetconfDeviceSchemasResolver() {
119 public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
120 return NetconfStateSchemas.EMPTY;
125 public void testNetconfDeviceFlawedModelFailedResolution() throws Exception {
126 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
127 final NetconfDeviceCommunicator listener = getListener();
129 final SchemaContextFactory schemaFactory = getSchemaFactory();
130 final SchemaContext schema = getSchema();
131 final SchemaRepository schemaRepository = getSchemaRepository();
133 final SchemaResolutionException schemaResolutionException =
134 new SchemaResolutionException("fail first", TEST_SID, new Throwable("YangTools parser fail"));
135 doAnswer(invocation -> {
136 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
137 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
139 return Futures.immediateCheckedFuture(schema);
141 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
143 final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> {
144 final Module first = Iterables.getFirst(schema.getModules(), null);
145 final QName qName = QName.create(first.getQNameModule(), first.getName());
146 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
147 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
148 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
151 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
152 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
154 final NetconfDevice device = new NetconfDeviceBuilder()
155 .setReconnectOnSchemasChange(true)
156 .setSchemaResourcesDTO(schemaResourcesDTO)
157 .setGlobalProcessingExecutor(getExecutor())
159 .setSalFacade(facade)
161 // Monitoring supported
162 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
163 device.onRemoteSessionUp(sessionCaps, listener);
165 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
166 Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
170 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
171 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
173 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
174 final NetconfDeviceCommunicator listener = getListener();
176 final SchemaContextFactory schemaFactory = getSchemaFactory();
177 final SchemaRepository schemaRepository = getSchemaRepository();
179 // Make fallback attempt to fail due to empty resolved sources
180 final SchemaResolutionException schemaResolutionException
181 = new SchemaResolutionException("fail first",
182 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
183 doReturn(Futures.immediateFailedCheckedFuture(
184 schemaResolutionException))
185 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
187 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
188 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
189 final NetconfDevice device = new NetconfDeviceBuilder()
190 .setReconnectOnSchemasChange(true)
191 .setSchemaResourcesDTO(schemaResourcesDTO)
192 .setGlobalProcessingExecutor(getExecutor())
194 .setSalFacade(facade)
197 // Monitoring not supported
198 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
199 device.onRemoteSessionUp(sessionCaps, listener);
201 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
202 Mockito.verify(listener, Mockito.timeout(5000)).close();
203 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
207 public void testNetconfDeviceMissingSource() throws Exception {
208 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
209 final NetconfDeviceCommunicator listener = getListener();
210 final SchemaContext schema = getSchema();
212 final SchemaContextFactory schemaFactory = getSchemaFactory();
213 final SchemaRepository schemaRepository = getSchemaRepository();
215 // Make fallback attempt to fail due to empty resolved sources
216 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
217 doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)).when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
218 doAnswer(new Answer<Object>() {
220 public Object answer(final InvocationOnMock invocation) throws Throwable {
221 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
222 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
224 return Futures.immediateCheckedFuture(schema);
227 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
229 final NetconfDeviceSchemasResolver stateSchemasResolver = new NetconfDeviceSchemasResolver() {
231 public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
232 final Module first = Iterables.getFirst(schema.getModules(), null);
233 final QName qName = QName.create(first.getQNameModule(), first.getName());
234 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
235 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
236 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
240 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
241 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
243 final NetconfDevice device = new NetconfDeviceBuilder()
244 .setReconnectOnSchemasChange(true)
245 .setSchemaResourcesDTO(schemaResourcesDTO)
246 .setGlobalProcessingExecutor(getExecutor())
248 .setSalFacade(facade)
250 // Monitoring supported
251 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
252 device.onRemoteSessionUp(sessionCaps, listener);
254 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
255 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
258 private SchemaSourceRegistry getSchemaRegistry() {
259 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
260 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
261 doNothing().when(mockReg).close();
262 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
266 private SchemaRepository getSchemaRepository() {
267 final SchemaRepository mock = mock(SchemaRepository.class);
268 final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
269 doReturn(Futures.immediateCheckedFuture(mockRep)).when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
274 public void testNotificationBeforeSchema() throws Exception {
275 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
276 final NetconfDeviceCommunicator listener = getListener();
278 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
279 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), stateSchemasResolver);
280 final NetconfDevice device = new NetconfDeviceBuilder()
281 .setReconnectOnSchemasChange(true)
282 .setSchemaResourcesDTO(schemaResourcesDTO)
283 .setGlobalProcessingExecutor(getExecutor())
285 .setSalFacade(facade)
288 device.onNotification(notification);
289 device.onNotification(notification);
291 verify(facade, times(0)).onNotification(any(DOMNotification.class));
293 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
294 Lists.newArrayList(TEST_CAPABILITY));
296 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
298 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
300 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
302 device.onNotification(notification);
303 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
307 public void testNetconfDeviceReconnect() throws Exception {
308 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
309 final NetconfDeviceCommunicator listener = getListener();
311 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
313 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
314 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
315 final NetconfDevice device = new NetconfDeviceBuilder()
316 .setReconnectOnSchemasChange(true)
317 .setSchemaResourcesDTO(schemaResourcesDTO)
318 .setGlobalProcessingExecutor(getExecutor())
320 .setSalFacade(facade)
322 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
323 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
324 device.onRemoteSessionUp(sessionCaps, listener);
326 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
327 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
329 device.onRemoteSessionDown();
330 verify(facade, timeout(5000)).onDeviceDisconnected();
332 device.onRemoteSessionUp(sessionCaps, listener);
334 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
335 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
339 public void testNetconfDeviceAvailableCapabilitiesBuilding() throws Exception {
340 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
341 final NetconfDeviceCommunicator listener = getListener();
343 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
345 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
346 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
347 final NetconfDevice device = new NetconfDeviceBuilder()
348 .setReconnectOnSchemasChange(true)
349 .setSchemaResourcesDTO(schemaResourcesDTO)
350 .setGlobalProcessingExecutor(getExecutor())
352 .setSalFacade(facade)
354 NetconfDevice netconfSpy = Mockito.spy(device);
356 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
357 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
358 Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
359 moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
360 moduleBasedCaps.put(QName.create("test:qname:side:loading"), AvailableCapability.CapabilityOrigin.UserDefined);
362 netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
364 ArgumentCaptor argument = ArgumentCaptor.forClass(NetconfSessionPreferences.class);
365 verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
366 NetconfDeviceCapabilities netconfDeviceCaps = ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
368 netconfDeviceCaps.getResolvedCapabilities().forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
369 moduleBasedCaps.get(QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
372 private SchemaContextFactory getSchemaFactory() {
373 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
374 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
375 return schemaFactory;
378 private static SchemaContext parseYangStreams(final List<InputStream> streams) {
379 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
381 final SchemaContext schemaContext;
383 schemaContext = reactor.buildEffective(streams);
384 } catch (ReactorException e) {
385 throw new RuntimeException("Unable to build schema context from " + streams, e);
387 return schemaContext;
390 public static SchemaContext getSchema() {
391 final List<InputStream> modelsToParse = Lists.newArrayList(
392 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
394 return parseYangStreams(modelsToParse);
397 private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
398 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
399 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
400 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
401 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
402 return remoteDeviceHandler;
405 private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
406 final T mock = mockClass(remoteDeviceHandlerClass);
407 doNothing().when(mock).close();
411 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
412 final T mock = mock(remoteDeviceHandlerClass);
413 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
417 public RemoteDeviceId getId() {
418 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
421 public ExecutorService getExecutor() {
422 return Executors.newSingleThreadExecutor();
425 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
426 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
427 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
428 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
429 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
430 return messageTransformer;
433 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
434 final ArrayList<String> capabilities = Lists.newArrayList(
435 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
436 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
439 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
442 capabilities.addAll(additionalCapabilities);
444 return NetconfSessionPreferences.fromStrings(
448 public NetconfDeviceCommunicator getListener() throws Exception {
449 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
450 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
451 return remoteDeviceCommunicator;