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.util.ASTSchemaSource;
80 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
82 public class NetconfDeviceTest {
84 private static final NetconfMessage notification;
86 private static final ContainerNode compositeNode;
90 compositeNode = mockClass(ContainerNode.class);
91 } catch (final Exception e) {
92 throw new RuntimeException(e);
95 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
96 } catch (Exception e) {
97 throw new ExceptionInInitializerError(e);
101 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
103 public static final String TEST_NAMESPACE = "test:namespace";
104 public static final String TEST_MODULE = "test-module";
105 public static final String TEST_REVISION = "2013-07-22";
106 public static final SourceIdentifier TEST_SID =
107 RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
108 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
110 public static final SourceIdentifier TEST_SID2 =
111 RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
112 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
114 private static final NetconfDeviceSchemasResolver stateSchemasResolver = new NetconfDeviceSchemasResolver() {
117 public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
118 return NetconfStateSchemas.EMPTY;
123 public void testNetconfDeviceFlawedModelFailedResolution() throws Exception {
124 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
125 final NetconfDeviceCommunicator listener = getListener();
127 final SchemaContextFactory schemaFactory = getSchemaFactory();
128 final SchemaContext schema = getSchema();
129 final SchemaRepository schemaRepository = getSchemaRepository();
131 final SchemaResolutionException schemaResolutionException =
132 new SchemaResolutionException("fail first", TEST_SID, new Throwable("YangTools parser fail"));
133 doAnswer(invocation -> {
134 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
135 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
137 return Futures.immediateCheckedFuture(schema);
139 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
141 final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> {
142 final Module first = Iterables.getFirst(schema.getModules(), null);
143 final QName qName = QName.create(first.getQNameModule(), first.getName());
144 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
145 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
146 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
149 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
150 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
152 final NetconfDevice device = new NetconfDeviceBuilder()
153 .setReconnectOnSchemasChange(true)
154 .setSchemaResourcesDTO(schemaResourcesDTO)
155 .setGlobalProcessingExecutor(getExecutor())
157 .setSalFacade(facade)
159 // Monitoring supported
160 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
161 device.onRemoteSessionUp(sessionCaps, listener);
163 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
164 Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
168 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
169 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
171 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
172 final NetconfDeviceCommunicator listener = getListener();
174 final SchemaContextFactory schemaFactory = getSchemaFactory();
175 final SchemaRepository schemaRepository = getSchemaRepository();
177 // Make fallback attempt to fail due to empty resolved sources
178 final SchemaResolutionException schemaResolutionException
179 = new SchemaResolutionException("fail first",
180 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
181 doReturn(Futures.immediateFailedCheckedFuture(
182 schemaResolutionException))
183 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
185 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
186 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
187 final NetconfDevice device = new NetconfDeviceBuilder()
188 .setReconnectOnSchemasChange(true)
189 .setSchemaResourcesDTO(schemaResourcesDTO)
190 .setGlobalProcessingExecutor(getExecutor())
192 .setSalFacade(facade)
195 // Monitoring not supported
196 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
197 device.onRemoteSessionUp(sessionCaps, listener);
199 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
200 Mockito.verify(listener, Mockito.timeout(5000)).close();
201 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
205 public void testNetconfDeviceMissingSource() throws Exception {
206 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
207 final NetconfDeviceCommunicator listener = getListener();
208 final SchemaContext schema = getSchema();
210 final SchemaContextFactory schemaFactory = getSchemaFactory();
211 final SchemaRepository schemaRepository = getSchemaRepository();
213 // Make fallback attempt to fail due to empty resolved sources
214 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
215 doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)).when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
216 doAnswer(new Answer<Object>() {
218 public Object answer(final InvocationOnMock invocation) throws Throwable {
219 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
220 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
222 return Futures.immediateCheckedFuture(schema);
225 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
227 final NetconfDeviceSchemasResolver stateSchemasResolver = new NetconfDeviceSchemasResolver() {
229 public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
230 final Module first = Iterables.getFirst(schema.getModules(), null);
231 final QName qName = QName.create(first.getQNameModule(), first.getName());
232 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
233 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
234 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
238 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
239 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
241 final NetconfDevice device = new NetconfDeviceBuilder()
242 .setReconnectOnSchemasChange(true)
243 .setSchemaResourcesDTO(schemaResourcesDTO)
244 .setGlobalProcessingExecutor(getExecutor())
246 .setSalFacade(facade)
248 // Monitoring supported
249 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
250 device.onRemoteSessionUp(sessionCaps, listener);
252 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
253 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
256 private SchemaSourceRegistry getSchemaRegistry() {
257 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
258 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
259 doNothing().when(mockReg).close();
260 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
264 private SchemaRepository getSchemaRepository() {
265 final SchemaRepository mock = mock(SchemaRepository.class);
266 final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
267 doReturn(Futures.immediateCheckedFuture(mockRep)).when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
272 public void testNotificationBeforeSchema() throws Exception {
273 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
274 final NetconfDeviceCommunicator listener = getListener();
276 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
277 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), stateSchemasResolver);
278 final NetconfDevice device = new NetconfDeviceBuilder()
279 .setReconnectOnSchemasChange(true)
280 .setSchemaResourcesDTO(schemaResourcesDTO)
281 .setGlobalProcessingExecutor(getExecutor())
283 .setSalFacade(facade)
286 device.onNotification(notification);
287 device.onNotification(notification);
289 verify(facade, times(0)).onNotification(any(DOMNotification.class));
291 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
292 Lists.newArrayList(TEST_CAPABILITY));
294 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
296 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
298 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
300 device.onNotification(notification);
301 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
305 public void testNetconfDeviceReconnect() throws Exception {
306 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
307 final NetconfDeviceCommunicator listener = getListener();
309 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
311 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
312 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
313 final NetconfDevice device = new NetconfDeviceBuilder()
314 .setReconnectOnSchemasChange(true)
315 .setSchemaResourcesDTO(schemaResourcesDTO)
316 .setGlobalProcessingExecutor(getExecutor())
318 .setSalFacade(facade)
320 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
321 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
322 device.onRemoteSessionUp(sessionCaps, listener);
324 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
325 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
327 device.onRemoteSessionDown();
328 verify(facade, timeout(5000)).onDeviceDisconnected();
330 device.onRemoteSessionUp(sessionCaps, listener);
332 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
333 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
337 public void testNetconfDeviceAvailableCapabilitiesBuilding() throws Exception {
338 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
339 final NetconfDeviceCommunicator listener = getListener();
341 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
343 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
344 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
345 final NetconfDevice device = new NetconfDeviceBuilder()
346 .setReconnectOnSchemasChange(true)
347 .setSchemaResourcesDTO(schemaResourcesDTO)
348 .setGlobalProcessingExecutor(getExecutor())
350 .setSalFacade(facade)
352 NetconfDevice netconfSpy = Mockito.spy(device);
354 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
355 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
356 Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
357 moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
358 moduleBasedCaps.put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
360 netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
362 ArgumentCaptor argument = ArgumentCaptor.forClass(NetconfSessionPreferences.class);
363 verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
364 NetconfDeviceCapabilities netconfDeviceCaps = ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
366 netconfDeviceCaps.getResolvedCapabilities().forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
367 moduleBasedCaps.get(QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
370 private SchemaContextFactory getSchemaFactory() throws Exception {
371 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
372 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
373 return schemaFactory;
376 public static SchemaContext getSchema() throws Exception {
377 final List<InputStream> modelsToParse = Lists.newArrayList(
378 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
380 return YangParserTestUtils.parseYangStreams(modelsToParse);
383 private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
384 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
385 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
386 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
387 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
388 return remoteDeviceHandler;
391 private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
392 final T mock = mockClass(remoteDeviceHandlerClass);
393 doNothing().when(mock).close();
397 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
398 final T mock = mock(remoteDeviceHandlerClass);
399 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
403 public RemoteDeviceId getId() {
404 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
407 public ExecutorService getExecutor() {
408 return Executors.newSingleThreadExecutor();
411 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
412 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
413 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
414 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
415 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
416 return messageTransformer;
419 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
420 final ArrayList<String> capabilities = Lists.newArrayList(
421 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
422 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
425 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
428 capabilities.addAll(additionalCapabilities);
430 return NetconfSessionPreferences.fromStrings(
434 public NetconfDeviceCommunicator getListener() throws Exception {
435 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
436 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
437 return remoteDeviceCommunicator;