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