Bug 8153: enforce check-style rules for netconf
[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
9 package org.opendaylight.netconf.callhome.mount;
10
11 import static com.google.common.base.Preconditions.checkArgument;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Optional;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import java.io.IOException;
17 import java.net.InetSocketAddress;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Set;
22 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
23 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
24 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
25 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
27 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
30 import org.opendaylight.netconf.callhome.protocol.CallHomeAuthorizationProvider;
31 import org.opendaylight.netconf.callhome.protocol.NetconfCallHomeServer;
32 import org.opendaylight.netconf.callhome.protocol.NetconfCallHomeServerBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.callhome.device.status.rev170112.Device1;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.callhome.device.status.rev170112.Device1Builder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.NetconfCallhomeServer;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.AllowedDevices;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.allowed.devices.Device;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.allowed.devices.DeviceBuilder;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev161109.netconf.callhome.server.allowed.devices.DeviceKey;
40 import org.opendaylight.yangtools.concepts.ListenerRegistration;
41 import org.opendaylight.yangtools.yang.binding.DataObject;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class IetfZeroTouchCallHomeServerProvider implements AutoCloseable, DataChangeListener {
47     private static final String APPNAME = "CallHomeServer";
48     static final InstanceIdentifier<AllowedDevices> ALL_DEVICES = InstanceIdentifier.create(NetconfCallhomeServer.class)
49         .child(AllowedDevices.class);
50
51     private static final Logger LOG = LoggerFactory.getLogger(IetfZeroTouchCallHomeServerProvider.class);
52
53     private final DataBroker dataBroker;
54     private final CallHomeMountDispatcher mountDispacher;
55     private CallHomeAuthProviderImpl authProvider;
56
57     protected NetconfCallHomeServer server;
58
59     private ListenerRegistration<IetfZeroTouchCallHomeServerProvider> listenerReg = null;
60
61     private static final String CALL_HOME_PORT_KEY = "DefaultCallHomePort";
62     private int port = 0; // 0 = use default in NetconfCallHomeBuilder
63     private CallhomeStatusReporter statusReporter;
64
65     public IetfZeroTouchCallHomeServerProvider(DataBroker dataBroker, CallHomeMountDispatcher mountDispacher) {
66         this.dataBroker = dataBroker;
67         this.mountDispacher = mountDispacher;
68         this.authProvider = new CallHomeAuthProviderImpl(dataBroker);
69         this.statusReporter = new CallhomeStatusReporter(dataBroker);
70     }
71
72     public void init() {
73         // Register itself as a listener to changes in Devices subtree
74         try {
75             LOG.info("Initializing provider for {}", APPNAME);
76             initializeServer();
77             dataBroker.registerDataChangeListener(
78                 LogicalDatastoreType.CONFIGURATION, ALL_DEVICES, this, AsyncDataBroker.DataChangeScope.SUBTREE);
79             LOG.info("Initialization complete for {}", APPNAME);
80         } catch (IOException | Configuration.ConfigurationException e) {
81             LOG.error("Unable to successfully initialize", e);
82         }
83     }
84
85     public void setPort(String portStr) {
86         try {
87             Configuration configuration = new Configuration();
88             configuration.set(CALL_HOME_PORT_KEY, portStr);
89             port = configuration.getAsPort(CALL_HOME_PORT_KEY);
90             LOG.info("Setting port for call home server to {}", portStr);
91         } catch (Configuration.ConfigurationException e) {
92             LOG.error("Problem trying to set port for call home server {}", portStr, e);
93         }
94     }
95
96     private CallHomeAuthorizationProvider getCallHomeAuthorization() {
97         return new CallHomeAuthProviderImpl(dataBroker);
98     }
99
100     private void initializeServer() throws IOException {
101         LOG.info("Initializing Call Home server instance");
102         CallHomeAuthorizationProvider provider = this.getCallHomeAuthorization();
103         NetconfCallHomeServerBuilder builder = new NetconfCallHomeServerBuilder(
104                 provider, mountDispacher, statusReporter);
105         if (port > 0) {
106             builder.setBindAddress(new InetSocketAddress(port));
107         }
108         server = builder.build();
109         server.bind();
110         mountDispacher.createTopology();
111         LOG.info("Initialization complete for Call Home server instance");
112     }
113
114     @VisibleForTesting
115     void assertValid(Object obj, String description) {
116         if (obj == null) {
117             throw new RuntimeException(
118                 String.format("Failed to find %s in IetfZeroTouchCallHomeProvider.initialize()", description));
119         }
120     }
121
122     @Override
123     public void close() throws Exception {
124         authProvider.close();
125         statusReporter.close();
126
127         // FIXME unbind the server
128         if (this.listenerReg != null) {
129             listenerReg.close();
130         }
131         if (server != null) {
132             server.close();
133         }
134
135         LOG.info("Successfully closed provider for {}", APPNAME);
136     }
137
138     @Override
139     public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
140
141         // In case of any changes to the devices datatree, register the changed values with callhome server
142         // As of now, no way to add a new callhome client key to the CallHomeAuthorization instance since
143         // its created under CallHomeAuthorizationProvider.
144         // Will have to redesign a bit here.
145         // CallHomeAuthorization.
146         ReadOnlyTransaction roConfigTx = dataBroker.newReadOnlyTransaction();
147         CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture =
148                 roConfigTx.read(LogicalDatastoreType.CONFIGURATION, IetfZeroTouchCallHomeServerProvider.ALL_DEVICES);
149
150         if (hasDeletedDevices(change)) {
151             handleDeletedDevices(change);
152         }
153
154         try {
155             for (Device confDevice : getReadDevices(devicesFuture)) {
156                 readAndUpdateStatus(confDevice);
157             }
158         } catch (ReadFailedException e) {
159             LOG.error("Error trying to read the whitelist devices: {}", e);
160         }
161     }
162
163     private boolean hasDeletedDevices(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
164         return change.getRemovedPaths() != null;
165     }
166
167     private void handleDeletedDevices(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
168         checkArgument(change.getRemovedPaths() != null);
169
170         ReadWriteTransaction opTx = dataBroker.newReadWriteTransaction();
171
172         Set<InstanceIdentifier<?>> removedDevices = change.getRemovedPaths();
173         int numRemoved = removedDevices.size();
174
175         Iterator<InstanceIdentifier<?>> iterator = removedDevices.iterator();
176         while (iterator.hasNext()) {
177             InstanceIdentifier<?> removedIID = iterator.next();
178             LOG.info("Deleting the entry for callhome device {}", removedIID);
179             opTx.delete(LogicalDatastoreType.OPERATIONAL, removedIID);
180         }
181
182         if (numRemoved > 0) {
183             opTx.submit();
184         }
185     }
186
187     private List<Device> getReadDevices(CheckedFuture<Optional<AllowedDevices>, ReadFailedException> devicesFuture)
188             throws ReadFailedException {
189         Optional<AllowedDevices> opt = devicesFuture.checkedGet();
190         if (opt.isPresent()) {
191             AllowedDevices confDevices = opt.get();
192             if (confDevices != null) {
193                 LOG.debug("Read {} devices", confDevices.getDevice().size());
194                 return confDevices.getDevice();
195             }
196         }
197
198         LOG.debug("Failed to read devices");
199         return new ArrayList<>();
200     }
201
202     private void readAndUpdateStatus(Device cfgDevice) throws ReadFailedException {
203         InstanceIdentifier<Device> deviceIID = InstanceIdentifier.create(NetconfCallhomeServer.class)
204                 .child(AllowedDevices.class)
205                 .child(Device.class, new DeviceKey(cfgDevice.getUniqueId()));
206
207         ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();
208         CheckedFuture<Optional<Device>, ReadFailedException> deviceFuture = tx.read(
209             LogicalDatastoreType.OPERATIONAL, deviceIID);
210
211         Optional<Device> opDevGet = deviceFuture.checkedGet();
212         Device1 devStatus = new Device1Builder().setDeviceStatus(Device1.DeviceStatus.DISCONNECTED).build();
213         if (opDevGet.isPresent()) {
214             Device opDevice = opDevGet.get();
215             devStatus = opDevice.getAugmentation(Device1.class);
216         }
217
218         Device newOpDevice = new DeviceBuilder()
219                 .addAugmentation(Device1.class, devStatus)
220                 .setSshHostKey(cfgDevice.getSshHostKey())
221                 .setUniqueId(cfgDevice.getUniqueId()).build();
222
223         cfgDevice = newOpDevice;
224
225         tx.merge(LogicalDatastoreType.OPERATIONAL, deviceIID, cfgDevice);
226         tx.submit();
227     }
228 }