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