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;
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.RemoteDeviceHandler;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
50 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
51 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
52 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
53 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.model.api.Module;
58 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
61 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
67 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
68 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
70 public class NetconfDeviceTest {
72 private static final NetconfMessage notification;
74 private static final ContainerNode compositeNode;
78 compositeNode = mockClass(ContainerNode.class);
79 } catch (final Exception e) {
80 throw new RuntimeException(e);
83 notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
84 } catch (Exception e) {
85 throw new ExceptionInInitializerError(e);
89 private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
91 public static final String TEST_NAMESPACE = "test:namespace";
92 public static final String TEST_MODULE = "test-module";
93 public static final String TEST_REVISION = "2013-07-22";
94 public static final SourceIdentifier TEST_SID = new SourceIdentifier(TEST_MODULE, Optional.of(TEST_REVISION));
95 public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
97 public static final SourceIdentifier TEST_SID2 = new SourceIdentifier(TEST_MODULE + "2", Optional.of(TEST_REVISION));
98 public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
100 private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
103 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
104 return NetconfStateSchemas.EMPTY;
109 public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
110 final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
112 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
113 final NetconfDeviceCommunicator listener = getListener();
115 final SchemaContextFactory schemaFactory = getSchemaFactory();
117 // Make fallback attempt to fail due to empty resolved sources
118 final SchemaResolutionException schemaResolutionException
119 = new SchemaResolutionException("fail first",
120 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
121 doReturn(Futures.immediateFailedCheckedFuture(
122 schemaResolutionException))
123 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
125 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
126 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
127 final NetconfDevice device = new NetconfDeviceBuilder()
128 .setReconnectOnSchemasChange(true)
129 .setSchemaResourcesDTO(schemaResourcesDTO)
130 .setGlobalProcessingExecutor(getExecutor())
132 .setSalFacade(facade)
135 // Monitoring not supported
136 final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
137 device.onRemoteSessionUp(sessionCaps, listener);
139 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
140 Mockito.verify(listener, Mockito.timeout(5000)).close();
141 Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
145 public void testNetconfDeviceMissingSource() throws Exception {
146 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
147 final NetconfDeviceCommunicator listener = getListener();
148 final SchemaContext schema = getSchema();
150 final SchemaContextFactory schemaFactory = getSchemaFactory();
152 // Make fallback attempt to fail due to empty resolved sources
153 final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
154 doAnswer(new Answer<Object>() {
156 public Object answer(final InvocationOnMock invocation) throws Throwable {
157 if(((Collection<?>) invocation.getArguments()[0]).size() == 2) {
158 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
160 return Futures.immediateCheckedFuture(schema);
163 }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
165 final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
167 public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
168 final Module first = Iterables.getFirst(schema.getModules(), null);
169 final QName qName = QName.create(first.getQNameModule(), first.getName());
170 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
171 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
172 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
176 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
177 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
179 final NetconfDevice device = new NetconfDeviceBuilder()
180 .setReconnectOnSchemasChange(true)
181 .setSchemaResourcesDTO(schemaResourcesDTO)
182 .setGlobalProcessingExecutor(getExecutor())
184 .setSalFacade(facade)
186 // Monitoring supported
187 final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
188 device.onRemoteSessionUp(sessionCaps, listener);
190 Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
191 Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
194 private SchemaSourceRegistry getSchemaRegistry() {
195 final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
196 final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
197 doNothing().when(mockReg).close();
198 doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
203 public void testNotificationBeforeSchema() throws Exception {
204 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
205 final NetconfDeviceCommunicator listener = getListener();
207 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
208 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaFactory(), stateSchemasResolver);
209 final NetconfDevice device = new NetconfDeviceBuilder()
210 .setReconnectOnSchemasChange(true)
211 .setSchemaResourcesDTO(schemaResourcesDTO)
212 .setGlobalProcessingExecutor(getExecutor())
214 .setSalFacade(facade)
217 device.onNotification(notification);
218 device.onNotification(notification);
220 verify(facade, times(0)).onNotification(any(DOMNotification.class));
222 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
223 Lists.newArrayList(TEST_CAPABILITY));
225 final DOMRpcService deviceRpc = mock(DOMRpcService.class);
227 device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass()), sessionCaps, deviceRpc);
229 verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
231 device.onNotification(notification);
232 verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
236 public void testNetconfDeviceReconnect() throws Exception {
237 final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
238 final NetconfDeviceCommunicator listener = getListener();
240 final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
242 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
243 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaContextProviderFactory, stateSchemasResolver);
244 final NetconfDevice device = new NetconfDeviceBuilder()
245 .setReconnectOnSchemasChange(true)
246 .setSchemaResourcesDTO(schemaResourcesDTO)
247 .setGlobalProcessingExecutor(getExecutor())
249 .setSalFacade(facade)
251 final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
252 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
253 device.onRemoteSessionUp(sessionCaps, listener);
255 verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
256 verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
258 device.onRemoteSessionDown();
259 verify(facade, timeout(5000)).onDeviceDisconnected();
261 device.onRemoteSessionUp(sessionCaps, listener);
263 verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
264 verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
267 private SchemaContextFactory getSchemaFactory() {
268 final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
269 doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
270 return schemaFactory;
273 public static SchemaContext getSchema() {
274 final YangParserImpl parser = new YangParserImpl();
275 final List<InputStream> modelsToParse = Lists.newArrayList(
276 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
278 final Set<Module> models = parser.parseYangModelsFromStreams(modelsToParse);
279 return parser.resolveSchemaContext(models);
282 private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
283 final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
284 doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
285 doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
286 doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
287 return remoteDeviceHandler;
290 private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
291 final T mock = mockClass(remoteDeviceHandlerClass);
292 doNothing().when(mock).close();
296 private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
297 final T mock = mock(remoteDeviceHandlerClass);
298 Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
302 public RemoteDeviceId getId() {
303 return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
306 public ExecutorService getExecutor() {
307 return Executors.newSingleThreadExecutor();
310 public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
311 final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
312 doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
313 doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
314 doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
315 return messageTransformer;
318 public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
319 final ArrayList<String> capabilities = Lists.newArrayList(
320 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
321 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
324 capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
327 capabilities.addAll(additionalCapabilities);
329 return NetconfSessionPreferences.fromStrings(
333 public NetconfDeviceCommunicator getListener() throws Exception {
334 final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
335 // doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
336 return remoteDeviceCommunicator;