8c14f8cd1b3fd84f66f8e3dcc5036126c4a0e254
[netconf.git] / netconf / sal-netconf-connector / src / test / java / org / opendaylight / netconf / sal / connect / netconf / NetconfDeviceTest.java
1 /*
2  * Copyright (c) 2014, 2015 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
9 package org.opendaylight.netconf.sal.connect.netconf;
10
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;
20
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;
70
71 public class NetconfDeviceTest {
72
73     private static final NetconfMessage notification;
74
75     private static final ContainerNode compositeNode;
76
77     static {
78         try {
79             compositeNode = mockClass(ContainerNode.class);
80         } catch (final Exception e) {
81             throw new RuntimeException(e);
82         }
83         try {
84             notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
85         } catch (Exception e) {
86             throw new ExceptionInInitializerError(e);
87         }
88     }
89
90     private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
91
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;
97
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;
100
101     private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
102
103         @Override
104         public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
105             return NetconfStateSchemas.EMPTY;
106         }
107     };
108
109     @Test
110     public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
111         final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
112
113         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
114         final NetconfDeviceCommunicator listener = getListener();
115
116         final SchemaContextFactory schemaFactory = getSchemaFactory();
117
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));
125
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())
132                 .setId(getId())
133                 .setSalFacade(facade)
134                 .build();
135
136         // Monitoring not supported
137         final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
138         device.onRemoteSessionUp(sessionCaps, listener);
139
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));
143     }
144
145     @Test
146     public void testNetconfDeviceMissingSource() throws Exception {
147         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
148         final NetconfDeviceCommunicator listener = getListener();
149         final SchemaContext schema = getSchema();
150
151         final SchemaContextFactory schemaFactory = getSchemaFactory();
152
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>() {
156             @Override
157             public Object answer(final InvocationOnMock invocation) throws Throwable {
158                 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
159                     return Futures.immediateFailedCheckedFuture(schemaResolutionException);
160                 } else {
161                     return Futures.immediateCheckedFuture(schema);
162                 }
163             }
164         }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
165
166         final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
167             @Override
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));
174             }
175         };
176
177         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
178                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
179
180         final NetconfDevice device = new NetconfDeviceBuilder()
181                 .setReconnectOnSchemasChange(true)
182                 .setSchemaResourcesDTO(schemaResourcesDTO)
183                 .setGlobalProcessingExecutor(getExecutor())
184                 .setId(getId())
185                 .setSalFacade(facade)
186                 .build();
187         // Monitoring supported
188         final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
189         device.onRemoteSessionUp(sessionCaps, listener);
190
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));
193     }
194
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));
200         return mock;
201     }
202
203     @Test
204     public void testNotificationBeforeSchema() throws Exception {
205         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
206         final NetconfDeviceCommunicator listener = getListener();
207
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())
214                 .setId(getId())
215                 .setSalFacade(facade)
216                 .build();
217
218         device.onNotification(notification);
219         device.onNotification(notification);
220
221         verify(facade, times(0)).onNotification(any(DOMNotification.class));
222
223         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
224                 Lists.newArrayList(TEST_CAPABILITY));
225
226         final DOMRpcService deviceRpc = mock(DOMRpcService.class);
227
228         device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
229
230         verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
231
232         device.onNotification(notification);
233         verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
234     }
235
236     @Test
237     public void testNetconfDeviceReconnect() throws Exception {
238         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
239         final NetconfDeviceCommunicator listener = getListener();
240
241         final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
242
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())
249                 .setId(getId())
250                 .setSalFacade(facade)
251                 .build();
252         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
253                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
254         device.onRemoteSessionUp(sessionCaps, listener);
255
256         verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
257         verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
258
259         device.onRemoteSessionDown();
260         verify(facade, timeout(5000)).onDeviceDisconnected();
261
262         device.onRemoteSessionUp(sessionCaps, listener);
263
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));
266     }
267
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;
272     }
273
274     private static SchemaContext parseYangStreams(final List<InputStream> streams) {
275         CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
276                 .newBuild();
277         final SchemaContext schemaContext;
278         try {
279             schemaContext = reactor.buildEffective(streams);
280         } catch (ReactorException e) {
281             throw new RuntimeException("Unable to build schema context from " + streams, e);
282         }
283         return schemaContext;
284     }
285
286     public static SchemaContext getSchema() {
287         final List<InputStream> modelsToParse = Lists.newArrayList(
288                 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
289         );
290         return parseYangStreams(modelsToParse);
291     }
292
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;
299     }
300
301     private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
302         final T mock = mockClass(remoteDeviceHandlerClass);
303         doNothing().when(mock).close();
304         return mock;
305     }
306
307     private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
308         final T mock = mock(remoteDeviceHandlerClass);
309         Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
310         return mock;
311     }
312
313     public RemoteDeviceId getId() {
314         return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
315     }
316
317     public ExecutorService getExecutor() {
318         return Executors.newSingleThreadExecutor();
319     }
320
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;
327     }
328
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);
333
334         if(addMonitor) {
335             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
336         }
337
338         capabilities.addAll(additionalCapabilities);
339
340         return NetconfSessionPreferences.fromStrings(
341                 capabilities);
342     }
343
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;
348     }
349 }