Merge "InstanceIdentifierCodecImpl JUnit test"
[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         update.put(NetconfConsoleConstants.SCHEMALESS, "true");
207
208         netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
209         NetconfConsoleUtils.waitForUpdate("7.7.7.7");
210
211         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
212                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
213         final List<Node> nodes = topology.getNode();
214         assertEquals(1, nodes.size());
215
216         final Optional<Node> storedNode = nodes.stream().filter(node ->
217                 node.getKey().getNodeId().getValue().equals(NODE_ID)).findFirst();
218         assertTrue(storedNode.isPresent());
219
220         NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
221         assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
222     }
223
224     @Test
225     public void testNetconfNodeFromIp() throws TimeoutException, TransactionCommitFailedException {
226         final List<Node> nodesNotExist = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
227         assertNull(nodesNotExist);
228         createTopology(LogicalDatastoreType.OPERATIONAL);
229         final List<Node> nodes = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
230         assertNotNull(nodes);
231         assertEquals(1, nodes.size());
232     }
233
234     private void createTopology(LogicalDatastoreType dataStoreType) 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, NetconfNodeConnectionStatus.ConnectionStatus cs,
249                                 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 = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
259
260         final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
261                 setAvailableCapabilities(avCaps).build();
262         final NodeId nodeId = new NodeId(nodeIdent);
263         final NodeKey nk = new NodeKey(nodeId);
264         final NodeBuilder nb = new NodeBuilder();
265         nb.setKey(nk);
266         nb.setNodeId(nodeId);
267         nb.addAugmentation(NetconfNode.class, nn);
268         return nb.build();
269     }
270
271     private void assertBaseNodeAttributes(Map mapNode) {
272
273         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
274         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
275         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
276         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
277
278         assertEquals(NODE_ID, mapNode.get(NetconfConsoleConstants.NETCONF_ID));
279         assertEquals(IP, mapNode.get(NetconfConsoleConstants.NETCONF_IP));
280         assertEquals(String.valueOf(PORT), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
281         assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS));
282     }
283
284     private void assertBaseNodeAttributesImmutableList(Map mapNode) {
285         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
286         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
287         assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
288         assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
289
290         assertEquals(ImmutableList.of(NODE_ID), mapNode.get(NetconfConsoleConstants.NETCONF_ID));
291         assertEquals(ImmutableList.of(IP), mapNode.get(NetconfConsoleConstants.NETCONF_IP));
292         assertEquals(ImmutableList.of(String.valueOf(PORT)), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
293         assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
294     }
295
296     private List<InputStream> getYangSchemas() {
297         final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
298                 "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
299                 "/schemas/netconf-node-topology.yang");
300
301         final List<InputStream> schemas = new ArrayList<>();
302         for (String schemaPath : schemaPaths) {
303             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
304             schemas.add(resourceAsStream);
305         }
306         return schemas;
307     }
308
309     private static SchemaContext parseYangStreams(final List<InputStream> streams) {
310         CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
311                 .newBuild();
312         final SchemaContext schemaContext;
313         try {
314             schemaContext = reactor.buildEffective(streams);
315         } catch (ReactorException e) {
316             throw new RuntimeException("Unable to build schema context from " + streams, e);
317         }
318         return schemaContext;
319     }
320
321     private SchemaService createSchemaService() {
322         return new SchemaService() {
323
324             @Override
325             public void addModule(Module module) {
326             }
327
328             @Override
329             public void removeModule(Module module) {
330
331             }
332
333             @Override
334             public SchemaContext getSessionContext() {
335                 return schemaContext;
336             }
337
338             @Override
339             public SchemaContext getGlobalContext() {
340                 return schemaContext;
341             }
342
343             @Override
344             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
345                 listener.onGlobalContextUpdated(getGlobalContext());
346                 return new ListenerRegistration<SchemaContextListener>() {
347                     @Override
348                     public void close() {
349
350                     }
351
352                     @Override
353                     public SchemaContextListener getInstance() {
354                         return listener;
355                     }
356                 };
357             }
358         };
359     }
360 }