Remove BaseCallHomeTopology
[netconf.git] / apps / callhome-provider / src / main / java / org / opendaylight / netconf / callhome / mount / IetfZeroTouchCallHomeServerProvider.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.annotations.VisibleForTesting;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.MoreExecutors;
14 import io.netty.channel.nio.NioEventLoopGroup;
15 import java.io.IOException;
16 import java.net.InetSocketAddress;
17 import java.util.Collection;
18 import java.util.HashSet;
19 import java.util.Map;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.concurrent.ExecutionException;
23 import org.opendaylight.mdsal.binding.api.DataBroker;
24 import org.opendaylight.mdsal.binding.api.DataObjectModification;
25 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
26 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
27 import org.opendaylight.mdsal.binding.api.DataTreeModification;
28 import org.opendaylight.mdsal.binding.api.ReadTransaction;
29 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
30 import org.opendaylight.mdsal.binding.api.WriteTransaction;
31 import org.opendaylight.mdsal.common.api.CommitInfo;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.netconf.callhome.protocol.NetconfCallHomeServer;
34 import org.opendaylight.netconf.callhome.protocol.NetconfCallHomeServerBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.callhome.device.status.rev170112.Device1;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.callhome.device.status.rev170112.Device1Builder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.NetconfCallhomeServer;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.AllowedDevices;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.Device;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.DeviceBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.DeviceKey;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.Transport;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.Ssh;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.SshBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.Tls;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.ssh.SshClientParams;
47 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;
48 import org.opendaylight.yangtools.concepts.ListenerRegistration;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataTreeChangeListener<AllowedDevices> {
54     private static final String APPNAME = "CallHomeServer";
55     static final InstanceIdentifier<AllowedDevices> ALL_DEVICES = InstanceIdentifier.create(NetconfCallhomeServer.class)
56             .child(AllowedDevices.class);
57
58     private static final Logger LOG = LoggerFactory.getLogger(IetfZeroTouchCallHomeServerProvider.class);
59
60     private final DataBroker dataBroker;
61     private final CallHomeMountDispatcher mountDispacher;
62     private final CallHomeAuthProviderImpl authProvider;
63
64     protected NetconfCallHomeServer server;
65
66     private ListenerRegistration<IetfZeroTouchCallHomeServerProvider> listenerReg = null;
67
68     private static final String CALL_HOME_PORT_KEY = "DefaultCallHomePort";
69     private int port = 0; // 0 = use default in NetconfCallHomeBuilder
70     private final CallhomeStatusReporter statusReporter;
71
72     public IetfZeroTouchCallHomeServerProvider(final DataBroker dataBroker,
73             final CallHomeMountDispatcher mountDispacher) {
74         this.dataBroker = dataBroker;
75         this.mountDispacher = mountDispacher;
76         // FIXME: these should be separate components
77         authProvider = new CallHomeAuthProviderImpl(dataBroker);
78         statusReporter = new CallhomeStatusReporter(dataBroker);
79     }
80
81     public void init() {
82         // Register itself as a listener to changes in Devices subtree
83         try {
84             LOG.info("Initializing provider for {}", APPNAME);
85             initializeServer();
86             listenerReg = dataBroker.registerDataTreeChangeListener(
87                 DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, ALL_DEVICES), this);
88             LOG.info("Initialization complete for {}", APPNAME);
89         } catch (IOException | Configuration.ConfigurationException e) {
90             LOG.error("Unable to successfully initialize", e);
91         }
92     }
93
94     public void setPort(final String portStr) {
95         try {
96             Configuration configuration = new Configuration();
97             configuration.set(CALL_HOME_PORT_KEY, portStr);
98             port = configuration.getAsPort(CALL_HOME_PORT_KEY);
99             LOG.info("Setting port for call home server to {}", portStr);
100         } catch (Configuration.ConfigurationException e) {
101             LOG.error("Problem trying to set port for call home server {}", portStr, e);
102         }
103     }
104
105     private void initializeServer() throws IOException {
106         LOG.info("Initializing Call Home server instance");
107         NetconfCallHomeServerBuilder builder = new NetconfCallHomeServerBuilder(authProvider, mountDispacher,
108             statusReporter);
109         if (port > 0) {
110             builder.setBindAddress(new InetSocketAddress(port));
111         }
112         builder.setNettyGroup(new NioEventLoopGroup());
113         server = builder.build();
114         server.bind();
115         mountDispacher.createTopology();
116         LOG.info("Initialization complete for Call Home server instance");
117     }
118
119     @VisibleForTesting
120     void assertValid(final Object obj, final String description) {
121         if (obj == null) {
122             throw new IllegalStateException(
123                 "Failed to find " + description + " in IetfZeroTouchCallHomeProvider.initialize()");
124         }
125     }
126
127     @Override
128     public void close() {
129         authProvider.close();
130         statusReporter.close();
131
132         // FIXME unbind the server
133         if (listenerReg != null) {
134             listenerReg.close();
135         }
136         if (server != null) {
137             server.close();
138         }
139
140         LOG.info("Successfully closed provider for {}", APPNAME);
141     }
142
143     @Override
144     public void onDataTreeChanged(final Collection<DataTreeModification<AllowedDevices>> changes) {
145         // In case of any changes to the devices datatree, register the changed values with callhome server
146         // As of now, no way to add a new callhome client key to the CallHomeAuthorization instance since
147         // its created under CallHomeAuthorizationProvider.
148         // Will have to redesign a bit here.
149         // CallHomeAuthorization.
150         final ListenableFuture<Optional<AllowedDevices>> devicesFuture;
151         try (ReadTransaction roConfigTx = dataBroker.newReadOnlyTransaction()) {
152             devicesFuture = roConfigTx.read(LogicalDatastoreType.CONFIGURATION,
153                 IetfZeroTouchCallHomeServerProvider.ALL_DEVICES);
154         }
155
156         Set<InstanceIdentifier<?>> deletedDevices = new HashSet<>();
157         for (DataTreeModification<AllowedDevices> change : changes) {
158             DataObjectModification<AllowedDevices> rootNode = change.getRootNode();
159             switch (rootNode.getModificationType()) {
160                 case DELETE:
161                     deletedDevices.add(change.getRootPath().getRootIdentifier());
162                     break;
163                 default:
164                     break;
165             }
166         }
167
168         handleDeletedDevices(deletedDevices);
169
170         try {
171             for (Device confDevice : getReadDevices(devicesFuture)) {
172                 readAndUpdateStatus(confDevice);
173             }
174         } catch (ExecutionException | InterruptedException e) {
175             LOG.error("Error trying to read the whitelist devices", e);
176         }
177     }
178
179     private void handleDeletedDevices(final Set<InstanceIdentifier<?>> deletedDevices) {
180         if (deletedDevices.isEmpty()) {
181             return;
182         }
183
184         WriteTransaction opTx = dataBroker.newWriteOnlyTransaction();
185
186         for (InstanceIdentifier<?> removedIID : deletedDevices) {
187             LOG.info("Deleting the entry for callhome device {}", removedIID);
188             opTx.delete(LogicalDatastoreType.OPERATIONAL, removedIID);
189         }
190
191         opTx.commit().addCallback(new FutureCallback<CommitInfo>() {
192             @Override
193             public void onSuccess(final CommitInfo result) {
194                 LOG.debug("Device deletions committed");
195             }
196
197             @Override
198             public void onFailure(final Throwable cause) {
199                 LOG.warn("Failed to commit device deletions", cause);
200             }
201         }, MoreExecutors.directExecutor());
202     }
203
204     private static Collection<Device> getReadDevices(final ListenableFuture<Optional<AllowedDevices>> devicesFuture)
205             throws InterruptedException, ExecutionException {
206         return devicesFuture.get().map(AllowedDevices::nonnullDevice).orElse(Map.of()).values();
207     }
208
209     private void readAndUpdateStatus(final Device cfgDevice) throws InterruptedException, ExecutionException {
210         InstanceIdentifier<Device> deviceIID = InstanceIdentifier.create(NetconfCallhomeServer.class)
211                 .child(AllowedDevices.class).child(Device.class, new DeviceKey(cfgDevice.getUniqueId()));
212
213         ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
214         ListenableFuture<Optional<Device>> deviceFuture = tx.read(LogicalDatastoreType.OPERATIONAL, deviceIID);
215
216         final Device1 devStatus;
217         Optional<Device> opDevGet = deviceFuture.get();
218         if (opDevGet.isPresent()) {
219             devStatus = opDevGet.orElseThrow().augmentation(Device1.class);
220         } else {
221             devStatus = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.DISCONNECTED).build();
222         }
223
224         final Device opDevice = createOperationalDevice(cfgDevice, devStatus);
225         tx.merge(LogicalDatastoreType.OPERATIONAL, deviceIID, opDevice);
226         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
227             @Override
228             public void onSuccess(final CommitInfo result) {
229                 LOG.debug("Device {} status update committed", cfgDevice.key());
230             }
231
232             @Override
233             public void onFailure(final Throwable cause) {
234                 LOG.warn("Failed to commit device {} status update", cfgDevice.key(), cause);
235             }
236         }, MoreExecutors.directExecutor());
237     }
238
239     private static Device createOperationalDevice(final Device cfgDevice, final Device1 devStatus) {
240         final DeviceBuilder deviceBuilder = new DeviceBuilder()
241             .addAugmentation(devStatus)
242             .setUniqueId(cfgDevice.getUniqueId());
243         if (cfgDevice.getTransport() instanceof Ssh ssh) {
244             final String hostKey = ssh.getSshClientParams().getHostKey();
245             final SshClientParams params = new SshClientParamsBuilder().setHostKey(hostKey).build();
246             final Transport sshTransport = new SshBuilder().setSshClientParams(params).build();
247             deviceBuilder.setTransport(sshTransport);
248         } else if (cfgDevice.getTransport() instanceof Tls) {
249             deviceBuilder.setTransport(cfgDevice.getTransport());
250         } else if (cfgDevice.getSshHostKey() != null) {
251             deviceBuilder.setSshHostKey(cfgDevice.getSshHostKey());
252         }
253         return deviceBuilder.build();
254     }
255 }