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