Adjust for mdsal-binding-dom-codec movement
[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
17 import com.google.common.collect.ImmutableList;
18 import java.io.InputStream;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.EnumMap;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
29 import javassist.ClassPool;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
35 import org.opendaylight.controller.md.sal.binding.impl.BindingDOMDataBrokerAdapter;
36 import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
37 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
39 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
40 import org.opendaylight.controller.sal.core.api.model.SchemaService;
41 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
42 import org.opendaylight.mdsal.binding.dom.codec.gen.impl.DataObjectSerializerGenerator;
43 import org.opendaylight.mdsal.binding.dom.codec.gen.impl.StreamWriterGenerator;
44 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
45 import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy;
46 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
47 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
48 import org.opendaylight.mdsal.binding.generator.util.JavassistUtils;
49 import org.opendaylight.netconf.console.utils.NetconfConsoleConstants;
50 import org.opendaylight.netconf.console.utils.NetconfConsoleUtils;
51 import org.opendaylight.netconf.console.utils.NetconfIidFactory;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.HostBuilder;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilities;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilitiesBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
66 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
67 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
68 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
69 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
70 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
71 import org.opendaylight.yangtools.concepts.ListenerRegistration;
72 import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
73 import org.opendaylight.yangtools.yang.model.api.Module;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
76 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
77
78 public class NetconfCommandsImplTest {
79
80     private static final String NODE_ID = "NodeID";
81     private static final String IP = "192.168.1.1";
82     private static final int PORT = 1234;
83     private static final NetconfNodeConnectionStatus.ConnectionStatus CONN_STATUS =
84             NetconfNodeConnectionStatus.ConnectionStatus.Connected;
85     private static final String CAP_PREFIX = "prefix";
86
87     private DataBroker dataBroker;
88     private SchemaContext schemaContext;
89     private NetconfCommandsImpl netconfCommands;
90
91     @Before
92     public void setUp() throws Exception {
93         schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
94         schemaContext.getModules();
95         final SchemaService schemaService = createSchemaService();
96
97         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
98         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
99
100         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
101         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
102         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
103
104         final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
105                 16, 16, "CommitFutures");
106
107         final ConcurrentDOMDataBroker cDOMDataBroker =
108                 new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
109
110         final ClassPool pool = ClassPool.getDefault();
111         final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
112         final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
113         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
114         codecRegistry
115                 .onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
116
117         final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
118         final BindingToNormalizedNodeCodec bindingToNormalized =
119                 new BindingToNormalizedNodeCodec(loading, codecRegistry);
120         bindingToNormalized.onGlobalContextUpdated(schemaContext);
121         dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
122
123         netconfCommands = new NetconfCommandsImpl(dataBroker);
124     }
125
126     @Test
127     public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
128         createTopology(LogicalDatastoreType.OPERATIONAL);
129
130         final Map map = netconfCommands.listDevices();
131         map.containsKey(NetconfConsoleConstants.NETCONF_ID);
132         assertTrue(map.containsKey(NODE_ID));
133
134         final Map mapNode = (Map) map.get(NODE_ID);
135         assertBaseNodeAttributes(mapNode);
136     }
137
138     @Test
139     public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
140         createTopology(LogicalDatastoreType.OPERATIONAL);
141
142         final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
143         mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
144         assertTrue(mapCorrect.containsKey(NODE_ID));
145
146         assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
147
148         final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
149         assertFalse(mapWrongPort.containsKey(NODE_ID));
150
151         final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
152         assertFalse(mapWrongIP.containsKey(NODE_ID));
153
154         final Map mapId = netconfCommands.showDevice(NODE_ID);
155         assertTrue(mapId.containsKey(NODE_ID));
156         assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
157     }
158
159     @Test
160     public void testConnectDisconnectDevice()
161             throws InterruptedException, TimeoutException, TransactionCommitFailedException {
162         final NetconfNode netconfNode = new NetconfNodeBuilder()
163                 .setPort(new PortNumber(7777)).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         update.put(NetconfConsoleConstants.SCHEMALESS, "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)
234             throws TransactionCommitFailedException, TimeoutException {
235         final List<Node> nodes = new ArrayList<>();
236         final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
237         nodes.add(node);
238
239         final Topology topology = new TopologyBuilder()
240                 .setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())))
241                 .setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
242
243         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
244         writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
245         writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
246     }
247
248     private Node getNetconfNode(String nodeIdent, String ip, int portNumber,
249                                 NetconfNodeConnectionStatus.ConnectionStatus cs, String notificationCapabilityPrefix) {
250
251         final Host host = HostBuilder.getDefaultInstance(ip);
252         final PortNumber port = new PortNumber(portNumber);
253
254         final List<AvailableCapability> avCapList = new ArrayList<>();
255         avCapList.add(new AvailableCapabilityBuilder()
256                 .setCapabilityOrigin(AvailableCapability.CapabilityOrigin.UserDefined)
257                 .setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
258         final AvailableCapabilities avCaps =
259                 new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
260
261         final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port)
262                 .setAvailableCapabilities(avCaps).build();
263         final NodeId nodeId = new NodeId(nodeIdent);
264         final NodeKey nk = new NodeKey(nodeId);
265         final NodeBuilder nb = new NodeBuilder();
266         nb.setKey(nk);
267         nb.setNodeId(nodeId);
268         nb.addAugmentation(NetconfNode.class, nn);
269         return nb.build();
270     }
271
272     private void assertBaseNodeAttributes(Map mapNode) {
273
274         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
275         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
276         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
277         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
278
279         assertEquals(NODE_ID, mapNode.get(NetconfConsoleConstants.NETCONF_ID));
280         assertEquals(IP, mapNode.get(NetconfConsoleConstants.NETCONF_IP));
281         assertEquals(String.valueOf(PORT), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
282         assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS));
283     }
284
285     private void assertBaseNodeAttributesImmutableList(Map mapNode) {
286         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
287         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
288         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
289         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
290
291         assertEquals(ImmutableList.of(NODE_ID), mapNode.get(NetconfConsoleConstants.NETCONF_ID));
292         assertEquals(ImmutableList.of(IP), mapNode.get(NetconfConsoleConstants.NETCONF_IP));
293         assertEquals(ImmutableList.of(String.valueOf(PORT)), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
294         assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
295     }
296
297     private List<InputStream> getYangSchemas() {
298         final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
299                 "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
300                 "/schemas/netconf-node-topology.yang");
301
302         final List<InputStream> schemas = new ArrayList<>();
303         for (String schemaPath : schemaPaths) {
304             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
305             schemas.add(resourceAsStream);
306         }
307         return schemas;
308     }
309
310     private SchemaService createSchemaService() {
311         return new SchemaService() {
312
313             @Override
314             public void addModule(Module module) {
315             }
316
317             @Override
318             public void removeModule(Module module) {
319
320             }
321
322             @Override
323             public SchemaContext getSessionContext() {
324                 return schemaContext;
325             }
326
327             @Override
328             public SchemaContext getGlobalContext() {
329                 return schemaContext;
330             }
331
332             @Override
333             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
334                     final SchemaContextListener listener) {
335                 listener.onGlobalContextUpdated(getGlobalContext());
336                 return new ListenerRegistration<SchemaContextListener>() {
337                     @Override
338                     public void close() {
339
340                     }
341
342                     @Override
343                     public SchemaContextListener getInstance() {
344                         return listener;
345                     }
346                 };
347             }
348         };
349     }
350 }