2 * Copyright 2015 Open Networking Laboratory
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onosproject.provider.netconf.device.impl;
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;
24 import java.io.IOException;
25 import java.net.SocketTimeoutException;
27 import java.net.URISyntaxException;
28 import java.util.Dictionary;
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;
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;
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.
65 @Component(immediate = true)
66 public class NetconfDeviceProvider extends AbstractProvider
67 implements DeviceProvider {
69 private final Logger log = getLogger(NetconfDeviceProvider.class);
71 protected Map<DeviceId, NetconfDevice> netconfDeviceMap = new ConcurrentHashMap<DeviceId, NetconfDevice>();
73 private DeviceProviderService providerService;
75 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
76 protected DeviceProviderRegistry providerRegistry;
78 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
79 protected DeviceService deviceService;
81 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
82 protected ClusterService clusterService;
84 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
85 protected ComponentConfigService cfgService;
87 private ExecutorService deviceBuilder = Executors
88 .newFixedThreadPool(1, groupedThreads("onos/netconf", "device-creator"));
90 // Delay between events in ms.
91 private static final int EVENTINTERVAL = 5;
93 private static final String SCHEME = "netconf";
95 @Property(name = "devConfigs", value = "", label = "Instance-specific configurations")
96 private String devConfigs = null;
98 @Property(name = "devPasswords", value = "", label = "Instance-specific password")
99 private String devPasswords = null;
102 * Creates a provider with the supplier identifier.
104 public NetconfDeviceProvider() {
105 super(new ProviderId("netconf", "org.onosproject.provider.netconf"));
109 public void activate(ComponentContext context) {
110 cfgService.registerProperties(getClass());
111 providerService = providerRegistry.register(this);
117 public void deactivate(ComponentContext context) {
118 cfgService.unregisterProperties(getClass(), false);
120 for (Entry<DeviceId, NetconfDevice> deviceEntry : netconfDeviceMap
122 deviceBuilder.submit(new DeviceCreator(deviceEntry.getValue(),
125 deviceBuilder.awaitTermination(1000, TimeUnit.MILLISECONDS);
126 } catch (InterruptedException e) {
127 log.error("Device builder did not terminate");
129 deviceBuilder.shutdownNow();
130 netconfDeviceMap.clear();
131 providerRegistry.unregister(this);
132 providerService = null;
137 public void modified(ComponentContext context) {
138 if (context == null) {
139 log.info("No configuration file");
142 Dictionary<?, ?> properties = context.getProperties();
143 String deviceCfgValue = get(properties, "devConfigs");
144 log.info("Settings: devConfigs={}", deviceCfgValue);
145 if (!isNullOrEmpty(deviceCfgValue)) {
146 addOrRemoveDevicesConfig(deviceCfgValue);
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));
160 deviceBuilder.submit(new DeviceCreator(device, false));
166 private NetconfDevice processDeviceEntry(String deviceEntry) {
167 if (deviceEntry == null) {
168 log.info("No content for Device Entry, so cannot proceed further.");
171 log.info("Trying to convert Device Entry String: " + deviceEntry
172 + " to a Netconf Device Object");
173 NetconfDevice device = null;
175 String userInfo = deviceEntry.substring(0, deviceEntry
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];
186 hostPort = Integer.parseInt(infoSplit[1]);
187 } catch (NumberFormatException nfe) {
188 log.error("Bad Configuration Data: Failed to parse host port number string: "
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");
198 device = new NetconfDevice(hostIp, hostPort, username, password);
199 if (!isNullOrEmpty(deviceState)) {
200 if (deviceState.toUpperCase().equals(DeviceState.ACTIVE
202 device.setDeviceState(DeviceState.ACTIVE);
203 } else if (deviceState.toUpperCase()
204 .equals(DeviceState.INACTIVE.name())) {
205 device.setDeviceState(DeviceState.INACTIVE);
207 log.warn("Device State Information can not be empty, so marking the state as INVALID");
208 device.setDeviceState(DeviceState.INVALID);
211 log.warn("The device entry do not specify state information, so marking the state as INVALID");
212 device.setDeviceState(DeviceState.INVALID);
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'"
220 } catch (Exception e) {
221 log.error("Error while parsing config information for the device entry: "
228 public void triggerProbe(DeviceId deviceId) {
229 // TODO Auto-generated method stub
233 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
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");
246 return netconfDevice.isReachable();
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.
255 private class DeviceCreator implements Runnable {
257 private NetconfDevice device;
258 private boolean createFlag;
260 public DeviceCreator(NetconfDevice device, boolean createFlag) {
261 this.device = device;
262 this.createFlag = createFlag;
268 log.info("Trying to create Device Info on ONOS core");
271 log.info("Trying to remove Device Info on ONOS core");
277 * For each Netconf Device, remove the entry from the device store.
279 private void removeDevices() {
280 if (device == null) {
281 log.warn("The Request Netconf Device is null, cannot proceed further");
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() + "'");
292 providerService.deviceDisconnected(did);
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",
305 * Initialize Netconf Device object, and notify core saying device
308 private void advertiseDevices() {
310 if (device == null) {
311 log.warn("The Request Netconf Device is null, cannot proceed further");
315 DeviceId did = getDeviceId();
316 ChassisId cid = new ChassisId();
317 DeviceDescription desc = new DefaultDeviceDescription(
323 log.info("Persisting Device" + did.uri().toString());
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);
347 * This will build a device id for the device.
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,