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