Add explicit getExtensions()
[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.ClassToInstanceMap;
18 import com.google.common.collect.ImmutableClassToInstanceMap;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import java.util.ArrayList;
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.ExecutionException;
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.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.dom.api.DOMDataBroker;
39 import org.opendaylight.controller.md.sal.dom.broker.impl.SerializedDOMDataBroker;
40 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
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.mdsal.dom.api.DOMSchemaService;
50 import org.opendaylight.mdsal.dom.api.DOMSchemaServiceExtension;
51 import org.opendaylight.netconf.console.utils.NetconfConsoleConstants;
52 import org.opendaylight.netconf.console.utils.NetconfConsoleUtils;
53 import org.opendaylight.netconf.console.utils.NetconfIidFactory;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.HostBuilder;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilities;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.AvailableCapabilitiesBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
66 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
67 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
68 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
69 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
70 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
71 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
72 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
73 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
74 import org.opendaylight.yangtools.concepts.ListenerRegistration;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
77 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
78
79 public class NetconfCommandsImplTest {
80
81     private static final String NODE_ID = "NodeID";
82     private static final String IP = "192.168.1.1";
83     private static final int PORT = 1234;
84     private static final NetconfNodeConnectionStatus.ConnectionStatus CONN_STATUS =
85             NetconfNodeConnectionStatus.ConnectionStatus.Connected;
86     private static final String CAP_PREFIX = "prefix";
87
88     private DataBroker dataBroker;
89     private SchemaContext schemaContext;
90     private NetconfCommandsImpl netconfCommands;
91
92     @Before
93     public void setUp() throws Exception {
94         schemaContext = YangParserTestUtils.parseYangResources(NetconfCommandsImplTest.class,
95             "/schemas/network-topology@2013-10-21.yang", "/schemas/ietf-inet-types@2013-07-15.yang",
96             "/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang");
97         schemaContext.getModules();
98         final DOMSchemaService schemaService = createSchemaService();
99
100         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
101         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
102
103         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
104         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
105         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
106
107         final DOMDataBroker domDataBroker =
108                 new SerializedDOMDataBroker(datastores, MoreExecutors.newDirectExecutorService());
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(domDataBroker, bindingToNormalized);
122
123         netconfCommands = new NetconfCommandsImpl(dataBroker);
124     }
125
126     @Test
127     public void testListDevice() throws TimeoutException, InterruptedException, ExecutionException {
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, InterruptedException, ExecutionException {
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() throws InterruptedException, TimeoutException, ExecutionException {
161         final NetconfNode netconfNode = new NetconfNodeBuilder()
162                 .setPort(new PortNumber(7777)).setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
163
164         createTopology(LogicalDatastoreType.CONFIGURATION);
165         netconfCommands.connectDevice(netconfNode, "netconf-ID");
166         NetconfConsoleUtils.waitForUpdate("10.10.1.1");
167
168         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
169                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
170         final List<Node> nodes = topology.getNode();
171         assertEquals(2, nodes.size());
172
173         final Optional<Node> storedNode = nodes.stream().filter(node ->
174                 node.key().getNodeId().getValue().equals("netconf-ID")).findFirst();
175
176         assertTrue(storedNode.isPresent());
177
178         NetconfNode storedNetconfNode = storedNode.get().augmentation(NetconfNode.class);
179         assertEquals(7777, storedNetconfNode.getPort().getValue().longValue());
180         assertEquals("10.10.1.1", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
181
182         netconfCommands.disconnectDevice("netconf-ID");
183
184         final Topology topologyDeleted = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
185                 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
186         final List<Node> nodesDeleted = topologyDeleted.getNode();
187         assertEquals(1, nodesDeleted.size());
188
189         final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
190                 node.key().getNodeId().getValue().equals("netconf-ID")).findFirst();
191
192         assertFalse(storedNodeDeleted.isPresent());
193     }
194
195     @Test
196     public void testUpdateDevice() throws TimeoutException, InterruptedException, ExecutionException {
197         //We need both, read data from OPERATIONAL DS and update data in CONFIGURATIONAL DS
198         createTopology(LogicalDatastoreType.OPERATIONAL);
199         createTopology(LogicalDatastoreType.CONFIGURATION);
200
201         final Map<String, String> update = new HashMap<>();
202         update.put(NetconfConsoleConstants.NETCONF_IP, "7.7.7.7");
203         update.put(NetconfConsoleConstants.TCP_ONLY, "true");
204         update.put(NetconfConsoleConstants.SCHEMALESS, "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.key().getNodeId().getValue().equals(NODE_ID)).findFirst();
216         assertTrue(storedNode.isPresent());
217
218         NetconfNode storedNetconfNode = storedNode.get().augmentation(NetconfNode.class);
219         assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
220     }
221
222     @Test
223     public void testNetconfNodeFromIp() throws TimeoutException, InterruptedException, ExecutionException {
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(final LogicalDatastoreType dataStoreType)
233             throws TimeoutException, InterruptedException, ExecutionException {
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                 .withKey(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.commit().get(2, TimeUnit.SECONDS);
245     }
246
247     private static Node getNetconfNode(final String nodeIdent, final String ip, final int portNumber,
248             final NetconfNodeConnectionStatus.ConnectionStatus cs, final 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 =
258                 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.withKey(nk);
266         nb.setNodeId(nodeId);
267         nb.addAugmentation(NetconfNode.class, nn);
268         return nb.build();
269     }
270
271     private static void assertBaseNodeAttributes(final Map<?, ?> mapNode) {
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 static void assertBaseNodeAttributesImmutableList(final 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 DOMSchemaService createSchemaService() {
296         return new DOMSchemaService() {
297
298             @Override
299             public SchemaContext getSessionContext() {
300                 return schemaContext;
301             }
302
303             @Override
304             public SchemaContext getGlobalContext() {
305                 return schemaContext;
306             }
307
308             @Override
309             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
310                     final SchemaContextListener listener) {
311                 listener.onGlobalContextUpdated(getGlobalContext());
312                 return new AbstractListenerRegistration<SchemaContextListener>(listener) {
313
314                     @Override
315                     protected void removeRegistration() {
316                         // No-op
317                     }
318                 };
319             }
320
321             @Override
322             public ClassToInstanceMap<DOMSchemaServiceExtension> getExtensions() {
323                 return ImmutableClassToInstanceMap.of();
324             }
325         };
326     }
327 }