61bd73a0a8e576963ce4b2ac1a80fd5840c42639
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / test / java / org / opendaylight / controller / sal / connect / netconf / NetconfDeviceTest.java
1 /*
2 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3 *
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
7 */
8 package org.opendaylight.controller.sal.connect.netconf;
9
10 import static org.mockito.Matchers.any;
11 import static org.mockito.Matchers.anyCollectionOf;
12 import static org.mockito.Matchers.anyString;
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;
20
21 import com.google.common.base.Optional;
22 import com.google.common.collect.HashMultimap;
23 import com.google.common.collect.Lists;
24 import com.google.common.util.concurrent.Futures;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Set;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import org.junit.Test;
34 import org.mockito.Mockito;
35 import org.mockito.invocation.InvocationOnMock;
36 import org.mockito.stubbing.Answer;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
38 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
39 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
40 import org.opendaylight.controller.netconf.api.NetconfMessage;
41 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
42 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
43 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
44 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
45 import org.opendaylight.controller.sal.connect.api.SchemaSourceProviderFactory;
46 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
47 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
48 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc;
49 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
50 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
51 import org.opendaylight.controller.sal.core.api.RpcImplementation;
52 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
58 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
59 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
60 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
61 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
62 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
63 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
64 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
65 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
66
67 public class NetconfDeviceTest {
68
69     private static final NetconfMessage notification;
70
71     private static final ContainerNode compositeNode;
72
73     static {
74         try {
75             compositeNode = mockClass(ContainerNode.class);
76         } catch (final Exception e) {
77             throw new RuntimeException(e);
78         }
79         try {
80             notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
81         } catch (Exception e) {
82             throw new ExceptionInInitializerError(e);
83         }
84     }
85
86     private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
87
88     public static final String TEST_NAMESPACE = "test:namespace";
89     public static final String TEST_MODULE = "test-module";
90     public static final String TEST_REVISION = "2013-07-22";
91     public static final SourceIdentifier TEST_SID = new SourceIdentifier(TEST_MODULE, Optional.of(TEST_REVISION));
92     public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
93
94     public static final SourceIdentifier TEST_SID2 = new SourceIdentifier(TEST_MODULE + "2", Optional.of(TEST_REVISION));
95     public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
96
97     private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
98
99         @Override
100         public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
101             return NetconfStateSchemas.EMPTY;
102         }
103     };
104
105     @Test
106     public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
107         final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
108
109         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
110         final NetconfDeviceCommunicator listener = getListener();
111
112         final SchemaContextFactory schemaFactory = getSchemaFactory();
113
114         // Make fallback attempt to fail due to empty resolved sources
115         final SchemaResolutionException schemaResolutionException
116                 = new SchemaResolutionException("fail first",
117                 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
118         doReturn(Futures.immediateFailedCheckedFuture(
119                 schemaResolutionException))
120                 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
121
122         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
123                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
124         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(),true);
125         // Monitoring not supported
126         final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
127         device.onRemoteSessionUp(sessionCaps, listener);
128
129         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
130         Mockito.verify(listener, Mockito.timeout(5000)).close();
131         Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
132     }
133
134     @Test
135     public void testNetconfDeviceMissingSource() throws Exception {
136         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
137         final NetconfDeviceCommunicator listener = getListener();
138
139         final SchemaContextFactory schemaFactory = getSchemaFactory();
140
141         // Make fallback attempt to fail due to empty resolved sources
142         final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
143         doAnswer(new Answer<Object>() {
144             @Override
145             public Object answer(final InvocationOnMock invocation) throws Throwable {
146                 if(((Collection<?>) invocation.getArguments()[0]).size() == 2) {
147                     return Futures.immediateFailedCheckedFuture(schemaResolutionException);
148                 } else {
149                     return Futures.immediateCheckedFuture(getSchema());
150                 }
151             }
152         }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
153
154         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
155                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
156         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), true);
157         // Monitoring supported
158         final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
159         device.onRemoteSessionUp(sessionCaps, listener);
160
161         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
162         Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
163     }
164
165     private SchemaSourceRegistry getSchemaRegistry() {
166         final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
167         final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
168         doNothing().when(mockReg).close();
169         doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
170         return mock;
171     }
172
173     @Test
174     public void testNotificationBeforeSchema() throws Exception {
175         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
176         final NetconfDeviceCommunicator listener = getListener();
177
178         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
179                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaFactory(), stateSchemasResolver);
180         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), true);
181
182         device.onNotification(notification);
183         device.onNotification(notification);
184
185         verify(facade, times(0)).onNotification(any(ContainerNode.class));
186
187         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
188                 Lists.newArrayList(TEST_CAPABILITY));
189
190         final DOMRpcService deviceRpc = mock(DOMRpcService.class);
191
192         device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass()), sessionCaps, deviceRpc);
193
194         verify(facade, timeout(10000).times(2)).onNotification(any(ContainerNode.class));
195
196         device.onNotification(notification);
197         verify(facade, timeout(10000).times(3)).onNotification(any(ContainerNode.class));
198     }
199
200     @Test
201     public void testNetconfDeviceReconnect() throws Exception {
202         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
203         final NetconfDeviceCommunicator listener = getListener();
204
205         final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
206
207         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
208                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaContextProviderFactory, stateSchemasResolver);
209         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), true);
210         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
211                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
212         device.onRemoteSessionUp(sessionCaps, listener);
213
214         verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
215         verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
216
217         device.onRemoteSessionDown();
218         verify(facade, timeout(5000)).onDeviceDisconnected();
219
220         device.onRemoteSessionUp(sessionCaps, listener);
221
222         verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
223         verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
224     }
225
226     private SchemaContextFactory getSchemaFactory() {
227         final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
228         doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
229         return schemaFactory;
230     }
231
232     public static SchemaContext getSchema() {
233         final YangParserImpl parser = new YangParserImpl();
234         final List<InputStream> modelsToParse = Lists.newArrayList(
235                 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
236         );
237         final Set<Module> models = parser.parseYangModelsFromStreams(modelsToParse);
238         return parser.resolveSchemaContext(models);
239     }
240
241     private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
242         final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
243         doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
244         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
245         doNothing().when(remoteDeviceHandler).onNotification(any(ContainerNode.class));
246         return remoteDeviceHandler;
247     }
248
249     private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
250         final T mock = mockClass(remoteDeviceHandlerClass);
251         doNothing().when(mock).close();
252         return mock;
253     }
254
255     public SchemaSourceProviderFactory<InputStream> getSourceProviderFactory() {
256         final SchemaSourceProviderFactory<InputStream> mock = mockClass(SchemaSourceProviderFactory.class);
257
258         final SchemaSourceProvider<InputStream> schemaSourceProvider = mockClass(SchemaSourceProvider.class);
259         doReturn(Optional.<String>absent()).when(schemaSourceProvider).getSchemaSource(anyString(), any(Optional.class));
260
261         doReturn(schemaSourceProvider).when(mock).createSourceProvider(any(RpcImplementation.class));
262         return mock;
263     }
264
265     private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
266         final T mock = mock(remoteDeviceHandlerClass);
267         Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
268         return mock;
269     }
270
271     public RemoteDeviceId getId() {
272         return new RemoteDeviceId("test-D");
273     }
274
275     public ExecutorService getExecutor() {
276         return Executors.newSingleThreadExecutor();
277     }
278
279     public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
280         final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
281         doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(ContainerNode.class));
282         doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
283         doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
284         return messageTransformer;
285     }
286
287     public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
288         final ArrayList<String> capabilities = Lists.newArrayList(
289                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
290                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
291
292         if(addMonitor) {
293             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
294         }
295
296         capabilities.addAll(additionalCapabilities);
297
298         return NetconfSessionPreferences.fromStrings(
299                 capabilities);
300     }
301
302     public NetconfDeviceCommunicator getListener() throws Exception {
303         final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
304 //        doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
305         return remoteDeviceCommunicator;
306     }
307 }