2 * Copyright (c) 2016 Brocade Communication Systems and others. All rights reserved.
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
8 package org.opendaylight.netconf.callhome.mount;
10 import com.google.common.util.concurrent.FutureCallback;
11 import com.google.common.util.concurrent.MoreExecutors;
12 import java.io.IOException;
13 import java.security.GeneralSecurityException;
14 import java.security.PublicKey;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.Optional;
18 import java.util.concurrent.ExecutionException;
19 import org.opendaylight.mdsal.binding.api.DataBroker;
20 import org.opendaylight.mdsal.binding.api.DataObjectModification;
21 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
22 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
23 import org.opendaylight.mdsal.binding.api.DataTreeModification;
24 import org.opendaylight.mdsal.binding.api.ReadTransaction;
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.callhome.protocol.AuthorizedKeysDecoder;
29 import org.opendaylight.netconf.callhome.protocol.StatusRecorder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.callhome.device.status.rev170112.Device1;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.callhome.device.status.rev170112.Device1.DeviceStatus;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.callhome.device.status.rev170112.Device1Builder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.network.topology.topology.topology.types.TopologyNetconf;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.NetconfCallhomeServer;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.AllowedDevices;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.Device;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.DeviceBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.DeviceKey;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.Ssh;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.SshBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.ssh.SshClientParamsBuilder;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
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.TopologyId;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
49 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
50 import org.opendaylight.yangtools.concepts.ListenerRegistration;
51 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 final class CallhomeStatusReporter implements DataTreeChangeListener<Node>, StatusRecorder, AutoCloseable {
56 private static final InstanceIdentifier<Topology> NETCONF_TOPO_IID =
57 InstanceIdentifier.create(NetworkTopology.class).child(Topology.class,
58 new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
60 private static final Logger LOG = LoggerFactory.getLogger(CallhomeStatusReporter.class);
62 private final DataBroker dataBroker;
63 private final ListenerRegistration<CallhomeStatusReporter> reg;
65 CallhomeStatusReporter(final DataBroker broker) {
67 reg = dataBroker.registerDataTreeChangeListener(DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL,
68 NETCONF_TOPO_IID.child(Node.class)), this);
72 public void onDataTreeChanged(final Collection<DataTreeModification<Node>> changes) {
73 for (DataTreeModification<Node> change : changes) {
74 final DataObjectModification<Node> rootNode = change.getRootNode();
75 final InstanceIdentifier<Node> identifier = change.getRootPath().getRootIdentifier();
76 switch (rootNode.getModificationType()) {
78 case SUBTREE_MODIFIED:
79 if (isNetconfNode(rootNode.getDataAfter())) {
80 NodeId nodeId = getNodeId(identifier);
82 NetconfNode nnode = rootNode.getDataAfter().augmentation(NetconfNode.class);
83 handledNetconfNode(nodeId, nnode);
88 if (isNetconfNode(rootNode.getDataBefore())) {
89 final NodeId nodeId = getNodeId(identifier);
91 handleDisconnectedNetconfNode(nodeId);
101 private static boolean isNetconfNode(final Node node) {
102 return node.augmentation(NetconfNode.class) != null;
105 private static NodeId getNodeId(final InstanceIdentifier<?> path) {
106 NodeKey key = path.firstKeyOf(Node.class);
107 return key != null ? key.getNodeId() : null;
110 private void handledNetconfNode(final NodeId nodeId, final NetconfNode nnode) {
111 switch (nnode.getConnectionStatus()) {
113 handleConnectedNetconfNode(nodeId);
117 case UnableToConnect: {
118 handleUnableToConnectNetconfNode(nodeId);
124 private void handleConnectedNetconfNode(final NodeId nodeId) {
125 // Fully connected, all services for remote device are
126 // available from the MountPointService.
127 LOG.debug("NETCONF Node: {} is fully connected", nodeId.getValue());
129 Device opDev = readAndGetDevice(nodeId);
131 LOG.warn("No corresponding callhome device found - exiting.");
133 Device modifiedDevice = withConnectedStatus(opDev);
134 if (modifiedDevice == null) {
137 LOG.info("Setting successful status for callhome device id:{}.", nodeId);
138 writeDevice(nodeId, modifiedDevice);
142 private void handleDisconnectedNetconfNode(final NodeId nodeId) {
143 LOG.debug("NETCONF Node: {} disconnected", nodeId.getValue());
145 Device opDev = readAndGetDevice(nodeId);
147 LOG.warn("No corresponding callhome device found - exiting.");
149 Device modifiedDevice = withDisconnectedStatus(opDev);
150 if (modifiedDevice == null) {
153 LOG.info("Setting disconnected status for callhome device id:{}.", nodeId);
154 writeDevice(nodeId, modifiedDevice);
158 private void handleUnableToConnectNetconfNode(final NodeId nodeId) {
159 // The maximum configured number of reconnect attempts
160 // have been reached. No more reconnects will be
161 // attempted by the Netconf Connector.
162 LOG.debug("NETCONF Node: {} connection failed", nodeId.getValue());
164 Device opDev = readAndGetDevice(nodeId);
166 LOG.warn("No corresponding callhome device found - exiting.");
168 Device modifiedDevice = withFailedStatus(opDev);
169 if (modifiedDevice == null) {
172 LOG.info("Setting failed status for callhome device id:{}.", nodeId);
173 writeDevice(nodeId, modifiedDevice);
177 void asForceListedDevice(final String id, final PublicKey serverKey) {
178 NodeId nid = new NodeId(id);
179 Device device = newDevice(id, serverKey, Device1.DeviceStatus.DISCONNECTED);
180 writeDevice(nid, device);
183 void asUnlistedDevice(final String id, final PublicKey serverKey) {
184 NodeId nid = new NodeId(id);
185 Device device = newDevice(id, serverKey, Device1.DeviceStatus.FAILEDNOTALLOWED);
186 writeDevice(nid, device);
189 private static Device newDevice(final String id, final PublicKey serverKey, final Device1.DeviceStatus status) {
190 // used only for netconf devices that are connected via SSH transport and global credentials
191 String sshEncodedKey = serverKey.toString();
193 sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
194 } catch (IOException e) {
195 LOG.warn("Unable to encode public key to ssh format.", e);
197 return new DeviceBuilder()
199 .withKey(new DeviceKey(id))
200 .setTransport(new SshBuilder()
201 .setSshClientParams(new SshClientParamsBuilder().setHostKey(sshEncodedKey).build())
203 .addAugmentation(new Device1Builder().setDeviceStatus(status).build())
207 private Device readAndGetDevice(final NodeId nodeId) {
208 return readDevice(nodeId).orElse(null);
211 private Optional<Device> readDevice(final NodeId nodeId) {
212 try (ReadTransaction opTx = dataBroker.newReadOnlyTransaction()) {
213 InstanceIdentifier<Device> deviceIID = buildDeviceInstanceIdentifier(nodeId);
214 return opTx.read(LogicalDatastoreType.OPERATIONAL, deviceIID).get();
215 } catch (InterruptedException | ExecutionException e) {
216 return Optional.empty();
220 private void writeDevice(final NodeId nodeId, final Device modifiedDevice) {
221 WriteTransaction opTx = dataBroker.newWriteOnlyTransaction();
222 opTx.merge(LogicalDatastoreType.OPERATIONAL, buildDeviceInstanceIdentifier(nodeId), modifiedDevice);
223 commit(opTx, modifiedDevice.key());
226 private static InstanceIdentifier<Device> buildDeviceInstanceIdentifier(final NodeId nodeId) {
227 return InstanceIdentifier.create(NetconfCallhomeServer.class)
228 .child(AllowedDevices.class)
229 .child(Device.class, new DeviceKey(nodeId.getValue()));
232 private static Device withConnectedStatus(final Device opDev) {
233 return deviceWithStatus(opDev, Device1.DeviceStatus.CONNECTED);
236 private static Device withFailedStatus(final Device opDev) {
237 return deviceWithStatus(opDev, DeviceStatus.FAILED);
240 private static Device withDisconnectedStatus(final Device opDev) {
241 return deviceWithStatus(opDev, DeviceStatus.DISCONNECTED);
244 private static Device withFailedAuthStatus(final Device opDev) {
245 return deviceWithStatus(opDev, DeviceStatus.FAILEDAUTHFAILURE);
248 private static Device deviceWithStatus(final Device opDev, final DeviceStatus status) {
249 final DeviceBuilder deviceBuilder = new DeviceBuilder()
250 .setUniqueId(opDev.getUniqueId())
251 .addAugmentation(new Device1Builder().setDeviceStatus(status).build());
252 if (opDev.getTransport() != null) {
253 deviceBuilder.setTransport(opDev.getTransport());
255 deviceBuilder.setSshHostKey(opDev.getSshHostKey());
257 return deviceBuilder.build();
260 private void setDeviceStatus(final Device device) {
261 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
262 InstanceIdentifier<Device> deviceIId = InstanceIdentifier.create(NetconfCallhomeServer.class)
263 .child(AllowedDevices.class)
264 .child(Device.class, device.key());
266 tx.merge(LogicalDatastoreType.OPERATIONAL, deviceIId, device);
267 commit(tx, device.key());
270 private static void commit(final WriteTransaction tx, final DeviceKey device) {
271 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
273 public void onSuccess(final CommitInfo result) {
274 LOG.debug("Device {} committed", device);
278 public void onFailure(final Throwable cause) {
279 LOG.warn("Failed to commit device {}", device, cause);
281 }, MoreExecutors.directExecutor());
284 private AllowedDevices getDevices() {
285 try (ReadTransaction rxTransaction = dataBroker.newReadOnlyTransaction()) {
286 return rxTransaction.read(LogicalDatastoreType.OPERATIONAL, IetfZeroTouchCallHomeServerProvider.ALL_DEVICES)
288 } catch (ExecutionException | InterruptedException e) {
289 LOG.error("Error trying to read the whitelist devices", e);
294 private Collection<Device> getDevicesAsList() {
295 AllowedDevices devices = getDevices();
296 return devices == null ? Collections.emptyList() : devices.nonnullDevice().values();
300 public void reportFailedAuth(final PublicKey sshKey) {
301 AuthorizedKeysDecoder decoder = new AuthorizedKeysDecoder();
303 for (final Device device : getDevicesAsList()) {
304 final String keyString;
305 if (device.getTransport() instanceof Ssh ssh) {
306 keyString = ssh.getSshClientParams().getHostKey();
308 keyString = device.getSshHostKey();
310 if (keyString == null) {
311 LOG.info("Whitelist device {} does not have a host key, skipping it", device.getUniqueId());
316 PublicKey pubKey = decoder.decodePublicKey(keyString);
317 if (sshKey.getAlgorithm().equals(pubKey.getAlgorithm()) && sshKey.equals(pubKey)) {
318 Device failedDevice = withFailedAuthStatus(device);
319 if (failedDevice == null) {
322 LOG.info("Setting auth failed status for callhome device id:{}.", failedDevice.getUniqueId());
323 setDeviceStatus(failedDevice);
326 } catch (GeneralSecurityException e) {
327 LOG.error("Failed decoding a device key with host key: {}", keyString, e);
332 LOG.error("No match found for the failed auth device (should have been filtered by whitelist). Key: {}",
337 public void close() {