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.List;
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.netconf.topology.spi.NetconfNodeUtils;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.NetconfCallhomeServer;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.AllowedDevices;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.allowed.devices.Device;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.allowed.devices.Device.DeviceStatus;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.allowed.devices.DeviceBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.allowed.devices.DeviceKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.allowed.devices.device.transport.Ssh;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.allowed.devices.device.transport.SshBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev230428.netconf.callhome.server.allowed.devices.device.transport.ssh.SshClientParamsBuilder;
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.Node;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
44 import org.opendaylight.yangtools.concepts.ListenerRegistration;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 final class CallhomeStatusReporter implements DataTreeChangeListener<Node>, StatusRecorder, AutoCloseable {
50 private static final Logger LOG = LoggerFactory.getLogger(CallhomeStatusReporter.class);
52 private final DataBroker dataBroker;
53 private final ListenerRegistration<CallhomeStatusReporter> reg;
55 CallhomeStatusReporter(final DataBroker broker) {
57 reg = dataBroker.registerDataTreeChangeListener(DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL,
58 NetconfNodeUtils.DEFAULT_TOPOLOGY_IID.child(Node.class)), this);
62 public void onDataTreeChanged(final Collection<DataTreeModification<Node>> changes) {
63 for (DataTreeModification<Node> change : changes) {
64 final DataObjectModification<Node> rootNode = change.getRootNode();
65 final InstanceIdentifier<Node> identifier = change.getRootPath().getRootIdentifier();
66 switch (rootNode.getModificationType()) {
68 case SUBTREE_MODIFIED:
69 if (isNetconfNode(rootNode.getDataAfter())) {
70 NodeId nodeId = getNodeId(identifier);
72 NetconfNode nnode = rootNode.getDataAfter().augmentation(NetconfNode.class);
73 handledNetconfNode(nodeId, nnode);
78 if (isNetconfNode(rootNode.getDataBefore())) {
79 final NodeId nodeId = getNodeId(identifier);
81 handleDisconnectedNetconfNode(nodeId);
91 private static boolean isNetconfNode(final Node node) {
92 return node.augmentation(NetconfNode.class) != null;
95 private static NodeId getNodeId(final InstanceIdentifier<?> path) {
96 NodeKey key = path.firstKeyOf(Node.class);
97 return key != null ? key.getNodeId() : null;
100 private void handledNetconfNode(final NodeId nodeId, final NetconfNode nnode) {
101 switch (nnode.getConnectionStatus()) {
103 handleConnectedNetconfNode(nodeId);
107 case UnableToConnect: {
108 handleUnableToConnectNetconfNode(nodeId);
114 private void handleConnectedNetconfNode(final NodeId nodeId) {
115 // Fully connected, all services for remote device are
116 // available from the MountPointService.
117 LOG.debug("NETCONF Node: {} is fully connected", nodeId.getValue());
119 Device opDev = readAndGetDevice(nodeId);
121 LOG.warn("No corresponding callhome device found - exiting.");
123 Device modifiedDevice = withConnectedStatus(opDev);
124 if (modifiedDevice == null) {
127 LOG.info("Setting successful status for callhome device id:{}.", nodeId);
128 writeDevice(nodeId, modifiedDevice);
132 private void handleDisconnectedNetconfNode(final NodeId nodeId) {
133 LOG.debug("NETCONF Node: {} disconnected", nodeId.getValue());
135 Device opDev = readAndGetDevice(nodeId);
137 LOG.warn("No corresponding callhome device found - exiting.");
139 Device modifiedDevice = withDisconnectedStatus(opDev);
140 if (modifiedDevice == null) {
143 LOG.info("Setting disconnected status for callhome device id:{}.", nodeId);
144 writeDevice(nodeId, modifiedDevice);
148 private void handleUnableToConnectNetconfNode(final NodeId nodeId) {
149 // The maximum configured number of reconnect attempts
150 // have been reached. No more reconnects will be
151 // attempted by the Netconf Connector.
152 LOG.debug("NETCONF Node: {} connection failed", nodeId.getValue());
154 Device opDev = readAndGetDevice(nodeId);
156 LOG.warn("No corresponding callhome device found - exiting.");
158 Device modifiedDevice = withFailedStatus(opDev);
159 if (modifiedDevice == null) {
162 LOG.info("Setting failed status for callhome device id:{}.", nodeId);
163 writeDevice(nodeId, modifiedDevice);
167 void asForceListedDevice(final String id, final PublicKey serverKey) {
168 NodeId nid = new NodeId(id);
169 Device device = newDevice(id, serverKey, DeviceStatus.DISCONNECTED);
170 writeDevice(nid, device);
173 void asUnlistedDevice(final String id, final PublicKey serverKey) {
174 NodeId nid = new NodeId(id);
175 Device device = newDevice(id, serverKey, DeviceStatus.FAILEDNOTALLOWED);
176 writeDevice(nid, device);
179 private static Device newDevice(final String id, final PublicKey serverKey, final DeviceStatus status) {
180 // used only for netconf devices that are connected via SSH transport and global credentials
181 String sshEncodedKey = serverKey.toString();
183 sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
184 } catch (IOException e) {
185 LOG.warn("Unable to encode public key to ssh format.", e);
187 return new DeviceBuilder()
189 .withKey(new DeviceKey(id))
190 .setTransport(new SshBuilder()
191 .setSshClientParams(new SshClientParamsBuilder().setHostKey(sshEncodedKey).build())
193 .setDeviceStatus(status)
197 private Device readAndGetDevice(final NodeId nodeId) {
198 return readDevice(nodeId).orElse(null);
201 private Optional<Device> readDevice(final NodeId nodeId) {
202 try (ReadTransaction opTx = dataBroker.newReadOnlyTransaction()) {
203 InstanceIdentifier<Device> deviceIID = buildDeviceInstanceIdentifier(nodeId);
204 return opTx.read(LogicalDatastoreType.OPERATIONAL, deviceIID).get();
205 } catch (InterruptedException | ExecutionException e) {
206 return Optional.empty();
210 private void writeDevice(final NodeId nodeId, final Device modifiedDevice) {
211 WriteTransaction opTx = dataBroker.newWriteOnlyTransaction();
212 opTx.merge(LogicalDatastoreType.OPERATIONAL, buildDeviceInstanceIdentifier(nodeId), modifiedDevice);
213 commit(opTx, modifiedDevice.key());
216 private static InstanceIdentifier<Device> buildDeviceInstanceIdentifier(final NodeId nodeId) {
217 return InstanceIdentifier.create(NetconfCallhomeServer.class)
218 .child(AllowedDevices.class)
219 .child(Device.class, new DeviceKey(nodeId.getValue()));
222 private static Device withConnectedStatus(final Device opDev) {
223 return deviceWithStatus(opDev, DeviceStatus.CONNECTED);
226 private static Device withFailedStatus(final Device opDev) {
227 return deviceWithStatus(opDev, DeviceStatus.FAILED);
230 private static Device withDisconnectedStatus(final Device opDev) {
231 return deviceWithStatus(opDev, DeviceStatus.DISCONNECTED);
234 private static Device withFailedAuthStatus(final Device opDev) {
235 return deviceWithStatus(opDev, DeviceStatus.FAILEDAUTHFAILURE);
238 private static Device deviceWithStatus(final Device opDev, final DeviceStatus status) {
239 final DeviceBuilder deviceBuilder = new DeviceBuilder()
240 .setUniqueId(opDev.getUniqueId())
241 .setDeviceStatus(status);
242 if (opDev.getTransport() != null) {
243 deviceBuilder.setTransport(opDev.getTransport());
245 deviceBuilder.setSshHostKey(opDev.getSshHostKey());
247 return deviceBuilder.build();
250 private void setDeviceStatus(final Device device) {
251 WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
252 InstanceIdentifier<Device> deviceIId = InstanceIdentifier.create(NetconfCallhomeServer.class)
253 .child(AllowedDevices.class)
254 .child(Device.class, device.key());
256 tx.merge(LogicalDatastoreType.OPERATIONAL, deviceIId, device);
257 commit(tx, device.key());
260 private static void commit(final WriteTransaction tx, final DeviceKey device) {
261 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
263 public void onSuccess(final CommitInfo result) {
264 LOG.debug("Device {} committed", device);
268 public void onFailure(final Throwable cause) {
269 LOG.warn("Failed to commit device {}", device, cause);
271 }, MoreExecutors.directExecutor());
274 private AllowedDevices getDevices() {
275 try (ReadTransaction rxTransaction = dataBroker.newReadOnlyTransaction()) {
276 return rxTransaction.read(LogicalDatastoreType.OPERATIONAL, IetfZeroTouchCallHomeServerProvider.ALL_DEVICES)
278 } catch (ExecutionException | InterruptedException e) {
279 LOG.error("Error trying to read the allowlist devices", e);
284 private Collection<Device> getDevicesAsList() {
285 AllowedDevices devices = getDevices();
286 return devices == null ? List.of() : devices.nonnullDevice().values();
290 public void reportFailedAuth(final PublicKey sshKey) {
291 AuthorizedKeysDecoder decoder = new AuthorizedKeysDecoder();
293 for (final Device device : getDevicesAsList()) {
294 final String keyString;
295 if (device.getTransport() instanceof Ssh ssh) {
296 keyString = ssh.getSshClientParams().getHostKey();
298 keyString = device.getSshHostKey();
300 if (keyString == null) {
301 LOG.info("Allowlist device {} does not have a host key, skipping it", device.getUniqueId());
306 PublicKey pubKey = decoder.decodePublicKey(keyString);
307 if (sshKey.getAlgorithm().equals(pubKey.getAlgorithm()) && sshKey.equals(pubKey)) {
308 Device failedDevice = withFailedAuthStatus(device);
309 if (failedDevice == null) {
312 LOG.info("Setting auth failed status for callhome device id:{}.", failedDevice.getUniqueId());
313 setDeviceStatus(failedDevice);
316 } catch (GeneralSecurityException e) {
317 LOG.error("Failed decoding a device key with host key: {}", keyString, e);
322 LOG.error("No match found for the failed auth device (should have been filtered by allowlist). Key: {}",
327 public void close() {