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