Add blueprint wiring for netconf-console
[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         netconfCommands = new NetconfCommandsImpl(dataBroker);
125     }
126
127     @Test
128     public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
129         createTopology(LogicalDatastoreType.OPERATIONAL);
130
131         final Map map = netconfCommands.listDevices();
132         map.containsKey(NetconfConsoleConstants.NETCONF_ID);
133         assertTrue(map.containsKey(NODE_ID));
134
135         final Map mapNode = (Map) map.get(NODE_ID);
136         assertBaseNodeAttributes(mapNode);
137     }
138
139     @Test
140     public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
141         createTopology(LogicalDatastoreType.OPERATIONAL);
142
143         final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
144         mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
145         assertTrue(mapCorrect.containsKey(NODE_ID));
146
147         assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
148
149         final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
150         assertFalse(mapWrongPort.containsKey(NODE_ID));
151
152         final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
153         assertFalse(mapWrongIP.containsKey(NODE_ID));
154
155         final Map mapId = netconfCommands.showDevice(NODE_ID);
156         assertTrue(mapId.containsKey(NODE_ID));
157         assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
158     }
159
160     @Test
161     public void testConnectDisconnectDevice() throws InterruptedException, TimeoutException, TransactionCommitFailedException {
162         final NetconfNode netconfNode = new NetconfNodeBuilder().setPort(new PortNumber(7777)).
163                 setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
164
165         createTopology(LogicalDatastoreType.CONFIGURATION);
166         netconfCommands.connectDevice(netconfNode, "netconf-ID");
167         NetconfConsoleUtils.waitForUpdate("10.10.1.1");
168
169         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
170                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
171         final List<Node> nodes = topology.getNode();
172         assertEquals(2, nodes.size());
173
174         final Optional<Node> storedNode = nodes.stream().filter(node ->
175                 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
176
177         assertTrue(storedNode.isPresent());
178
179         NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
180         assertEquals(7777, storedNetconfNode.getPort().getValue().longValue());
181         assertEquals("10.10.1.1", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
182
183         netconfCommands.disconnectDevice("netconf-ID");
184
185         final Topology topologyDeleted = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
186                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
187         final List<Node> nodesDeleted = topologyDeleted.getNode();
188         assertEquals(1, nodesDeleted.size());
189
190         final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
191                 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
192
193         assertFalse(storedNodeDeleted.isPresent());
194     }
195
196     @Test
197     public void testUpdateDevice() throws TimeoutException, TransactionCommitFailedException {
198         //We need both, read data from OPERATIONAL DS and update data in CONFIGURATIONAL DS
199         createTopology(LogicalDatastoreType.OPERATIONAL);
200         createTopology(LogicalDatastoreType.CONFIGURATION);
201
202         final Map<String, String> update = new HashMap<>();
203         update.put(NetconfConsoleConstants.NETCONF_IP, "7.7.7.7");
204         update.put(NetconfConsoleConstants.TCP_ONLY, "true");
205
206         netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
207         NetconfConsoleUtils.waitForUpdate("7.7.7.7");
208
209         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
210                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
211         final List<Node> nodes = topology.getNode();
212         assertEquals(1, nodes.size());
213
214         final Optional<Node> storedNode = nodes.stream().filter(node ->
215                 node.getKey().getNodeId().getValue().equals(NODE_ID)).findFirst();
216         assertTrue(storedNode.isPresent());
217
218         NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
219         assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
220     }
221
222     @Test
223     public void testNetconfNodeFromIp() throws TimeoutException, TransactionCommitFailedException {
224         final List<Node> nodesNotExist = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
225         assertNull(nodesNotExist);
226         createTopology(LogicalDatastoreType.OPERATIONAL);
227         final List<Node> nodes = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
228         assertNotNull(nodes);
229         assertEquals(1, nodes.size());
230     }
231
232     private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
233         final List<Node> nodes = new ArrayList<>();
234         final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
235         nodes.add(node);
236
237         final Topology topology = new TopologyBuilder().
238                 setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
239                 setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
240
241         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
242         writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
243         writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
244     }
245
246     private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
247                                 String notificationCapabilityPrefix) {
248
249         final Host host = HostBuilder.getDefaultInstance(ip);
250         final PortNumber port = new PortNumber(portNumber);
251
252         final List<AvailableCapability> avCapList = new ArrayList<>();
253         avCapList.add(new AvailableCapabilityBuilder()
254                 .setCapabilityOrigin(AvailableCapability.CapabilityOrigin.UserDefined)
255                 .setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
256         final AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
257
258         final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
259                 setAvailableCapabilities(avCaps).build();
260         final NodeId nodeId = new NodeId(nodeIdent);
261         final NodeKey nk = new NodeKey(nodeId);
262         final NodeBuilder nb = new NodeBuilder();
263         nb.setKey(nk);
264         nb.setNodeId(nodeId);
265         nb.addAugmentation(NetconfNode.class, nn);
266         return nb.build();
267     }
268
269     private void assertBaseNodeAttributes(Map mapNode) {
270
271         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
272         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
273         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
274         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
275
276         assertEquals(NODE_ID, mapNode.get(NetconfConsoleConstants.NETCONF_ID));
277         assertEquals(IP, mapNode.get(NetconfConsoleConstants.NETCONF_IP));
278         assertEquals(String.valueOf(PORT), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
279         assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS));
280     }
281
282     private void assertBaseNodeAttributesImmutableList(Map mapNode) {
283         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
284         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
285         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
286         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
287
288         assertEquals(ImmutableList.of(NODE_ID), mapNode.get(NetconfConsoleConstants.NETCONF_ID));
289         assertEquals(ImmutableList.of(IP), mapNode.get(NetconfConsoleConstants.NETCONF_IP));
290         assertEquals(ImmutableList.of(String.valueOf(PORT)), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
291         assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
292     }
293
294     private List<InputStream> getYangSchemas() {
295         final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
296                 "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
297                 "/schemas/netconf-node-topology.yang");
298
299         final List<InputStream> schemas = new ArrayList<>();
300         for (String schemaPath : schemaPaths) {
301             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
302             schemas.add(resourceAsStream);
303         }
304         return schemas;
305     }
306
307     private static SchemaContext parseYangStreams(final List<InputStream> streams) {
308         CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
309                 .newBuild();
310         final SchemaContext schemaContext;
311         try {
312             schemaContext = reactor.buildEffective(streams);
313         } catch (ReactorException e) {
314             throw new RuntimeException("Unable to build schema context from " + streams, e);
315         }
316         return schemaContext;
317     }
318
319     private SchemaService createSchemaService() {
320         return new SchemaService() {
321
322             @Override
323             public void addModule(Module module) {
324             }
325
326             @Override
327             public void removeModule(Module module) {
328
329             }
330
331             @Override
332             public SchemaContext getSessionContext() {
333                 return schemaContext;
334             }
335
336             @Override
337             public SchemaContext getGlobalContext() {
338                 return schemaContext;
339             }
340
341             @Override
342             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
343                 listener.onGlobalContextUpdated(getGlobalContext());
344                 return new ListenerRegistration<SchemaContextListener>() {
345                     @Override
346                     public void close() {
347
348                     }
349
350                     @Override
351                     public SchemaContextListener getInstance() {
352                         return listener;
353                     }
354                 };
355             }
356         };
357     }
358 }