Merge "Bug 5912 - Restconf draft11 - utils"
[netconf.git] / netconf / netconf-console / src / main / java / org / opendaylight / netconf / console / impl / NetconfCommandsImpl.java
1 /*
2  * Copyright (c) 2016 Inocybe Technologies 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 com.google.common.base.Strings;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.UUID;
20 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
21 import org.opendaylight.controller.md.sal.binding.api.MountPoint;
22 import org.opendaylight.controller.md.sal.binding.api.MountPointService;
23 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.netconf.console.api.NetconfCommands;
27 import org.opendaylight.netconf.console.utils.NetconfConsoleConstants;
28 import org.opendaylight.netconf.console.utils.NetconfConsoleUtils;
29 import org.opendaylight.netconf.console.utils.NetconfIidFactory;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.ModuleType;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.Modules;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.Module;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.ModuleKey;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.connector.netconf.rev150803.SalNetconfConnector;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
48 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
49 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class NetconfCommandsImpl implements NetconfCommands {
54
55     private static final Logger LOG = LoggerFactory.getLogger(NetconfCommandsImpl.class);
56
57     private final DataBroker dataBroker;
58     private final MountPointService mountPointService;
59
60     public NetconfCommandsImpl(final DataBroker db, final MountPointService mountPointService) {
61         LOG.debug("NetconfConsoleProviderImpl initialized");
62         this.dataBroker = db;
63         this.mountPointService = mountPointService;
64     }
65
66     @Override
67     public Map<String, Map<String, String>> listDevices() {
68         final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
69         final Map<String, Map<String, String>> netconfNodes = new HashMap<>();
70         for (final Node node : topology.getNode()) {
71             final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
72             final Map<String, String> attributes = new HashMap<>();
73             attributes.put(NetconfConsoleConstants.NETCONF_ID, node.getNodeId().getValue());
74             attributes.put(NetconfConsoleConstants.NETCONF_IP, netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
75             attributes.put(NetconfConsoleConstants.NETCONF_PORT, netconfNode.getPort().getValue().toString());
76             attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name().toLowerCase());
77             netconfNodes.put(node.getNodeId().getValue(), attributes);
78         }
79         return netconfNodes;
80     }
81
82     @Override
83     public Map<String, Map<String, List<String>>> showDevice(final String deviceIp, final String devicePort) {
84         final Map<String, Map<String, List<String>>> device = new HashMap<>();
85         List<Node> nodeList = new ArrayList<>();
86         if (devicePort != null) {
87             nodeList.add(NetconfConsoleUtils.getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker));
88         } else {
89             nodeList = NetconfConsoleUtils.getNetconfNodeFromId(deviceIp, dataBroker);
90         }
91         if (nodeList != null) {
92             for (final Node node : nodeList) {
93                 final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
94                 final Map<String, List<String>> attributes = new HashMap<>();
95                 attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
96                 attributes.put(NetconfConsoleConstants.NETCONF_IP, ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
97                 attributes.put(NetconfConsoleConstants.NETCONF_PORT, ImmutableList.of(netconfNode.getPort().getValue().toString()));
98                 attributes.put(NetconfConsoleConstants.STATUS, ImmutableList.of(netconfNode.getConnectionStatus().name()));
99                 attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES, netconfNode.getAvailableCapabilities().getAvailableCapability());
100                 device.put(node.getNodeId().getValue(), attributes);
101             }
102         }
103         return device;
104     }
105
106     @Override
107     public Map<String, Map<String, List<String>>> showDevice(final String deviceId) {
108         final Map<String, Map<String, List<String>>> device = new HashMap<>();
109         final List<Node> nodeList = NetconfConsoleUtils.getNetconfNodeFromId(deviceId, dataBroker);
110         if (nodeList != null && nodeList.size() > 0) {
111             for (final Node node : nodeList) {
112                 final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
113                 final Map<String, List<String>> attributes = new HashMap<>();
114                 attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
115                 attributes.put(NetconfConsoleConstants.NETCONF_IP, ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
116                 attributes.put(NetconfConsoleConstants.NETCONF_PORT, ImmutableList.of(netconfNode.getPort().getValue().toString()));
117                 attributes.put(NetconfConsoleConstants.STATUS, ImmutableList.of(netconfNode.getConnectionStatus().name()));
118                 attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES, netconfNode.getAvailableCapabilities().getAvailableCapability());
119                 device.put(node.getNodeId().getValue(), attributes);
120             }
121         }
122         return device;
123     }
124
125     @Override
126     public void connectDevice(NetconfNode netconfNode, String netconfNodeId) {
127         final NodeId nodeId;
128         if (!Strings.isNullOrEmpty(netconfNodeId)) {
129             nodeId = new NodeId(netconfNodeId);
130         } else {
131             nodeId = new NodeId(UUID.randomUUID().toString().replace("-", ""));
132         }
133         final Node node = new NodeBuilder()
134                 .setKey(new NodeKey(nodeId))
135                 .setNodeId(nodeId)
136                 .addAugmentation(NetconfNode.class, netconfNode)
137                 .build();
138
139         final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
140         transaction.put(LogicalDatastoreType.CONFIGURATION, NetconfIidFactory.netconfNodeIid(nodeId.getValue()), node);
141
142         Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
143
144             @Override
145             public void onSuccess(Void result) {
146                 LOG.debug("NetconfNode={} created successfully", netconfNode);
147             }
148
149             @Override
150             public void onFailure(Throwable t) {
151                 LOG.error("Failed to created NetconfNode={}", netconfNode);
152                 throw new RuntimeException(t);
153             }
154         });
155     }
156
157     @Override
158     public boolean disconnectDevice(String netconfNodeId) {
159         boolean result = false;
160         final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
161         InstanceIdentifier<Node> iid = NetconfIidFactory.netconfNodeIid(netconfNodeId);
162         transaction.delete(LogicalDatastoreType.CONFIGURATION, iid);
163
164         try {
165             LOG.debug("Deleting netconf node: {}", netconfNodeId);
166             transaction.submit().checkedGet();
167             result = true;
168         } catch (final TransactionCommitFailedException e) {
169             LOG.error("Unable to remove node with Iid {}", iid, e);
170         }
171         return result;
172     }
173
174     @Override
175     public boolean disconnectDevice(final String deviceIp, final String devicePort) {
176         final String netconfNodeId = NetconfConsoleUtils.getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker).getNodeId().getValue();
177         return disconnectDevice(netconfNodeId);
178     }
179
180     @Override
181     public String updateDevice(final String netconfNodeId, String username, String password, Map<String, String> updated) {
182         final Node node = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.netconfNodeIid(netconfNodeId), dataBroker);
183
184         if (node != null && node.getAugmentation(NetconfNode.class) != null) {
185             final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
186
187             // Get NETCONF attributes to update if present else get their original values from NetconfNode instance
188             final String deviceIp = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_IP)) ?
189                     netconfNode.getHost().getIpAddress().getIpv4Address().getValue() : updated.get(NetconfConsoleConstants.NETCONF_IP);
190             final String devicePort = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_PORT)) ?
191                     netconfNode.getPort().getValue().toString() : updated.get(NetconfConsoleConstants.NETCONF_PORT);
192             final Boolean tcpOnly = (updated.get(NetconfConsoleConstants.TCP_ONLY).equals("true")) ? true : false;
193             final String newUsername = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.USERNAME)) ? updated.get(NetconfConsoleConstants.USERNAME) : username;
194             final String newPassword = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.PASSWORD)) ? updated.get(NetconfConsoleConstants.PASSWORD) : password;
195
196             final Credentials credentials = new LoginPasswordBuilder().setPassword(newPassword).setUsername(newUsername).build();
197             final NetconfNode updatedNetconfNode = new NetconfNodeBuilder()
198                     .setHost(new Host(new IpAddress(new Ipv4Address(deviceIp))))
199                     .setPort(new PortNumber(Integer.decode(devicePort)))
200                     .setTcpOnly(tcpOnly)
201                     .setCredentials(credentials)
202                     .build();
203
204             final Node updatedNode = new NodeBuilder()
205                     .setKey(node.getKey())
206                     .setNodeId(node.getNodeId())
207                     .addAugmentation(NetconfNode.class, updatedNetconfNode)
208                     .build();
209
210             final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
211             transaction.put(LogicalDatastoreType.CONFIGURATION, NetconfIidFactory.netconfNodeIid(updatedNode.getNodeId().getValue()), updatedNode);
212
213             Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
214
215                 @Override
216                 public void onSuccess(Void result) {
217                     LOG.debug("NetconfNode={} updated successfully", netconfNode);
218                 }
219
220                 @Override
221                 public void onFailure(Throwable t) {
222                     LOG.error("Failed to updated NetconfNode={}", netconfNode);
223                     throw new RuntimeException(t);
224                 }
225             });
226
227             return "NETCONF node: " + netconfNodeId + " updated successfully.";
228         } else {
229             return "NETCONF node: " + netconfNodeId + " does not exist to update";
230         }
231     }
232 }