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.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;
82 public class NetconfCommandsImplTest {
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";
91 private DataBroker dataBroker;
92 private SchemaContext schemaContext;
93 private NetconfCommandsImpl netconfCommands;
96 public void setUp() throws TransactionCommitFailedException, TimeoutException, InterruptedException {
97 schemaContext = parseYangStreams(getYangSchemas());
98 schemaContext.getModules();
99 final SchemaService schemaService = createSchemaService();
101 final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
102 final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
104 final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
105 datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
106 datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
108 final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
109 16, 16, "CommitFutures");
111 final ConcurrentDOMDataBroker cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
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));
119 final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
120 final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
121 bindingToNormalized.onGlobalContextUpdated(schemaContext);
122 dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
124 netconfCommands = new NetconfCommandsImpl(dataBroker);
128 public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
129 createTopology(LogicalDatastoreType.OPERATIONAL);
131 final Map map = netconfCommands.listDevices();
132 map.containsKey(NetconfConsoleConstants.NETCONF_ID);
133 assertTrue(map.containsKey(NODE_ID));
135 final Map mapNode = (Map) map.get(NODE_ID);
136 assertBaseNodeAttributes(mapNode);
140 public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
141 createTopology(LogicalDatastoreType.OPERATIONAL);
143 final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
144 mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
145 assertTrue(mapCorrect.containsKey(NODE_ID));
147 assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
149 final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
150 assertFalse(mapWrongPort.containsKey(NODE_ID));
152 final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
153 assertFalse(mapWrongIP.containsKey(NODE_ID));
155 final Map mapId = netconfCommands.showDevice(NODE_ID);
156 assertTrue(mapId.containsKey(NODE_ID));
157 assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
161 public void testConnectDisconnectDevice() throws InterruptedException, TimeoutException, TransactionCommitFailedException {
162 final NetconfNode netconfNode = new NetconfNodeBuilder().setPort(new PortNumber(7777)).
163 setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
165 createTopology(LogicalDatastoreType.CONFIGURATION);
166 netconfCommands.connectDevice(netconfNode, "netconf-ID");
167 NetconfConsoleUtils.waitForUpdate("10.10.1.1");
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());
174 final Optional<Node> storedNode = nodes.stream().filter(node ->
175 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
177 assertTrue(storedNode.isPresent());
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());
183 netconfCommands.disconnectDevice("netconf-ID");
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());
190 final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
191 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
193 assertFalse(storedNodeDeleted.isPresent());
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);
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");
206 netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
207 NetconfConsoleUtils.waitForUpdate("7.7.7.7");
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());
214 final Optional<Node> storedNode = nodes.stream().filter(node ->
215 node.getKey().getNodeId().getValue().equals(NODE_ID)).findFirst();
216 assertTrue(storedNode.isPresent());
218 NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
219 assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
223 public void testNetconfNodeFromIp() throws TimeoutException, TransactionCommitFailedException {
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());
232 private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
233 final List<Node> nodes = new ArrayList<>();
234 final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
237 final Topology topology = new TopologyBuilder().
238 setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
239 setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
241 final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
242 writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
243 writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
246 private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
247 String notificationCapabilityPrefix) {
249 final Host host = HostBuilder.getDefaultInstance(ip);
250 final PortNumber port = new PortNumber(portNumber);
252 final List<AvailableCapability> avCapList = new ArrayList<>();
253 avCapList.add(new AvailableCapabilityBuilder()
254 .setCapabilityOrigin(AvailableCapability.CapabilityOrigin.UserDefined)
255 .setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
256 final AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
258 final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
259 setAvailableCapabilities(avCaps).build();
260 final NodeId nodeId = new NodeId(nodeIdent);
261 final NodeKey nk = new NodeKey(nodeId);
262 final NodeBuilder nb = new NodeBuilder();
264 nb.setNodeId(nodeId);
265 nb.addAugmentation(NetconfNode.class, nn);
269 private void assertBaseNodeAttributes(Map mapNode) {
271 assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
272 assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
273 assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
274 assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
276 assertEquals(NODE_ID, mapNode.get(NetconfConsoleConstants.NETCONF_ID));
277 assertEquals(IP, mapNode.get(NetconfConsoleConstants.NETCONF_IP));
278 assertEquals(String.valueOf(PORT), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
279 assertEquals(CONN_STATUS.name().toLowerCase(), mapNode.get(NetconfConsoleConstants.STATUS));
282 private void assertBaseNodeAttributesImmutableList(Map mapNode) {
283 assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_ID));
284 assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_IP));
285 assertTrue(mapNode.containsKey(NetconfConsoleConstants.NETCONF_PORT));
286 assertTrue(mapNode.containsKey(NetconfConsoleConstants.STATUS));
288 assertEquals(ImmutableList.of(NODE_ID), mapNode.get(NetconfConsoleConstants.NETCONF_ID));
289 assertEquals(ImmutableList.of(IP), mapNode.get(NetconfConsoleConstants.NETCONF_IP));
290 assertEquals(ImmutableList.of(String.valueOf(PORT)), mapNode.get(NetconfConsoleConstants.NETCONF_PORT));
291 assertEquals(ImmutableList.of(CONN_STATUS.name()), mapNode.get(NetconfConsoleConstants.STATUS));
294 private List<InputStream> getYangSchemas() {
295 final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
296 "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
297 "/schemas/netconf-node-topology.yang");
299 final List<InputStream> schemas = new ArrayList<>();
300 for (String schemaPath : schemaPaths) {
301 final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
302 schemas.add(resourceAsStream);
307 private static SchemaContext parseYangStreams(final List<InputStream> streams) {
308 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
310 final SchemaContext schemaContext;
312 schemaContext = reactor.buildEffective(streams);
313 } catch (ReactorException e) {
314 throw new RuntimeException("Unable to build schema context from " + streams, e);
316 return schemaContext;
319 private SchemaService createSchemaService() {
320 return new SchemaService() {
323 public void addModule(Module module) {
327 public void removeModule(Module module) {
332 public SchemaContext getSessionContext() {
333 return schemaContext;
337 public SchemaContext getGlobalContext() {
338 return schemaContext;
342 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
343 listener.onGlobalContextUpdated(getGlobalContext());
344 return new ListenerRegistration<SchemaContextListener>() {
346 public void close() {
351 public SchemaContextListener getInstance() {