Merge "Add unit tests for sal-netconf-connector"
[netconf.git] / netconf / netconf-console / src / test / java / org / opendaylight / netconf / console / impl / NetconfCommandsImplTest.java
1 /*
2  * Copyright (c) 2016 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.console.impl;
10
11 import static junit.framework.TestCase.assertFalse;
12 import static junit.framework.TestCase.assertNull;
13 import static junit.framework.TestCase.assertTrue;
14 import static org.junit.Assert.assertEquals;
15 import static org.junit.Assert.assertNotNull;
16 import static org.mockito.Mockito.mock;
17
18 import com.google.common.collect.ImmutableList;
19 import java.io.InputStream;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.EnumMap;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import javassist.ClassPool;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
34 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
35 import org.opendaylight.controller.md.sal.binding.api.MountPointService;
36 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
37 import org.opendaylight.controller.md.sal.binding.impl.BindingDOMDataBrokerAdapter;
38 import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
42 import org.opendaylight.controller.sal.core.api.model.SchemaService;
43 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
44 import org.opendaylight.netconf.console.utils.NetconfConsoleConstants;
45 import org.opendaylight.netconf.console.utils.NetconfConsoleUtils;
46 import org.opendaylight.netconf.console.utils.NetconfIidFactory;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.HostBuilder;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilities;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilitiesBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
61 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
66 import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
67 import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
68 import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
69 import org.opendaylight.yangtools.concepts.ListenerRegistration;
70 import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
71 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
72 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
73 import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
74 import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
75 import org.opendaylight.yangtools.yang.model.api.Module;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
78 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
79 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
80 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
81
82 public class NetconfCommandsImplTest {
83
84     private static final String NODE_ID = "NodeID";
85     private static final String IP = "192.168.1.1";
86     private static final int PORT = 1234;
87     private static final NetconfNodeConnectionStatus.ConnectionStatus CONN_STATUS =
88             NetconfNodeConnectionStatus.ConnectionStatus.Connected;
89     private static final String CAP_PREFIX = "prefix";
90
91     private DataBroker dataBroker;
92     private SchemaContext schemaContext;
93     private NetconfCommandsImpl netconfCommands;
94
95     @Before
96     public void setUp() throws TransactionCommitFailedException, TimeoutException, InterruptedException {
97         schemaContext = parseYangStreams(getYangSchemas());
98         schemaContext.getModules();
99         final SchemaService schemaService = createSchemaService();
100
101         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
102         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
103
104         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
105         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
106         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
107
108         final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
109                 16, 16, "CommitFutures");
110
111         final ConcurrentDOMDataBroker cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
112
113         final ClassPool pool = ClassPool.getDefault();
114         final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
115         final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
116         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
117         codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
118
119         final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
120         final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
121         bindingToNormalized.onGlobalContextUpdated(schemaContext);
122         dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
123
124         final MountPointService mountPointService = mock(MountPointService.class);
125         netconfCommands = new NetconfCommandsImpl(dataBroker, mountPointService);
126     }
127
128     @Test
129     public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
130         createTopology(LogicalDatastoreType.OPERATIONAL);
131
132         final Map map = netconfCommands.listDevices();
133         map.containsKey(NetconfConsoleConstants.NETCONF_ID);
134         assertTrue(map.containsKey(NODE_ID));
135
136         final Map mapNode = (Map) map.get(NODE_ID);
137         assertBaseNodeAttributes(mapNode);
138     }
139
140     @Test
141     public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
142         createTopology(LogicalDatastoreType.OPERATIONAL);
143
144         final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
145         mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
146         assertTrue(mapCorrect.containsKey(NODE_ID));
147
148         assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
149
150         final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
151         assertFalse(mapWrongPort.containsKey(NODE_ID));
152
153         final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
154         assertFalse(mapWrongIP.containsKey(NODE_ID));
155
156         final Map mapId = netconfCommands.showDevice(NODE_ID);
157         assertTrue(mapId.containsKey(NODE_ID));
158         assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
159     }
160
161     @Test
162     public void testConnectDisconnectDevice() throws InterruptedException, TimeoutException, TransactionCommitFailedException {
163         final NetconfNode netconfNode = new NetconfNodeBuilder().setPort(new PortNumber(7777)).
164                 setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
165
166         createTopology(LogicalDatastoreType.CONFIGURATION);
167         netconfCommands.connectDevice(netconfNode, "netconf-ID");
168         NetconfConsoleUtils.waitForUpdate("10.10.1.1");
169
170         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
171                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
172         final List<Node> nodes = topology.getNode();
173         assertEquals(2, nodes.size());
174
175         final Optional<Node> storedNode = nodes.stream().filter(node ->
176                 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
177
178         assertTrue(storedNode.isPresent());
179
180         NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
181         assertEquals(7777, storedNetconfNode.getPort().getValue().longValue());
182         assertEquals("10.10.1.1", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
183
184         netconfCommands.disconnectDevice("netconf-ID");
185
186         final Topology topologyDeleted = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
187                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
188         final List<Node> nodesDeleted = topologyDeleted.getNode();
189         assertEquals(1, nodesDeleted.size());
190
191         final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
192                 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
193
194         assertFalse(storedNodeDeleted.isPresent());
195     }
196
197     @Test
198     public void testUpdateDevice() throws TimeoutException, TransactionCommitFailedException {
199         //We need both, read data from OPERATIONAL DS and update data in CONFIGURATIONAL DS
200         createTopology(LogicalDatastoreType.OPERATIONAL);
201         createTopology(LogicalDatastoreType.CONFIGURATION);
202
203         final Map<String, String> update = new HashMap<>();
204         update.put(NetconfConsoleConstants.NETCONF_IP, "7.7.7.7");
205         update.put(NetconfConsoleConstants.TCP_ONLY, "true");
206
207         netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
208         NetconfConsoleUtils.waitForUpdate("7.7.7.7");
209
210         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
211                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
212         final List<Node> nodes = topology.getNode();
213         assertEquals(1, nodes.size());
214
215         final Optional<Node> storedNode = nodes.stream().filter(node ->
216                 node.getKey().getNodeId().getValue().equals(NODE_ID)).findFirst();
217         assertTrue(storedNode.isPresent());
218
219         NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
220         assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
221     }
222
223     @Test
224     public void testNetconfNodeFromIp() throws TimeoutException, TransactionCommitFailedException {
225         final List<Node> nodesNotExist = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
226         assertNull(nodesNotExist);
227         createTopology(LogicalDatastoreType.OPERATIONAL);
228         final List<Node> nodes = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
229         assertNotNull(nodes);
230         assertEquals(1, nodes.size());
231     }
232
233     private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
234         final List<Node> nodes = new ArrayList<>();
235         final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
236         nodes.add(node);
237
238         final Topology topology = new TopologyBuilder().
239                 setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
240                 setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
241
242         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
243         writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
244         writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
245     }
246
247     private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
248                                 String notificationCapabilityPrefix) {
249
250         final Host host = HostBuilder.getDefaultInstance(ip);
251         final PortNumber port = new PortNumber(portNumber);
252
253         final List<AvailableCapability> avCapList = new ArrayList<>();
254         avCapList.add(new AvailableCapabilityBuilder()
255                 .setCapabilityOrigin(AvailableCapability.CapabilityOrigin.UserDefined)
256                 .setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
257         final AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
258
259         final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
260                 setAvailableCapabilities(avCaps).build();
261         final NodeId nodeId = new NodeId(nodeIdent);
262         final NodeKey nk = new NodeKey(nodeId);
263         final NodeBuilder nb = new NodeBuilder();
264         nb.setKey(nk);
265         nb.setNodeId(nodeId);
266         nb.addAugmentation(NetconfNode.class, nn);
267         return nb.build();
268     }
269
270     private void assertBaseNodeAttributes(Map mapNode) {
271
272         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
273         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
274         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
275         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
276
277         assertEquals(NODE_ID, mapNode.get(NetconfConsoleConstants.NETCONF_ID));
278         assertEquals(IP, mapNode.get(NetconfConsoleConstants.NETCONF_IP));
279         assertEquals(String.valueOf(PORT), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
280         assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS));
281     }
282
283     private void assertBaseNodeAttributesImmutableList(Map mapNode) {
284         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
285         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
286         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
287         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
288
289         assertEquals(ImmutableList.of(NODE_ID), mapNode.get(NetconfConsoleConstants.NETCONF_ID));
290         assertEquals(ImmutableList.of(IP), mapNode.get(NetconfConsoleConstants.NETCONF_IP));
291         assertEquals(ImmutableList.of(String.valueOf(PORT)), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
292         assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
293     }
294
295     private List<InputStream> getYangSchemas() {
296         final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
297                 "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
298                 "/schemas/netconf-node-topology.yang");
299
300         final List<InputStream> schemas = new ArrayList<>();
301         for (String schemaPath : schemaPaths) {
302             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
303             schemas.add(resourceAsStream);
304         }
305         return schemas;
306     }
307
308     private static SchemaContext parseYangStreams(final List<InputStream> streams) {
309         CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
310                 .newBuild();
311         final SchemaContext schemaContext;
312         try {
313             schemaContext = reactor.buildEffective(streams);
314         } catch (ReactorException e) {
315             throw new RuntimeException("Unable to build schema context from " + streams, e);
316         }
317         return schemaContext;
318     }
319
320     private SchemaService createSchemaService() {
321         return new SchemaService() {
322
323             @Override
324             public void addModule(Module module) {
325             }
326
327             @Override
328             public void removeModule(Module module) {
329
330             }
331
332             @Override
333             public SchemaContext getSessionContext() {
334                 return schemaContext;
335             }
336
337             @Override
338             public SchemaContext getGlobalContext() {
339                 return schemaContext;
340             }
341
342             @Override
343             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
344                 listener.onGlobalContextUpdated(getGlobalContext());
345                 return new ListenerRegistration<SchemaContextListener>() {
346                     @Override
347                     public void close() {
348
349                     }
350
351                     @Override
352                     public SchemaContextListener getInstance() {
353                         return listener;
354                     }
355                 };
356             }
357         };
358     }
359 }