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 final MountPointService mountPointService = mock(MountPointService.class);
125 netconfCommands = new NetconfCommandsImpl(dataBroker, mountPointService);
129 public void testListDevice() throws TimeoutException, TransactionCommitFailedException {
130 createTopology(LogicalDatastoreType.OPERATIONAL);
132 final Map map = netconfCommands.listDevices();
133 map.containsKey(NetconfConsoleConstants.NETCONF_ID);
134 assertTrue(map.containsKey(NODE_ID));
136 final Map mapNode = (Map) map.get(NODE_ID);
137 assertBaseNodeAttributes(mapNode);
141 public void testShowDevice() throws TimeoutException, TransactionCommitFailedException {
142 createTopology(LogicalDatastoreType.OPERATIONAL);
144 final Map mapCorrect = netconfCommands.showDevice(IP, String.valueOf(PORT));
145 mapCorrect.containsKey(NetconfConsoleConstants.NETCONF_ID);
146 assertTrue(mapCorrect.containsKey(NODE_ID));
148 assertBaseNodeAttributesImmutableList((Map) mapCorrect.get(NODE_ID));
150 final Map mapWrongPort = netconfCommands.showDevice(IP, "1");
151 assertFalse(mapWrongPort.containsKey(NODE_ID));
153 final Map mapWrongIP = netconfCommands.showDevice("1.1.1.1", String.valueOf(PORT));
154 assertFalse(mapWrongIP.containsKey(NODE_ID));
156 final Map mapId = netconfCommands.showDevice(NODE_ID);
157 assertTrue(mapId.containsKey(NODE_ID));
158 assertBaseNodeAttributesImmutableList((Map) mapId.get(NODE_ID));
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();
166 createTopology(LogicalDatastoreType.CONFIGURATION);
167 netconfCommands.connectDevice(netconfNode, "netconf-ID");
168 NetconfConsoleUtils.waitForUpdate("10.10.1.1");
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());
175 final Optional<Node> storedNode = nodes.stream().filter(node ->
176 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
178 assertTrue(storedNode.isPresent());
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());
184 netconfCommands.disconnectDevice("netconf-ID");
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());
191 final Optional<Node> storedNodeDeleted = nodesDeleted.stream().filter(node ->
192 node.getKey().getNodeId().getValue().equals("netconf-ID")).findFirst();
194 assertFalse(storedNodeDeleted.isPresent());
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);
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");
207 netconfCommands.updateDevice(NODE_ID, "admin", "admin", update);
208 NetconfConsoleUtils.waitForUpdate("7.7.7.7");
210 final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.CONFIGURATION,
211 NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
212 final List<Node> nodes = topology.getNode();
213 assertEquals(1, nodes.size());
215 final Optional<Node> storedNode = nodes.stream().filter(node ->
216 node.getKey().getNodeId().getValue().equals(NODE_ID)).findFirst();
217 assertTrue(storedNode.isPresent());
219 NetconfNode storedNetconfNode = storedNode.get().getAugmentation(NetconfNode.class);
220 assertEquals("7.7.7.7", storedNetconfNode.getHost().getIpAddress().getIpv4Address().getValue());
224 public void testNetconfNodeFromIp() throws TimeoutException, TransactionCommitFailedException {
225 final List<Node> nodesNotExist = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
226 assertNull(nodesNotExist);
227 createTopology(LogicalDatastoreType.OPERATIONAL);
228 final List<Node> nodes = NetconfConsoleUtils.getNetconfNodeFromIp(IP, dataBroker);
229 assertNotNull(nodes);
230 assertEquals(1, nodes.size());
233 private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
234 final List<Node> nodes = new ArrayList<>();
235 final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
238 final Topology topology = new TopologyBuilder().
239 setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
240 setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
242 final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
243 writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
244 writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
247 private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
248 String notificationCapabilityPrefix) {
250 final Host host = HostBuilder.getDefaultInstance(ip);
251 final PortNumber port = new PortNumber(portNumber);
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 = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
259 final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
260 setAvailableCapabilities(avCaps).build();
261 final NodeId nodeId = new NodeId(nodeIdent);
262 final NodeKey nk = new NodeKey(nodeId);
263 final NodeBuilder nb = new NodeBuilder();
265 nb.setNodeId(nodeId);
266 nb.addAugmentation(NetconfNode.class, nn);
270 private void assertBaseNodeAttributes(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));
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));
283 private void assertBaseNodeAttributesImmutableList(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));
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));
295 private List<InputStream> getYangSchemas() {
296 final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
297 "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
298 "/schemas/netconf-node-topology.yang");
300 final List<InputStream> schemas = new ArrayList<>();
301 for (String schemaPath : schemaPaths) {
302 final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
303 schemas.add(resourceAsStream);
308 private static SchemaContext parseYangStreams(final List<InputStream> streams) {
309 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
311 final SchemaContext schemaContext;
313 schemaContext = reactor.buildEffective(streams);
314 } catch (ReactorException e) {
315 throw new RuntimeException("Unable to build schema context from " + streams, e);
317 return schemaContext;
320 private SchemaService createSchemaService() {
321 return new SchemaService() {
324 public void addModule(Module module) {
328 public void removeModule(Module module) {
333 public SchemaContext getSessionContext() {
334 return schemaContext;
338 public SchemaContext getGlobalContext() {
339 return schemaContext;
343 public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
344 listener.onGlobalContextUpdated(getGlobalContext());
345 return new ListenerRegistration<SchemaContextListener>() {
347 public void close() {
352 public SchemaContextListener getInstance() {