2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.netconf.console.impl;
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;
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;
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.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.parser.spi.meta.ReactorException;
77 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
78 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
80 public class NetconfCommandsImplTest {
82 private static final String NODE_ID = "NodeID";
83 private static final String IP = "192.168.1.1";
84 private static final int PORT = 1234;
85 private static final NetconfNodeConnectionStatus.ConnectionStatus CONN_STATUS =
86 NetconfNodeConnectionStatus.ConnectionStatus.Connected;
87 private static final String CAP_PREFIX = "prefix";
89 private DataBroker dataBroker;
90 private SchemaContext schemaContext;
91 private NetconfCommandsImpl netconfCommands;
94 public void setUp() throws TransactionCommitFailedException, TimeoutException, InterruptedException {
95 schemaContext = parseYangStreams(getYangSchemas());
96 schemaContext.getModules();
97 final SchemaService schemaService = createSchemaService();
99 final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
100 final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
102 final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
103 datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
104 datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
106 final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
107 16, 16, "CommitFutures");
109 final ConcurrentDOMDataBroker cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
111 final ClassPool pool = ClassPool.getDefault();
112 final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
113 final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
114 final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
115 codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
117 final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
118 final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
119 bindingToNormalized.onGlobalContextUpdated(schemaContext);
120 dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
122 final MountPointService mountPointService = mock(MountPointService.class);
123 netconfCommands = new NetconfCommandsImpl(dataBroker, mountPointService);
127 public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
128 createTopology(LogicalDatastoreType.OPERATIONAL);
130 final Map map = netconfCommands.listDevices();
131 map.containsKey(NetconfConsoleConstants.NETCONF_ID);
132 assertTrue(map.containsKey(NODE_ID));
134 final Map mapNode = (Map) map.get(NODE_ID);
135 assertBaseNodeAttributes(mapNode);
139 public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
140 createTopology(LogicalDatastoreType.OPERATIONAL);
142 final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
143 mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
144 assertTrue(mapCorrect.containsKey(NODE_ID));
146 assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
148 final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
149 assertFalse(mapWrongPort.containsKey(NODE_ID));
151 final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
152 assertFalse(mapWrongIP.containsKey(NODE_ID));
154 final Map mapId = netconfCommands.showDevice(NODE_ID);
155 assertTrue(mapId.containsKey(NODE_ID));
156 assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
160 public void testConnectDisconnectDevice() throws InterruptedException, TimeoutException, TransactionCommitFailedException {
161 final NetconfNode netconfNode = new NetconfNodeBuilder().setPort(new PortNumber(7777)).
162 setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
164 createTopology(LogicalDatastoreType.CONFIGURATION);
165 netconfCommands.connectDevice(netconfNode, "netconf-ID");
166 NetconfConsoleUtils.waitForUpdate("10.10.1.1");
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());
173 final Optional<Node> storedNode = nodes.stream().filter(node ->
174 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
176 assertTrue(storedNode.isPresent());
178 NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
179 assertEquals(7777, storedNetconfNode.getPort().getValue().longValue());
180 assertEquals("10.10.1.1", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
182 netconfCommands.disconnectDevice("netconf-ID");
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());
189 final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
190 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
192 assertFalse(storedNodeDeleted.isPresent());
196 public void testUpdateDevice() throws TimeoutException, TransactionCommitFailedException {
197 //We need both, read data from OPERATIONAL DS and update data in CONFIGURATIONAL DS
198 createTopology(LogicalDatastoreType.OPERATIONAL);
199 createTopology(LogicalDatastoreType.CONFIGURATION);
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");
205 netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
206 NetconfConsoleUtils.waitForUpdate("7.7.7.7");
208 final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
209 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
210 final List<Node> nodes = topology.getNode();
211 assertEquals(1, nodes.size());
213 final Optional<Node> storedNode = nodes.stream().filter(node ->
214 node.getKey().getNodeId().getValue().equals(NODE_ID)).findFirst();
215 assertTrue(storedNode.isPresent());
217 NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
218 assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
222 public void testNetconfNodeFromIp() throws TimeoutException, TransactionCommitFailedException {
223 final List<Node> nodesNotExist = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
224 assertNull(nodesNotExist);
225 createTopology(LogicalDatastoreType.OPERATIONAL);
226 final List<Node> nodes = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
227 assertNotNull(nodes);
228 assertEquals(1, nodes.size());
231 private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
232 final List<Node> nodes = new ArrayList<>();
233 final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
236 final Topology topology = new TopologyBuilder().
237 setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
238 setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
240 final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
241 writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
242 writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
245 private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
246 String notificationCapabilityPrefix) {
248 final Host host = HostBuilder.getDefaultInstance(ip);
249 final PortNumber port = new PortNumber(portNumber);
251 final List<String> avCapList = new ArrayList<>();
252 avCapList.add(notificationCapabilityPrefix + "_availableCapabilityString1");
253 final AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
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();
261 nb.setNodeId(nodeId);
262 nb.addAugmentation(NetconfNode.class, nn);
266 private void assertBaseNodeAttributes(Map mapNode) {
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));
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));
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));
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));
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", "/schemas/netconf-node-topology.yang");
294 final List<InputStream> schemas = new ArrayList<>();
295 for (String schemaPath : schemaPaths) {
296 final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
297 schemas.add(resourceAsStream);
302 private static SchemaContext parseYangStreams(final List<InputStream> streams) {
303 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
305 final SchemaContext schemaContext;
307 schemaContext = reactor.buildEffective(streams);
308 } catch (ReactorException e) {
309 throw new RuntimeException("Unable to build schema context from " + streams, e);
311 return schemaContext;
314 private SchemaService createSchemaService() {
315 return new SchemaService() {
318 public void addModule(Module module) {
322 public void removeModule(Module module) {
327 public SchemaContext getSessionContext() {
328 return schemaContext;
332 public SchemaContext getGlobalContext() {
333 return schemaContext;
337 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
338 listener.onGlobalContextUpdated(getGlobalContext());
339 return new ListenerRegistration<SchemaContextListener>() {
341 public void close() {
346 public SchemaContextListener getInstance() {