Rework SslHandlerFactory
[netconf.git] / apps / callhome-provider / src / main / java / org / opendaylight / netconf / callhome / mount / CallHomeMountStatusReporter.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech s.r.o. 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.collect.ImmutableList;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.MoreExecutors;
13 import java.io.IOException;
14 import java.net.SocketAddress;
15 import java.security.PublicKey;
16 import java.util.List;
17 import java.util.concurrent.ExecutionException;
18 import javax.annotation.PreDestroy;
19 import javax.inject.Inject;
20 import javax.inject.Singleton;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.mdsal.binding.api.DataBroker;
23 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
24 import org.opendaylight.mdsal.binding.api.DataTreeModification;
25 import org.opendaylight.mdsal.common.api.CommitInfo;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.netconf.callhome.server.CallHomeStatusRecorder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.NetconfCallhomeServer;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.SshPublicKey;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.AllowedDevices;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.Device;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.Device.DeviceStatus;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.DeviceBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.DeviceKey;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.device.transport.SshBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.device.transport.ssh.SshClientParamsBuilder;
37 import org.opendaylight.yangtools.concepts.Registration;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.osgi.service.component.annotations.Activate;
40 import org.osgi.service.component.annotations.Component;
41 import org.osgi.service.component.annotations.Deactivate;
42 import org.osgi.service.component.annotations.Reference;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Service responsible for status update for call-home devices.
48  */
49 @Component(service = {CallHomeMountStatusReporter.class, CallHomeStatusRecorder.class}, immediate = true)
50 @Singleton
51 public final class CallHomeMountStatusReporter implements CallHomeStatusRecorder, AutoCloseable {
52     private static final Logger LOG = LoggerFactory.getLogger(CallHomeMountStatusReporter.class);
53     private static final InstanceIdentifier<AllowedDevices> ALL_DEVICES_II =
54         InstanceIdentifier.create(NetconfCallhomeServer.class).child(AllowedDevices.class);
55
56     private final DataBroker dataBroker;
57     private final Registration syncReg;
58
59     @Activate
60     @Inject
61     public CallHomeMountStatusReporter(final @Reference DataBroker broker) {
62         dataBroker = broker;
63         syncReg = dataBroker.registerDataTreeChangeListener(
64             DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, ALL_DEVICES_II.child(Device.class)),
65             this::onConfigurationDataTreeChanged);
66     }
67
68     @Deactivate
69     @PreDestroy
70     @Override
71     public void close() {
72         syncReg.close();
73     }
74
75     @Override
76     public void reportSuccess(final String id) {
77         updateCallHomeDeviceStatus(id, DeviceStatus.CONNECTED);
78     }
79
80     @Override
81     public void reportDisconnected(final String id) {
82         updateCallHomeDeviceStatus(id, DeviceStatus.DISCONNECTED);
83     }
84
85     @Override
86     public void reportFailedAuth(final String id) {
87         updateCallHomeDeviceStatus(id, DeviceStatus.FAILEDAUTHFAILURE);
88     }
89
90     @Override
91     public void reportNetconfFailure(final String id) {
92         updateCallHomeDeviceStatus(id, DeviceStatus.FAILED);
93     }
94
95     @Override
96     public void reportUnknown(final SocketAddress address, final PublicKey publicKey) {
97         // ignored --> the case is handled by ssh auth provider which are conditionally invoking
98         // reportNewSshDevice() directly
99     }
100
101     /**
102      * Update device status within operational datastore.
103      *
104      * @param id device id
105      * @param status new status
106      */
107     public void updateCallHomeDeviceStatus(final String id, final DeviceStatus status) {
108         LOG.debug("Setting status '{}' for call-home device {}.", status, id);
109         final var instanceIdentifier = buildInstanceIdentifier(id);
110         final var device = readDevice(instanceIdentifier);
111         if (device == null) {
112             LOG.warn("No call-home device '{}' found in operational datastore. Status update to '{}' is omitted.",
113                 id, status);
114             return;
115         }
116         if (status == device.getDeviceStatus()) {
117             LOG.debug("Call-home device '{}' already having status '{}'. Update omitted", id, status);
118             return;
119         }
120         writeDevice(instanceIdentifier, new DeviceBuilder(device).setDeviceStatus(status).build());
121     }
122
123     /**
124      * Persists new call-home device within operational datastore.
125      *
126      * @param id device id
127      * @param serverKey public key used for device identification over ssh
128      * @param status initial device status
129      */
130     public void reportNewSshDevice(final String id, final PublicKey serverKey, final DeviceStatus status) {
131         final var device = newSshDevice(id, serverKey, status);
132         if (device != null) {
133             writeDevice(buildInstanceIdentifier(id), device);
134         }
135     }
136
137     private static Device newSshDevice(final String id, final PublicKey serverKey, final DeviceStatus status) {
138         // used only for netconf devices that are connected via SSH transport and global credentials
139         final SshPublicKey sshEncodedKey;
140         try {
141             sshEncodedKey = AuthorizedKeysDecoder.encodePublicKey(serverKey);
142         } catch (IOException e) {
143             LOG.warn("Unable to encode public key to ssh format, skipping update", e);
144             return null;
145         }
146
147         return new DeviceBuilder()
148             .setUniqueId(id)
149             .withKey(new DeviceKey(id))
150             .setTransport(new SshBuilder().setSshClientParams(
151                 new SshClientParamsBuilder().setHostKey(sshEncodedKey).build()).build())
152             .setDeviceStatus(status)
153             .build();
154     }
155
156     private @Nullable Device readDevice(final InstanceIdentifier<Device> instanceIdentifier) {
157         try (var readTx = dataBroker.newReadOnlyTransaction()) {
158             return readTx.read(LogicalDatastoreType.OPERATIONAL, instanceIdentifier).get().orElse(null);
159         } catch (InterruptedException | ExecutionException e) {
160             return null;
161         }
162     }
163
164     private void writeDevice(final InstanceIdentifier<Device> instanceIdentifier, final Device device) {
165         final var tx = dataBroker.newWriteOnlyTransaction();
166         tx.merge(LogicalDatastoreType.OPERATIONAL, instanceIdentifier, device);
167         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
168             @Override
169             public void onSuccess(final CommitInfo result) {
170                 LOG.debug("Device {} committed", device);
171             }
172
173             @Override
174             public void onFailure(final Throwable cause) {
175                 LOG.warn("Failed to commit device {}", device, cause);
176             }
177         }, MoreExecutors.directExecutor());
178     }
179
180     private static InstanceIdentifier<Device> buildInstanceIdentifier(final String id) {
181         return ALL_DEVICES_II.child(Device.class, new DeviceKey(id));
182     }
183
184     // DataTreeChangeListener dedicated to call-home device data synchronization
185     // from CONFIGURATION to OPERATIONAL datastore (excluding device status)
186     private void onConfigurationDataTreeChanged(final List<DataTreeModification<Device>> changes) {
187         final var deleted = ImmutableList.<InstanceIdentifier<Device>>builder();
188         final var modified = ImmutableList.<Device>builder();
189         for (var change : changes) {
190             var changeRootNode = change.getRootNode();
191             switch (changeRootNode.modificationType()) {
192                 case SUBTREE_MODIFIED:
193                 case WRITE:
194                     modified.add(changeRootNode.dataAfter());
195                     break;
196                 case DELETE:
197                     deleted.add(change.getRootPath().path());
198                     break;
199                 default:
200                     break;
201             }
202         }
203         syncModifiedDevices(modified.build());
204         syncDeletedDevices(deleted.build());
205     }
206
207     private void syncModifiedDevices(final List<Device> updatedDevices) {
208         if (updatedDevices.isEmpty()) {
209             return;
210         }
211         for (var configDevice : updatedDevices) {
212             final var instanceIdentifier = buildInstanceIdentifier(configDevice.getUniqueId());
213             final var operDevice = readDevice(instanceIdentifier);
214             final var currentStatus = operDevice == null || operDevice.getDeviceStatus() == null
215                 ? DeviceStatus.DISCONNECTED : operDevice.getDeviceStatus();
216             writeDevice(instanceIdentifier, new DeviceBuilder(configDevice).setDeviceStatus(currentStatus).build());
217         }
218     }
219
220     private void syncDeletedDevices(final List<InstanceIdentifier<Device>> deletedDeviceIdentifiers) {
221         if (deletedDeviceIdentifiers.isEmpty()) {
222             return;
223         }
224         final var writeTx = dataBroker.newWriteOnlyTransaction();
225         deletedDeviceIdentifiers.forEach(instancedIdentifier ->
226             writeTx.delete(LogicalDatastoreType.OPERATIONAL, instancedIdentifier));
227
228         writeTx.commit().addCallback(new FutureCallback<CommitInfo>() {
229             @Override
230             public void onSuccess(final CommitInfo result) {
231                 LOG.debug("Device deletions committed");
232             }
233
234             @Override
235             public void onFailure(final Throwable cause) {
236                 LOG.warn("Failed to commit device deletions", cause);
237             }
238         }, MoreExecutors.directExecutor());
239     }
240 }