Merge "Bug 3864: Notify netconf monitoring about changes in session"
[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.Set;
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;
69
70 public class NetconfDeviceTest {
71
72     private static final NetconfMessage notification;
73
74     private static final ContainerNode compositeNode;
75
76     static {
77         try {
78             compositeNode = mockClass(ContainerNode.class);
79         } catch (final Exception e) {
80             throw new RuntimeException(e);
81         }
82         try {
83             notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
84         } catch (Exception e) {
85             throw new ExceptionInInitializerError(e);
86         }
87     }
88
89     private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
90
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;
96
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;
99
100     private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
101
102         @Override
103         public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
104             return NetconfStateSchemas.EMPTY;
105         }
106     };
107
108     @Test
109     public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
110         final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
111
112         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
113         final NetconfDeviceCommunicator listener = getListener();
114
115         final SchemaContextFactory schemaFactory = getSchemaFactory();
116
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));
124
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())
131                 .setId(getId())
132                 .setSalFacade(facade)
133                 .build();
134
135         // Monitoring not supported
136         final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
137         device.onRemoteSessionUp(sessionCaps, listener);
138
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));
142     }
143
144     @Test
145     public void testNetconfDeviceMissingSource() throws Exception {
146         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
147         final NetconfDeviceCommunicator listener = getListener();
148         final SchemaContext schema = getSchema();
149
150         final SchemaContextFactory schemaFactory = getSchemaFactory();
151
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>() {
155             @Override
156             public Object answer(final InvocationOnMock invocation) throws Throwable {
157                 if(((Collection<?>) invocation.getArguments()[0]).size() == 2) {
158                     return Futures.immediateFailedCheckedFuture(schemaResolutionException);
159                 } else {
160                     return Futures.immediateCheckedFuture(schema);
161                 }
162             }
163         }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
164
165         final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
166             @Override
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));
173             }
174         };
175
176         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
177                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
178
179         final NetconfDevice device = new NetconfDeviceBuilder()
180                 .setReconnectOnSchemasChange(true)
181                 .setSchemaResourcesDTO(schemaResourcesDTO)
182                 .setGlobalProcessingExecutor(getExecutor())
183                 .setId(getId())
184                 .setSalFacade(facade)
185                 .build();
186         // Monitoring supported
187         final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
188         device.onRemoteSessionUp(sessionCaps, listener);
189
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));
192     }
193
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));
199         return mock;
200     }
201
202     @Test
203     public void testNotificationBeforeSchema() throws Exception {
204         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
205         final NetconfDeviceCommunicator listener = getListener();
206
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())
213                 .setId(getId())
214                 .setSalFacade(facade)
215                 .build();
216
217         device.onNotification(notification);
218         device.onNotification(notification);
219
220         verify(facade, times(0)).onNotification(any(DOMNotification.class));
221
222         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
223                 Lists.newArrayList(TEST_CAPABILITY));
224
225         final DOMRpcService deviceRpc = mock(DOMRpcService.class);
226
227         device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
228
229         verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
230
231         device.onNotification(notification);
232         verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
233     }
234
235     @Test
236     public void testNetconfDeviceReconnect() throws Exception {
237         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
238         final NetconfDeviceCommunicator listener = getListener();
239
240         final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
241
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())
248                 .setId(getId())
249                 .setSalFacade(facade)
250                 .build();
251         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
252                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
253         device.onRemoteSessionUp(sessionCaps, listener);
254
255         verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
256         verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
257
258         device.onRemoteSessionDown();
259         verify(facade, timeout(5000)).onDeviceDisconnected();
260
261         device.onRemoteSessionUp(sessionCaps, listener);
262
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));
265     }
266
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;
271     }
272
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")
277         );
278         final Set<Module> models = parser.parseYangModelsFromStreams(modelsToParse);
279         return parser.resolveSchemaContext(models);
280     }
281
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;
288     }
289
290     private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
291         final T mock = mockClass(remoteDeviceHandlerClass);
292         doNothing().when(mock).close();
293         return mock;
294     }
295
296     private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
297         final T mock = mock(remoteDeviceHandlerClass);
298         Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
299         return mock;
300     }
301
302     public RemoteDeviceId getId() {
303         return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
304     }
305
306     public ExecutorService getExecutor() {
307         return Executors.newSingleThreadExecutor();
308     }
309
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;
316     }
317
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);
322
323         if(addMonitor) {
324             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
325         }
326
327         capabilities.addAll(additionalCapabilities);
328
329         return NetconfSessionPreferences.fromStrings(
330                 capabilities);
331     }
332
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;
337     }
338 }