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