Simplify builder
[netconf.git] / apps / callhome-provider / src / main / java / org / opendaylight / netconf / callhome / mount / CallhomeStatusReporter.java
1 /*
2  * Copyright (c) 2016 Brocade Communication Systems 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.callhome.mount;
9
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;
54
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())));
59
60     private static final Logger LOG = LoggerFactory.getLogger(CallhomeStatusReporter.class);
61
62     private final DataBroker dataBroker;
63     private final ListenerRegistration<CallhomeStatusReporter> reg;
64
65     CallhomeStatusReporter(final DataBroker broker) {
66         dataBroker = broker;
67         reg = dataBroker.registerDataTreeChangeListener(DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL,
68             NETCONF_TOPO_IID.child(Node.class)), this);
69     }
70
71     @Override
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()) {
77                 case WRITE:
78                 case SUBTREE_MODIFIED:
79                     if (isNetconfNode(rootNode.getDataAfter())) {
80                         NodeId nodeId = getNodeId(identifier);
81                         if (nodeId != null) {
82                             NetconfNode nnode = rootNode.getDataAfter().augmentation(NetconfNode.class);
83                             handledNetconfNode(nodeId, nnode);
84                         }
85                     }
86                     break;
87                 case DELETE:
88                     if (isNetconfNode(rootNode.getDataBefore())) {
89                         final NodeId nodeId = getNodeId(identifier);
90                         if (nodeId != null) {
91                             handleDisconnectedNetconfNode(nodeId);
92                         }
93                     }
94                     break;
95                 default:
96                     break;
97             }
98         }
99     }
100
101     private static boolean isNetconfNode(final Node node) {
102         return node.augmentation(NetconfNode.class) != null;
103     }
104
105     private static NodeId getNodeId(final InstanceIdentifier<?> path) {
106         NodeKey key = path.firstKeyOf(Node.class);
107         return key != null ? key.getNodeId() : null;
108     }
109
110     private void handledNetconfNode(final NodeId nodeId, final NetconfNode nnode) {
111         switch (nnode.getConnectionStatus()) {
112             case Connected: {
113                 handleConnectedNetconfNode(nodeId);
114                 break;
115             }
116             default:
117             case UnableToConnect: {
118                 handleUnableToConnectNetconfNode(nodeId);
119                 break;
120             }
121         }
122     }
123
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());
128
129         Device opDev = readAndGetDevice(nodeId);
130         if (opDev == null) {
131             LOG.warn("No corresponding callhome device found - exiting.");
132         } else {
133             Device modifiedDevice = withConnectedStatus(opDev);
134             if (modifiedDevice == null) {
135                 return;
136             }
137             LOG.info("Setting successful status for callhome device id:{}.", nodeId);
138             writeDevice(nodeId, modifiedDevice);
139         }
140     }
141
142     private void handleDisconnectedNetconfNode(final NodeId nodeId) {
143         LOG.debug("NETCONF Node: {} disconnected", nodeId.getValue());
144
145         Device opDev = readAndGetDevice(nodeId);
146         if (opDev == null) {
147             LOG.warn("No corresponding callhome device found - exiting.");
148         } else {
149             Device modifiedDevice = withDisconnectedStatus(opDev);
150             if (modifiedDevice == null) {
151                 return;
152             }
153             LOG.info("Setting disconnected status for callhome device id:{}.", nodeId);
154             writeDevice(nodeId, modifiedDevice);
155         }
156     }
157
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());
163
164         Device opDev = readAndGetDevice(nodeId);
165         if (opDev == null) {
166             LOG.warn("No corresponding callhome device found - exiting.");
167         } else {
168             Device modifiedDevice = withFailedStatus(opDev);
169             if (modifiedDevice == null) {
170                 return;
171             }
172             LOG.info("Setting failed status for callhome device id:{}.", nodeId);
173             writeDevice(nodeId, modifiedDevice);
174         }
175     }
176
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);
181     }
182
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);
187     }
188
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();
192         try {
193             sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
194         } catch (IOException e) {
195             LOG.warn("Unable to encode public key to ssh format.", e);
196         }
197         return new DeviceBuilder()
198             .setUniqueId(id)
199             .withKey(new DeviceKey(id))
200             .setTransport(new SshBuilder()
201                 .setSshClientParams(new SshClientParamsBuilder().setHostKey(sshEncodedKey).build())
202                 .build())
203             .addAugmentation(new Device1Builder().setDeviceStatus(status).build())
204             .build();
205     }
206
207     private Device readAndGetDevice(final NodeId nodeId) {
208         return readDevice(nodeId).orElse(null);
209     }
210
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();
217         }
218     }
219
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());
224     }
225
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()));
230     }
231
232     private static Device withConnectedStatus(final Device opDev) {
233         return deviceWithStatus(opDev, Device1.DeviceStatus.CONNECTED);
234     }
235
236     private static Device withFailedStatus(final Device opDev) {
237         return deviceWithStatus(opDev, DeviceStatus.FAILED);
238     }
239
240     private static Device withDisconnectedStatus(final Device opDev) {
241         return deviceWithStatus(opDev, DeviceStatus.DISCONNECTED);
242     }
243
244     private static Device withFailedAuthStatus(final Device opDev) {
245         return deviceWithStatus(opDev, DeviceStatus.FAILEDAUTHFAILURE);
246     }
247
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());
254         } else {
255             deviceBuilder.setSshHostKey(opDev.getSshHostKey());
256         }
257         return deviceBuilder.build();
258     }
259
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());
265
266         tx.merge(LogicalDatastoreType.OPERATIONAL, deviceIId, device);
267         commit(tx, device.key());
268     }
269
270     private static void commit(final WriteTransaction tx, final DeviceKey device) {
271         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
272             @Override
273             public void onSuccess(final CommitInfo result) {
274                 LOG.debug("Device {} committed", device);
275             }
276
277             @Override
278             public void onFailure(final Throwable cause) {
279                 LOG.warn("Failed to commit device {}", device, cause);
280             }
281         }, MoreExecutors.directExecutor());
282     }
283
284     private AllowedDevices getDevices() {
285         try (ReadTransaction rxTransaction = dataBroker.newReadOnlyTransaction()) {
286             return rxTransaction.read(LogicalDatastoreType.OPERATIONAL, IetfZeroTouchCallHomeServerProvider.ALL_DEVICES)
287                     .get().orElse(null);
288         } catch (ExecutionException | InterruptedException e) {
289             LOG.error("Error trying to read the whitelist devices", e);
290             return null;
291         }
292     }
293
294     private Collection<Device> getDevicesAsList() {
295         AllowedDevices devices = getDevices();
296         return devices == null ? Collections.emptyList() : devices.nonnullDevice().values();
297     }
298
299     @Override
300     public void reportFailedAuth(final PublicKey sshKey) {
301         AuthorizedKeysDecoder decoder = new AuthorizedKeysDecoder();
302
303         for (final Device device : getDevicesAsList()) {
304             final String keyString;
305             if (device.getTransport() instanceof Ssh ssh) {
306                 keyString = ssh.getSshClientParams().getHostKey();
307             } else {
308                 keyString = device.getSshHostKey();
309             }
310             if (keyString == null) {
311                 LOG.info("Whitelist device {} does not have a host key, skipping it", device.getUniqueId());
312                 continue;
313             }
314
315             try {
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) {
320                         return;
321                     }
322                     LOG.info("Setting auth failed status for callhome device id:{}.", failedDevice.getUniqueId());
323                     setDeviceStatus(failedDevice);
324                     return;
325                 }
326             } catch (GeneralSecurityException e) {
327                 LOG.error("Failed decoding a device key with host key: {}", keyString, e);
328                 return;
329             }
330         }
331
332         LOG.error("No match found for the failed auth device (should have been filtered by whitelist). Key: {}",
333                 sshKey);
334     }
335
336     @Override
337     public void close() {
338         reg.close();
339     }
340 }