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.SchemaContextFactory;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
65 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
67 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
68 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
69 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
71 public class NetconfDeviceTest {
73 private static final NetconfMessage notification;
75 private static final ContainerNode compositeNode;
79 compositeNode = mockClass(ContainerNode.class);
80 } catch (final Exception e) {
81 throw new RuntimeException(e);
84 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
85 } catch (Exception e) {
86 throw new ExceptionInInitializerError(e);
90 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
92 public static final String TEST_NAMESPACE = "test:namespace";
93 public static final String TEST_MODULE = "test-module";
94 public static final String TEST_REVISION = "2013-07-22";
95 public static final SourceIdentifier TEST_SID = new SourceIdentifier(TEST_MODULE, Optional.of(TEST_REVISION));
96 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
98 public static final SourceIdentifier TEST_SID2 = new SourceIdentifier(TEST_MODULE + "2", Optional.of(TEST_REVISION));
99 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
101 private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
104 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
105 return NetconfStateSchemas.EMPTY;
110 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
111 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
113 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
114 final NetconfDeviceCommunicator listener = getListener();
116 final SchemaContextFactory schemaFactory = getSchemaFactory();
118 // Make fallback attempt to fail due to empty resolved sources
119 final SchemaResolutionException schemaResolutionException
120 = new SchemaResolutionException("fail first",
121 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
122 doReturn(Futures.immediateFailedCheckedFuture(
123 schemaResolutionException))
124 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
126 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
127 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
128 final NetconfDevice device = new NetconfDeviceBuilder()
129 .setReconnectOnSchemasChange(true)
130 .setSchemaResourcesDTO(schemaResourcesDTO)
131 .setGlobalProcessingExecutor(getExecutor())
133 .setSalFacade(facade)
136 // Monitoring not supported
137 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
138 device.onRemoteSessionUp(sessionCaps, listener);
140 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
141 Mockito.verify(listener, Mockito.timeout(5000)).close();
142 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
146 public void testNetconfDeviceMissingSource() throws Exception {
147 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
148 final NetconfDeviceCommunicator listener = getListener();
149 final SchemaContext schema = getSchema();
151 final SchemaContextFactory schemaFactory = getSchemaFactory();
153 // Make fallback attempt to fail due to empty resolved sources
154 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
155 doAnswer(new Answer<Object>() {
157 public Object answer(final InvocationOnMock invocation) throws Throwable {
158 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
159 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
161 return Futures.immediateCheckedFuture(schema);
164 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
166 final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
168 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
169 final Module first = Iterables.getFirst(schema.getModules(), null);
170 final QName qName = QName.create(first.getQNameModule(), first.getName());
171 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
172 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
173 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
177 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
178 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
180 final NetconfDevice device = new NetconfDeviceBuilder()
181 .setReconnectOnSchemasChange(true)
182 .setSchemaResourcesDTO(schemaResourcesDTO)
183 .setGlobalProcessingExecutor(getExecutor())
185 .setSalFacade(facade)
187 // Monitoring supported
188 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
189 device.onRemoteSessionUp(sessionCaps, listener);
191 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
192 Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
195 private SchemaSourceRegistry getSchemaRegistry() {
196 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
197 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
198 doNothing().when(mockReg).close();
199 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
204 public void testNotificationBeforeSchema() throws Exception {
205 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
206 final NetconfDeviceCommunicator listener = getListener();
208 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
209 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaFactory(), stateSchemasResolver);
210 final NetconfDevice device = new NetconfDeviceBuilder()
211 .setReconnectOnSchemasChange(true)
212 .setSchemaResourcesDTO(schemaResourcesDTO)
213 .setGlobalProcessingExecutor(getExecutor())
215 .setSalFacade(facade)
218 device.onNotification(notification);
219 device.onNotification(notification);
221 verify(facade, times(0)).onNotification(any(DOMNotification.class));
223 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
224 Lists.newArrayList(TEST_CAPABILITY));
226 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
228 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
230 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
232 device.onNotification(notification);
233 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
237 public void testNetconfDeviceReconnect() throws Exception {
238 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
239 final NetconfDeviceCommunicator listener = getListener();
241 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
243 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
244 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaContextProviderFactory, stateSchemasResolver);
245 final NetconfDevice device = new NetconfDeviceBuilder()
246 .setReconnectOnSchemasChange(true)
247 .setSchemaResourcesDTO(schemaResourcesDTO)
248 .setGlobalProcessingExecutor(getExecutor())
250 .setSalFacade(facade)
252 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
253 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
254 device.onRemoteSessionUp(sessionCaps, listener);
256 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
257 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
259 device.onRemoteSessionDown();
260 verify(facade, timeout(5000)).onDeviceDisconnected();
262 device.onRemoteSessionUp(sessionCaps, listener);
264 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
265 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
268 private SchemaContextFactory getSchemaFactory() {
269 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
270 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
271 return schemaFactory;
274 private static SchemaContext parseYangStreams(final List<InputStream> streams) {
275 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
277 final SchemaContext schemaContext;
279 schemaContext = reactor.buildEffective(streams);
280 } catch (ReactorException e) {
281 throw new RuntimeException("Unable to build schema context from " + streams, e);
283 return schemaContext;
286 public static SchemaContext getSchema() {
287 final List<InputStream> modelsToParse = Lists.newArrayList(
288 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
290 return parseYangStreams(modelsToParse);
293 private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
294 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
295 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
296 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
297 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
298 return remoteDeviceHandler;
301 private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
302 final T mock = mockClass(remoteDeviceHandlerClass);
303 doNothing().when(mock).close();
307 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
308 final T mock = mock(remoteDeviceHandlerClass);
309 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
313 public RemoteDeviceId getId() {
314 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
317 public ExecutorService getExecutor() {
318 return Executors.newSingleThreadExecutor();
321 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
322 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
323 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
324 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
325 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
326 return messageTransformer;
329 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
330 final ArrayList<String> capabilities = Lists.newArrayList(
331 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
332 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
335 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
338 capabilities.addAll(additionalCapabilities);
340 return NetconfSessionPreferences.fromStrings(
344 public NetconfDeviceCommunicator getListener() throws Exception {
345 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
346 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
347 return remoteDeviceCommunicator;