f9194a7e1ce63c68f38380e33042e4b52cc14794
[onosfw.git] /
1 /*
2  * Copyright 2015 Open Networking Laboratory
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onosproject.provider.netconf.device.impl;
17
18 import static com.google.common.base.Strings.isNullOrEmpty;
19 import static org.onlab.util.Tools.delay;
20 import static org.onlab.util.Tools.get;
21 import static org.onlab.util.Tools.groupedThreads;
22 import static org.slf4j.LoggerFactory.getLogger;
23
24 import java.io.IOException;
25 import java.net.SocketTimeoutException;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.util.Dictionary;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.TimeUnit;
35
36 import org.apache.felix.scr.annotations.Activate;
37 import org.apache.felix.scr.annotations.Component;
38 import org.apache.felix.scr.annotations.Deactivate;
39 import org.apache.felix.scr.annotations.Modified;
40 import org.apache.felix.scr.annotations.Property;
41 import org.apache.felix.scr.annotations.Reference;
42 import org.apache.felix.scr.annotations.ReferenceCardinality;
43 import org.onlab.packet.ChassisId;
44 import org.onosproject.cfg.ComponentConfigService;
45 import org.onosproject.cluster.ClusterService;
46 import org.onosproject.net.Device;
47 import org.onosproject.net.DeviceId;
48 import org.onosproject.net.MastershipRole;
49 import org.onosproject.net.device.DefaultDeviceDescription;
50 import org.onosproject.net.device.DeviceDescription;
51 import org.onosproject.net.device.DeviceProvider;
52 import org.onosproject.net.device.DeviceProviderRegistry;
53 import org.onosproject.net.device.DeviceProviderService;
54 import org.onosproject.net.device.DeviceService;
55 import org.onosproject.net.provider.AbstractProvider;
56 import org.onosproject.net.provider.ProviderId;
57 import org.onosproject.provider.netconf.device.impl.NetconfDevice.DeviceState;
58 import org.osgi.service.component.ComponentContext;
59 import org.slf4j.Logger;
60
61 /**
62  * Provider which will try to fetch the details of NETCONF devices from the core
63  * and run a capability discovery on each of the device.
64  */
65 @Component(immediate = true)
66 public class NetconfDeviceProvider extends AbstractProvider
67         implements DeviceProvider {
68
69     private final Logger log = getLogger(NetconfDeviceProvider.class);
70
71     protected Map<DeviceId, NetconfDevice> netconfDeviceMap = new ConcurrentHashMap<DeviceId, NetconfDevice>();
72
73     private DeviceProviderService providerService;
74
75     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
76     protected DeviceProviderRegistry providerRegistry;
77
78     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
79     protected DeviceService deviceService;
80
81     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
82     protected ClusterService clusterService;
83
84     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
85     protected ComponentConfigService cfgService;
86
87     private ExecutorService deviceBuilder = Executors
88             .newFixedThreadPool(1, groupedThreads("onos/netconf", "device-creator"));
89
90     // Delay between events in ms.
91     private static final int EVENTINTERVAL = 5;
92
93     private static final String SCHEME = "netconf";
94
95     @Property(name = "devConfigs", value = "", label = "Instance-specific configurations")
96     private String devConfigs = null;
97
98     @Property(name = "devPasswords", value = "", label = "Instance-specific password")
99     private String devPasswords = null;
100
101     /**
102      * Creates a provider with the supplier identifier.
103      */
104     public NetconfDeviceProvider() {
105         super(new ProviderId("netconf", "org.onosproject.provider.netconf"));
106     }
107
108     @Activate
109     public void activate(ComponentContext context) {
110         cfgService.registerProperties(getClass());
111         providerService = providerRegistry.register(this);
112         modified(context);
113         log.info("Started");
114     }
115
116     @Deactivate
117     public void deactivate(ComponentContext context) {
118         cfgService.unregisterProperties(getClass(), false);
119         try {
120             for (Entry<DeviceId, NetconfDevice> deviceEntry : netconfDeviceMap
121                     .entrySet()) {
122                 deviceBuilder.submit(new DeviceCreator(deviceEntry.getValue(),
123                                                        false));
124             }
125             deviceBuilder.awaitTermination(1000, TimeUnit.MILLISECONDS);
126         } catch (InterruptedException e) {
127             log.error("Device builder did not terminate");
128         }
129         deviceBuilder.shutdownNow();
130         netconfDeviceMap.clear();
131         providerRegistry.unregister(this);
132         providerService = null;
133         log.info("Stopped");
134     }
135
136     @Modified
137     public void modified(ComponentContext context) {
138         if (context == null) {
139             log.info("No configuration file");
140             return;
141         }
142         Dictionary<?, ?> properties = context.getProperties();
143         String deviceCfgValue = get(properties, "devConfigs");
144         log.info("Settings: devConfigs={}", deviceCfgValue);
145         if (!isNullOrEmpty(deviceCfgValue)) {
146             addOrRemoveDevicesConfig(deviceCfgValue);
147         }
148     }
149
150     private void addOrRemoveDevicesConfig(String deviceConfig) {
151         for (String deviceEntry : deviceConfig.split(",")) {
152             NetconfDevice device = processDeviceEntry(deviceEntry);
153             if (device != null) {
154                 log.info("Device Detail: username: {}, host={}, port={}, state={}",
155                         device.getUsername(), device.getSshHost(),
156                          device.getSshPort(), device.getDeviceState().name());
157                 if (device.isActive()) {
158                     deviceBuilder.submit(new DeviceCreator(device, true));
159                 } else {
160                     deviceBuilder.submit(new DeviceCreator(device, false));
161                 }
162             }
163         }
164     }
165
166     private NetconfDevice processDeviceEntry(String deviceEntry) {
167         if (deviceEntry == null) {
168             log.info("No content for Device Entry, so cannot proceed further.");
169             return null;
170         }
171         log.info("Trying to convert Device Entry String: " + deviceEntry
172                 + " to a Netconf Device Object");
173         NetconfDevice device = null;
174         try {
175             String userInfo = deviceEntry.substring(0, deviceEntry
176                     .lastIndexOf('@'));
177             String hostInfo = deviceEntry.substring(deviceEntry
178                     .lastIndexOf('@') + 1);
179             String[] infoSplit = userInfo.split(":");
180             String username = infoSplit[0];
181             String password = infoSplit[1];
182             infoSplit = hostInfo.split(":");
183             String hostIp = infoSplit[0];
184             Integer hostPort;
185             try {
186                 hostPort = Integer.parseInt(infoSplit[1]);
187             } catch (NumberFormatException nfe) {
188                 log.error("Bad Configuration Data: Failed to parse host port number string: "
189                         + infoSplit[1]);
190                 throw nfe;
191             }
192             String deviceState = infoSplit[2];
193             if (isNullOrEmpty(username) || isNullOrEmpty(password)
194                     || isNullOrEmpty(hostIp) || hostPort == 0) {
195                 log.warn("Bad Configuration Data: both user and device information parts of Configuration "
196                         + deviceEntry + " should be non-nullable");
197             } else {
198                 device = new NetconfDevice(hostIp, hostPort, username, password);
199                 if (!isNullOrEmpty(deviceState)) {
200                     if (deviceState.toUpperCase().equals(DeviceState.ACTIVE
201                                                                  .name())) {
202                         device.setDeviceState(DeviceState.ACTIVE);
203                     } else if (deviceState.toUpperCase()
204                             .equals(DeviceState.INACTIVE.name())) {
205                         device.setDeviceState(DeviceState.INACTIVE);
206                     } else {
207                         log.warn("Device State Information can not be empty, so marking the state as INVALID");
208                         device.setDeviceState(DeviceState.INVALID);
209                     }
210                 } else {
211                     log.warn("The device entry do not specify state information, so marking the state as INVALID");
212                     device.setDeviceState(DeviceState.INVALID);
213                 }
214             }
215         } catch (ArrayIndexOutOfBoundsException aie) {
216             log.error("Error while reading config infromation from the config file: "
217                               + "The user, host and device state infomation should be "
218                               + "in the order 'userInfo@hostInfo:deviceState'"
219                               + deviceEntry, aie);
220         } catch (Exception e) {
221             log.error("Error while parsing config information for the device entry: "
222                               + deviceEntry, e);
223         }
224         return device;
225     }
226
227     @Override
228     public void triggerProbe(DeviceId deviceId) {
229         // TODO Auto-generated method stub
230     }
231
232     @Override
233     public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
234
235     }
236
237     @Override
238     public boolean isReachable(DeviceId deviceId) {
239         NetconfDevice netconfDevice = netconfDeviceMap.get(deviceId);
240         if (netconfDevice == null) {
241             log.warn("BAD REQUEST: the requested device id: "
242                     + deviceId.toString()
243                     + "  is not associated to any NETCONF Device");
244             return false;
245         }
246         return netconfDevice.isReachable();
247     }
248
249     /**
250      * This class is intended to add or remove Configured Netconf Devices.
251      * Functionality relies on 'createFlag' and 'NetconfDevice' content. The
252      * functionality runs as a thread and dependening on the 'createFlag' value
253      * it will create or remove Device entry from the core.
254      */
255     private class DeviceCreator implements Runnable {
256
257         private NetconfDevice device;
258         private boolean createFlag;
259
260         public DeviceCreator(NetconfDevice device, boolean createFlag) {
261             this.device = device;
262             this.createFlag = createFlag;
263         }
264
265         @Override
266         public void run() {
267             if (createFlag) {
268                 log.info("Trying to create Device Info on ONOS core");
269                 advertiseDevices();
270             } else {
271                 log.info("Trying to remove Device Info on ONOS core");
272                 removeDevices();
273             }
274         }
275
276         /**
277          * For each Netconf Device, remove the entry from the device store.
278          */
279         private void removeDevices() {
280             if (device == null) {
281                 log.warn("The Request Netconf Device is null, cannot proceed further");
282                 return;
283             }
284             try {
285                 DeviceId did = getDeviceId();
286                 if (!netconfDeviceMap.containsKey(did)) {
287                     log.error("BAD Request: 'Currently device is not discovered, "
288                             + "so cannot remove/disconnect the device: "
289                             + device.deviceInfo() + "'");
290                     return;
291                 }
292                 providerService.deviceDisconnected(did);
293                 device.disconnect();
294                 netconfDeviceMap.remove(did);
295                 delay(EVENTINTERVAL);
296             } catch (URISyntaxException uriSyntaxExcpetion) {
297                 log.error("Syntax Error while creating URI for the device: "
298                                   + device.deviceInfo()
299                                   + " couldn't remove the device from the store",
300                           uriSyntaxExcpetion);
301             }
302         }
303
304         /**
305          * Initialize Netconf Device object, and notify core saying device
306          * connected.
307          */
308         private void advertiseDevices() {
309             try {
310                 if (device == null) {
311                     log.warn("The Request Netconf Device is null, cannot proceed further");
312                     return;
313                 }
314                 device.init();
315                 DeviceId did = getDeviceId();
316                 ChassisId cid = new ChassisId();
317                 DeviceDescription desc = new DefaultDeviceDescription(
318                                                                       did.uri(),
319                                                                       Device.Type.OTHER,
320                                                                       "", "",
321                                                                       "", "",
322                                                                       cid);
323                 log.info("Persisting Device" + did.uri().toString());
324
325                 netconfDeviceMap.put(did, device);
326                 providerService.deviceConnected(did, desc);
327                 log.info("Done with Device Info Creation on ONOS core. Device Info: "
328                         + device.deviceInfo() + " " + did.uri().toString());
329                 delay(EVENTINTERVAL);
330             } catch (URISyntaxException e) {
331                 log.error("Syntax Error while creating URI for the device: "
332                         + device.deviceInfo()
333                         + " couldn't persist the device onto the store", e);
334             } catch (SocketTimeoutException e) {
335                 log.error("Error while setting connection for the device: "
336                         + device.deviceInfo(), e);
337             } catch (IOException e) {
338                 log.error("Error while setting connection for the device: "
339                         + device.deviceInfo(), e);
340             } catch (Exception e) {
341                 log.error("Error while initializing session for the device: "
342                         + (device != null ? device.deviceInfo() : null), e);
343             }
344         }
345
346         /**
347          * This will build a device id for the device.
348          */
349         private DeviceId getDeviceId() throws URISyntaxException {
350             String additionalSSP = new StringBuilder(device.getUsername())
351                     .append("@").append(device.getSshHost()).append(":")
352                     .append(device.getSshPort()).toString();
353             DeviceId did = DeviceId.deviceId(new URI(SCHEME, additionalSSP,
354                                                      null));
355             return did;
356         }
357     }
358 }