Bug 7432 - eliminate use of yang-parser-impl internals
[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.netconf.console.utils.NetconfConsoleConstants;
43 import org.opendaylight.netconf.console.utils.NetconfConsoleUtils;
44 import org.opendaylight.netconf.console.utils.NetconfIidFactory;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.HostBuilder;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilities;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilitiesBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
56 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
61 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
64 import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
65 import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
66 import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
69 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
70 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
71 import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
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 = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
108
109         final ClassPool pool = ClassPool.getDefault();
110         final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
111         final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
112         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
113         codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
114
115         final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
116         final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
117         bindingToNormalized.onGlobalContextUpdated(schemaContext);
118         dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
119
120         netconfCommands = new NetconfCommandsImpl(dataBroker);
121     }
122
123     @Test
124     public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
125         createTopology(LogicalDatastoreType.OPERATIONAL);
126
127         final Map map = netconfCommands.listDevices();
128         map.containsKey(NetconfConsoleConstants.NETCONF_ID);
129         assertTrue(map.containsKey(NODE_ID));
130
131         final Map mapNode = (Map) map.get(NODE_ID);
132         assertBaseNodeAttributes(mapNode);
133     }
134
135     @Test
136     public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
137         createTopology(LogicalDatastoreType.OPERATIONAL);
138
139         final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
140         mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
141         assertTrue(mapCorrect.containsKey(NODE_ID));
142
143         assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
144
145         final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
146         assertFalse(mapWrongPort.containsKey(NODE_ID));
147
148         final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
149         assertFalse(mapWrongIP.containsKey(NODE_ID));
150
151         final Map mapId = netconfCommands.showDevice(NODE_ID);
152         assertTrue(mapId.containsKey(NODE_ID));
153         assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
154     }
155
156     @Test
157     public void testConnectDisconnectDevice() throws InterruptedException, TimeoutException, TransactionCommitFailedException {
158         final NetconfNode netconfNode = new NetconfNodeBuilder().setPort(new PortNumber(7777)).
159                 setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
160
161         createTopology(LogicalDatastoreType.CONFIGURATION);
162         netconfCommands.connectDevice(netconfNode, "netconf-ID");
163         NetconfConsoleUtils.waitForUpdate("10.10.1.1");
164
165         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
166                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
167         final List<Node> nodes = topology.getNode();
168         assertEquals(2, nodes.size());
169
170         final Optional<Node> storedNode = nodes.stream().filter(node ->
171                 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
172
173         assertTrue(storedNode.isPresent());
174
175         NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
176         assertEquals(7777, storedNetconfNode.getPort().getValue().longValue());
177         assertEquals("10.10.1.1", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
178
179         netconfCommands.disconnectDevice("netconf-ID");
180
181         final Topology topologyDeleted = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
182                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
183         final List<Node> nodesDeleted = topologyDeleted.getNode();
184         assertEquals(1, nodesDeleted.size());
185
186         final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
187                 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
188
189         assertFalse(storedNodeDeleted.isPresent());
190     }
191
192     @Test
193     public void testUpdateDevice() throws TimeoutException, TransactionCommitFailedException {
194         //We need both, read data from OPERATIONAL DS and update data in CONFIGURATIONAL DS
195         createTopology(LogicalDatastoreType.OPERATIONAL);
196         createTopology(LogicalDatastoreType.CONFIGURATION);
197
198         final Map<String, String> update = new HashMap<>();
199         update.put(NetconfConsoleConstants.NETCONF_IP, "7.7.7.7");
200         update.put(NetconfConsoleConstants.TCP_ONLY, "true");
201         update.put(NetconfConsoleConstants.SCHEMALESS, "true");
202
203         netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
204         NetconfConsoleUtils.waitForUpdate("7.7.7.7");
205
206         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
207                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
208         final List<Node> nodes = topology.getNode();
209         assertEquals(1, nodes.size());
210
211         final Optional<Node> storedNode = nodes.stream().filter(node ->
212                 node.getKey().getNodeId().getValue().equals(NODE_ID)).findFirst();
213         assertTrue(storedNode.isPresent());
214
215         NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
216         assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
217     }
218
219     @Test
220     public void testNetconfNodeFromIp() throws TimeoutException, TransactionCommitFailedException {
221         final List<Node> nodesNotExist = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
222         assertNull(nodesNotExist);
223         createTopology(LogicalDatastoreType.OPERATIONAL);
224         final List<Node> nodes = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
225         assertNotNull(nodes);
226         assertEquals(1, nodes.size());
227     }
228
229     private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
230         final List<Node> nodes = new ArrayList<>();
231         final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
232         nodes.add(node);
233
234         final Topology topology = new TopologyBuilder().
235                 setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
236                 setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
237
238         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
239         writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
240         writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
241     }
242
243     private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
244                                 String notificationCapabilityPrefix) {
245
246         final Host host = HostBuilder.getDefaultInstance(ip);
247         final PortNumber port = new PortNumber(portNumber);
248
249         final List<AvailableCapability> avCapList = new ArrayList<>();
250         avCapList.add(new AvailableCapabilityBuilder()
251                 .setCapabilityOrigin(AvailableCapability.CapabilityOrigin.UserDefined)
252                 .setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
253         final AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
254
255         final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
256                 setAvailableCapabilities(avCaps).build();
257         final NodeId nodeId = new NodeId(nodeIdent);
258         final NodeKey nk = new NodeKey(nodeId);
259         final NodeBuilder nb = new NodeBuilder();
260         nb.setKey(nk);
261         nb.setNodeId(nodeId);
262         nb.addAugmentation(NetconfNode.class, nn);
263         return nb.build();
264     }
265
266     private void assertBaseNodeAttributes(Map mapNode) {
267
268         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
269         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
270         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
271         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
272
273         assertEquals(NODE_ID, mapNode.get(NetconfConsoleConstants.NETCONF_ID));
274         assertEquals(IP, mapNode.get(NetconfConsoleConstants.NETCONF_IP));
275         assertEquals(String.valueOf(PORT), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
276         assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS));
277     }
278
279     private void assertBaseNodeAttributesImmutableList(Map mapNode) {
280         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
281         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
282         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
283         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
284
285         assertEquals(ImmutableList.of(NODE_ID), mapNode.get(NetconfConsoleConstants.NETCONF_ID));
286         assertEquals(ImmutableList.of(IP), mapNode.get(NetconfConsoleConstants.NETCONF_IP));
287         assertEquals(ImmutableList.of(String.valueOf(PORT)), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
288         assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
289     }
290
291     private List<InputStream> getYangSchemas() {
292         final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
293                 "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
294                 "/schemas/netconf-node-topology.yang");
295
296         final List<InputStream> schemas = new ArrayList<>();
297         for (String schemaPath : schemaPaths) {
298             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
299             schemas.add(resourceAsStream);
300         }
301         return schemas;
302     }
303
304     private SchemaService createSchemaService() {
305         return new SchemaService() {
306
307             @Override
308             public void addModule(Module module) {
309             }
310
311             @Override
312             public void removeModule(Module module) {
313
314             }
315
316             @Override
317             public SchemaContext getSessionContext() {
318                 return schemaContext;
319             }
320
321             @Override
322             public SchemaContext getGlobalContext() {
323                 return schemaContext;
324             }
325
326             @Override
327             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
328                 listener.onGlobalContextUpdated(getGlobalContext());
329                 return new ListenerRegistration<SchemaContextListener>() {
330                     @Override
331                     public void close() {
332
333                     }
334
335                     @Override
336                     public SchemaContextListener getInstance() {
337                         return listener;
338                     }
339                 };
340             }
341         };
342     }
343 }