blob: 496375769a5bd7c6a200fc42a1a4235abdd6448b [file] [log] [blame]
Andrea Campanella945ded22016-01-07 13:17:43 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-present Open Networking Laboratory
Andrea Campanella945ded22016-01-07 13:17:43 -08003 *
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
17package org.onosproject.provider.rest.device.impl;
18
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -060019import com.google.common.base.Objects;
Andrea Campanella59b549d2017-04-14 21:58:16 +020020import com.google.common.collect.ImmutableList;
Andrea Campanella945ded22016-01-07 13:17:43 -080021import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Deactivate;
24import org.apache.felix.scr.annotations.Reference;
25import org.apache.felix.scr.annotations.ReferenceCardinality;
26import org.onlab.packet.ChassisId;
Michal Machd8099742017-06-19 14:32:35 +020027import org.onlab.util.SharedScheduledExecutorService;
28import org.onlab.util.SharedScheduledExecutors;
Andrea Campanella945ded22016-01-07 13:17:43 -080029import org.onosproject.core.ApplicationId;
30import org.onosproject.core.CoreService;
31import org.onosproject.incubator.net.config.basics.ConfigException;
Marc De Leenheerb0d131c2016-03-01 20:34:59 -080032import org.onosproject.net.AnnotationKeys;
Andrea Campanella945ded22016-01-07 13:17:43 -080033import org.onosproject.net.DefaultAnnotations;
34import org.onosproject.net.Device;
35import org.onosproject.net.DeviceId;
36import org.onosproject.net.MastershipRole;
Saurav Dasa2d37502016-03-25 17:50:40 -070037import org.onosproject.net.PortNumber;
Andrea Campanella945ded22016-01-07 13:17:43 -080038import org.onosproject.net.SparseAnnotations;
Michele Santuaric372c222017-01-12 09:41:25 +010039import org.onosproject.net.behaviour.DevicesDiscovery;
Andrea Campanellad8d92db2016-01-14 16:24:41 -080040import org.onosproject.net.behaviour.PortDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -080041import org.onosproject.net.config.ConfigFactory;
42import org.onosproject.net.config.NetworkConfigEvent;
43import org.onosproject.net.config.NetworkConfigListener;
44import org.onosproject.net.config.NetworkConfigRegistry;
Andrea Campanella59b549d2017-04-14 21:58:16 +020045import org.onosproject.net.config.basics.SubjectFactories;
Andrea Campanella945ded22016-01-07 13:17:43 -080046import org.onosproject.net.device.DefaultDeviceDescription;
47import org.onosproject.net.device.DeviceDescription;
Andrea Campanella6c71a052016-04-22 11:56:31 -070048import org.onosproject.net.device.DeviceDescriptionDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -080049import org.onosproject.net.device.DeviceProvider;
50import org.onosproject.net.device.DeviceProviderRegistry;
51import org.onosproject.net.device.DeviceProviderService;
Andrea Campanella6c71a052016-04-22 11:56:31 -070052import org.onosproject.net.device.DeviceService;
Michal Machd8099742017-06-19 14:32:35 +020053import org.onosproject.net.device.PortStatistics;
54import org.onosproject.net.device.PortStatisticsDiscovery;
Michele Santuaric372c222017-01-12 09:41:25 +010055import org.onosproject.net.driver.DefaultDriverData;
56import org.onosproject.net.driver.DefaultDriverHandler;
57import org.onosproject.net.driver.Driver;
58import org.onosproject.net.driver.DriverData;
59import org.onosproject.net.driver.DriverHandler;
60import org.onosproject.net.driver.DriverService;
Andrea Campanella945ded22016-01-07 13:17:43 -080061import org.onosproject.net.provider.AbstractProvider;
62import org.onosproject.net.provider.ProviderId;
Andrea Campanella59b549d2017-04-14 21:58:16 +020063import org.onosproject.protocol.rest.DefaultRestSBDevice;
Andrea Campanella945ded22016-01-07 13:17:43 -080064import org.onosproject.protocol.rest.RestSBController;
65import org.onosproject.protocol.rest.RestSBDevice;
66import org.slf4j.Logger;
67
Andrea Campanellac6ecc632016-03-10 17:57:06 -080068import javax.ws.rs.ProcessingException;
Michal Machd8099742017-06-19 14:32:35 +020069import java.util.Collection;
Andrea Campanella945ded22016-01-07 13:17:43 -080070import java.util.HashSet;
Andrea Campanella59b549d2017-04-14 21:58:16 +020071import java.util.List;
Andrea Campanella945ded22016-01-07 13:17:43 -080072import java.util.Set;
Palash Kala4c71ee72017-05-24 17:43:59 +090073import java.util.concurrent.Callable;
74import java.util.concurrent.ExecutionException;
Andrea Campanella784ee0f2016-02-17 15:50:59 -080075import java.util.concurrent.ExecutorService;
76import java.util.concurrent.Executors;
Palash Kala4c71ee72017-05-24 17:43:59 +090077import java.util.concurrent.Future;
Michal Machd8099742017-06-19 14:32:35 +020078import java.util.concurrent.ScheduledFuture;
Palash Kala4c71ee72017-05-24 17:43:59 +090079import java.util.concurrent.TimeUnit;
80import java.util.concurrent.TimeoutException;
Andrea Campanella59b549d2017-04-14 21:58:16 +020081import java.util.stream.Collectors;
Andrea Campanella945ded22016-01-07 13:17:43 -080082
Michele Santuaric372c222017-01-12 09:41:25 +010083import static com.google.common.base.Preconditions.checkNotNull;
Andrea Campanella784ee0f2016-02-17 15:50:59 -080084import static org.onlab.util.Tools.groupedThreads;
Andrea Campanella945ded22016-01-07 13:17:43 -080085import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_ADDED;
86import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UPDATED;
87import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
88import static org.slf4j.LoggerFactory.getLogger;
89
90/**
91 * Provider for devices that use REST as means of configuration communication.
92 */
93@Component(immediate = true)
94public class RestDeviceProvider extends AbstractProvider
95 implements DeviceProvider {
96 private static final String APP_NAME = "org.onosproject.restsb";
Andrea Campanella59b549d2017-04-14 21:58:16 +020097 protected static final String REST = "rest";
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -060098 private static final String JSON = "json";
Andrea Campanella945ded22016-01-07 13:17:43 -080099 private static final String PROVIDER = "org.onosproject.provider.rest.device";
100 private static final String IPADDRESS = "ipaddress";
Andrea Campanella2947e622016-01-27 09:23:46 -0800101 private static final String HTTPS = "https";
102 private static final String AUTHORIZATION_PROPERTY = "authorization";
103 private static final String BASIC_AUTH_PREFIX = "Basic ";
104 private static final String URL_SEPARATOR = "://";
Michele Santuaric372c222017-01-12 09:41:25 +0100105 protected static final String ISNOTNULL = "Rest device is not null";
106 private static final String UNKNOWN = "unknown";
Palash Kala4c71ee72017-05-24 17:43:59 +0900107 private static final int REST_TIMEOUT_SEC = 5;
Michal Machd8099742017-06-19 14:32:35 +0200108 private static final int DEFAULT_POLL_FREQUENCY_SECONDS = 30;
Andrea Campanella945ded22016-01-07 13:17:43 -0800109 private final Logger log = getLogger(getClass());
110
111 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
112 protected DeviceProviderRegistry providerRegistry;
113
114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
115 protected RestSBController controller;
116
117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
118 protected NetworkConfigRegistry cfgService;
119
120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
121 protected CoreService coreService;
122
Andrea Campanellad8d92db2016-01-14 16:24:41 -0800123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Andrea Campanella6c71a052016-04-22 11:56:31 -0700124 protected DeviceService deviceService;
Andrea Campanellad8d92db2016-01-14 16:24:41 -0800125
Michele Santuaric372c222017-01-12 09:41:25 +0100126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
127 protected DriverService driverService;
128
Andrea Campanella945ded22016-01-07 13:17:43 -0800129
130 private DeviceProviderService providerService;
Michele Santuaric372c222017-01-12 09:41:25 +0100131 private ApplicationId appId;
Andrea Campanella945ded22016-01-07 13:17:43 -0800132
Andrea Campanella784ee0f2016-02-17 15:50:59 -0800133 private final ExecutorService executor =
Andrea Campanella90f044f2016-03-02 09:14:57 -0800134 Executors.newFixedThreadPool(5, groupedThreads("onos/restsbprovider", "device-installer-%d", log));
Michal Machd8099742017-06-19 14:32:35 +0200135 private SharedScheduledExecutorService portStatisticsExecutor = SharedScheduledExecutors.getPoolThreadExecutor();
Andrea Campanella784ee0f2016-02-17 15:50:59 -0800136
Andrea Campanella59b549d2017-04-14 21:58:16 +0200137 protected final List<ConfigFactory> factories = ImmutableList.of(
Andrea Campanella945ded22016-01-07 13:17:43 -0800138 new ConfigFactory<ApplicationId, RestProviderConfig>(APP_SUBJECT_FACTORY,
139 RestProviderConfig.class,
Palash Kalac3ffad92017-06-09 21:18:19 +0900140 "rest_devices",
Andrea Campanella945ded22016-01-07 13:17:43 -0800141 true) {
142 @Override
143 public RestProviderConfig createConfig() {
144 return new RestProviderConfig();
145 }
Andrea Campanella59b549d2017-04-14 21:58:16 +0200146 },
147 new ConfigFactory<DeviceId, RestDeviceConfig>(SubjectFactories.DEVICE_SUBJECT_FACTORY,
148 RestDeviceConfig.class,
149 REST) {
150 @Override
151 public RestDeviceConfig createConfig() {
152 return new RestDeviceConfig();
153 }
154 });
155
Andrea Campanella945ded22016-01-07 13:17:43 -0800156 private final NetworkConfigListener cfgLister = new InternalNetworkConfigListener();
Andrea Campanella945ded22016-01-07 13:17:43 -0800157
Andrea Campanella784ee0f2016-02-17 15:50:59 -0800158 private Set<DeviceId> addedDevices = new HashSet<>();
Michal Machd8099742017-06-19 14:32:35 +0200159 private ScheduledFuture<?> scheduledTask;
Andrea Campanella784ee0f2016-02-17 15:50:59 -0800160
Andrea Campanella945ded22016-01-07 13:17:43 -0800161
162 @Activate
163 public void activate() {
164 appId = coreService.registerApplication(APP_NAME);
165 providerService = providerRegistry.register(this);
Andrea Campanella59b549d2017-04-14 21:58:16 +0200166 factories.forEach(cfgService::registerConfigFactory);
Andrea Campanella945ded22016-01-07 13:17:43 -0800167 cfgService.addListener(cfgLister);
Andrea Campanella59b549d2017-04-14 21:58:16 +0200168 executor.execute(RestDeviceProvider.this::createAndConnectDevices);
169 executor.execute(RestDeviceProvider.this::createDevices);
Michal Machd8099742017-06-19 14:32:35 +0200170 scheduledTask = schedulePolling();
Andrea Campanella945ded22016-01-07 13:17:43 -0800171 log.info("Started");
172 }
173
Andrea Campanella945ded22016-01-07 13:17:43 -0800174 @Deactivate
175 public void deactivate() {
Andrea Campanella86294db2016-03-07 11:42:49 -0800176 cfgService.removeListener(cfgLister);
177 controller.getDevices().keySet().forEach(this::deviceRemoved);
Andrea Campanella945ded22016-01-07 13:17:43 -0800178 providerRegistry.unregister(this);
179 providerService = null;
Andrea Campanella59b549d2017-04-14 21:58:16 +0200180 factories.forEach(cfgService::unregisterConfigFactory);
Michal Machd8099742017-06-19 14:32:35 +0200181 scheduledTask.cancel(true);
Andrea Campanella945ded22016-01-07 13:17:43 -0800182 log.info("Stopped");
183 }
184
185 public RestDeviceProvider() {
186 super(new ProviderId(REST, PROVIDER));
187 }
188
189 @Override
190 public void triggerProbe(DeviceId deviceId) {
191 // TODO: This will be implemented later.
192 log.info("Triggering probe on device {}", deviceId);
193 }
194
195 @Override
196 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
197 // TODO: This will be implemented later.
198 }
199
200
201 @Override
202 public boolean isReachable(DeviceId deviceId) {
203 RestSBDevice restDevice = controller.getDevice(deviceId);
204 if (restDevice == null) {
Michele Santuaric372c222017-01-12 09:41:25 +0100205 restDevice = controller.getProxySBDevice(deviceId);
206 if (restDevice == null) {
207 log.debug("the requested device id: " +
208 deviceId.toString() +
209 " is not associated to any REST or REST " +
210 "proxy Device");
211 return false;
212 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800213 }
214 return restDevice.isActive();
215 }
216
Michele Santuaric372c222017-01-12 09:41:25 +0100217 private void deviceAdded(RestSBDevice restSBDev) {
218 checkNotNull(restSBDev, ISNOTNULL);
219
220 //check if the server is controlling a single or multiple devices
221 if (restSBDev.isProxy()) {
222
223 Driver driver = driverService.getDriver(restSBDev.manufacturer().get(),
224 restSBDev.hwVersion().get(),
225 restSBDev.swVersion().get());
226
227 if (driver != null && driver.hasBehaviour(DevicesDiscovery.class)) {
228
229 //Creates the driver to communicate with the server
230 DevicesDiscovery devicesDiscovery =
231 devicesDiscovery(restSBDev, driver);
232 Set<DeviceId> deviceIds = devicesDiscovery.deviceIds();
233 restSBDev.setActive(true);
234 deviceIds.stream().forEach(deviceId -> {
235 controller.addProxiedDevice(deviceId, restSBDev);
236 DeviceDescription devDesc =
237 devicesDiscovery.deviceDetails(deviceId);
238 checkNotNull(devDesc,
239 "deviceDescription cannot be null");
240 providerService.deviceConnected(
241 deviceId, mergeAnn(restSBDev.deviceId(), devDesc));
242
243 if (driver.hasBehaviour(DeviceDescriptionDiscovery.class)) {
244 DriverHandler h = driverService.createHandler(deviceId);
245 DeviceDescriptionDiscovery devDisc =
246 h.behaviour(DeviceDescriptionDiscovery.class);
247 providerService.updatePorts(deviceId,
248 devDisc.discoverPortDetails());
249 }
250
251 checkAndUpdateDevice(deviceId);
252 addedDevices.add(deviceId);
253 });
254 } else {
255 log.warn("Driver not found for {}", restSBDev);
256 }
257 } else {
258 DeviceId deviceId = restSBDev.deviceId();
259 ChassisId cid = new ChassisId();
260 String ipAddress = restSBDev.ip().toString();
261 SparseAnnotations annotations = DefaultAnnotations.builder()
262 .set(IPADDRESS, ipAddress)
263 .set(AnnotationKeys.PROTOCOL, REST.toUpperCase())
264 .build();
265 DeviceDescription deviceDescription = new DefaultDeviceDescription(
266 deviceId.uri(),
267 Device.Type.SWITCH,
268 UNKNOWN, UNKNOWN,
269 UNKNOWN, UNKNOWN,
270 cid,
271 annotations);
272 restSBDev.setActive(true);
273 providerService.deviceConnected(deviceId, deviceDescription);
274 checkAndUpdateDevice(deviceId);
275 addedDevices.add(deviceId);
276 }
277 }
278
279 private DefaultDeviceDescription mergeAnn(DeviceId devId, DeviceDescription desc) {
280 return new DefaultDeviceDescription(
281 desc,
282 DefaultAnnotations.merge(
283 DefaultAnnotations.builder()
284 .set(AnnotationKeys.PROTOCOL, REST.toUpperCase())
285 // The rest server added as annotation to the device
286 .set(AnnotationKeys.REST_SERVER, devId.toString())
287 .build(),
288 desc.annotations()));
289 }
290
291 private DevicesDiscovery devicesDiscovery(RestSBDevice restSBDevice, Driver driver) {
292 DriverData driverData = new DefaultDriverData(driver, restSBDevice.deviceId());
293 DevicesDiscovery devicesDiscovery = driver.createBehaviour(driverData,
294 DevicesDiscovery.class);
295 devicesDiscovery.setHandler(new DefaultDriverHandler(driverData));
296 return devicesDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -0800297 }
298
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600299 private void checkAndUpdateDevice(DeviceId deviceId) {
300 if (deviceService.getDevice(deviceId) == null) {
301 log.warn("Device {} has not been added to store, " +
302 "maybe due to a problem in connectivity", deviceId);
303 } else {
304 boolean isReachable = isReachable(deviceId);
305 if (isReachable && deviceService.isAvailable(deviceId)) {
306 Device device = deviceService.getDevice(deviceId);
307 if (device.is(DeviceDescriptionDiscovery.class)) {
Michele Santuaric372c222017-01-12 09:41:25 +0100308 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
309 device.as(DeviceDescriptionDiscovery.class);
310 DeviceDescription updatedDeviceDescription =
311 deviceDescriptionDiscovery.discoverDeviceDetails();
312 if (updatedDeviceDescription != null &&
313 !descriptionEquals(device, updatedDeviceDescription)) {
314 providerService.deviceConnected(
315 deviceId,
316 new DefaultDeviceDescription(
317 updatedDeviceDescription, true,
318 updatedDeviceDescription.annotations()));
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600319 //if ports are not discovered, retry the discovery
320 if (deviceService.getPorts(deviceId).isEmpty()) {
321 discoverPorts(deviceId);
322 }
323 }
324 } else {
325 log.warn("No DeviceDescriptionDiscovery behaviour for device {}", deviceId);
326 }
327 } else if (!isReachable && deviceService.isAvailable(deviceId)) {
328 providerService.deviceDisconnected(deviceId);
329 }
330 }
331 }
332
333 private boolean descriptionEquals(Device device, DeviceDescription updatedDeviceDescription) {
Michele Santuarid2c8f212017-01-09 18:23:45 +0100334 return Objects.equal(device.id().uri(), updatedDeviceDescription.deviceUri())
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600335 && Objects.equal(device.type(), updatedDeviceDescription.type())
336 && Objects.equal(device.manufacturer(), updatedDeviceDescription.manufacturer())
337 && Objects.equal(device.hwVersion(), updatedDeviceDescription.hwVersion())
338 && Objects.equal(device.swVersion(), updatedDeviceDescription.swVersion())
339 && Objects.equal(device.serialNumber(), updatedDeviceDescription.serialNumber())
340 && Objects.equal(device.chassisId(), updatedDeviceDescription.chassisId())
341 && Objects.equal(device.annotations(), updatedDeviceDescription.annotations());
342 }
343
Andrea Campanella86294db2016-03-07 11:42:49 -0800344 private void deviceRemoved(DeviceId deviceId) {
Michele Santuaric372c222017-01-12 09:41:25 +0100345 checkNotNull(deviceId, ISNOTNULL);
Andrea Campanella945ded22016-01-07 13:17:43 -0800346 providerService.deviceDisconnected(deviceId);
Michele Santuaric372c222017-01-12 09:41:25 +0100347 controller.getProxiedDevices(deviceId).stream().forEach(device -> {
348 controller.removeProxiedDevice(device);
349 providerService.deviceDisconnected(device);
350 });
Andrea Campanella86294db2016-03-07 11:42:49 -0800351 controller.removeDevice(deviceId);
Andrea Campanella945ded22016-01-07 13:17:43 -0800352 }
353
Andrea Campanella59b549d2017-04-14 21:58:16 +0200354 //Method to connect devices provided via net-cfg under devices/ tree
355 private void createAndConnectDevices() {
356 Set<DeviceId> deviceSubjects =
357 cfgService.getSubjects(DeviceId.class, RestDeviceConfig.class);
358 connectDevices(deviceSubjects.stream()
359 .filter(deviceId -> deviceService.getDevice(deviceId) == null)
360 .map(deviceId -> {
361 RestDeviceConfig config =
362 cfgService.getConfig(deviceId, RestDeviceConfig.class);
363 RestSBDevice device = new DefaultRestSBDevice(config.ip(),
364 config.port(),
365 config.username(),
366 config.password(),
367 config.protocol(),
368 config.url(),
369 false, config.testUrl(),
370 config.manufacturer(),
371 config.hwVersion(),
372 config.swVersion());
373 return device;
374
375 }).collect(Collectors.toSet()));
376 }
377
378 //Old method to register devices provided via net-cfg under apps/rest/ tree
379 private void createDevices() {
Andrea Campanella945ded22016-01-07 13:17:43 -0800380 RestProviderConfig cfg = cfgService.getConfig(appId, RestProviderConfig.class);
381 try {
382 if (cfg != null && cfg.getDevicesAddresses() != null) {
Andrea Campanella59b549d2017-04-14 21:58:16 +0200383 connectDevices(cfg.getDevicesAddresses());
384
Andrea Campanella945ded22016-01-07 13:17:43 -0800385 }
386 } catch (ConfigException e) {
387 log.error("Configuration error {}", e);
388 }
Andrea Campanella2947e622016-01-27 09:23:46 -0800389 log.debug("REST Devices {}", controller.getDevices());
Andrea Campanella784ee0f2016-02-17 15:50:59 -0800390 addedDevices.clear();
Andrea Campanella945ded22016-01-07 13:17:43 -0800391 }
392
Andrea Campanella59b549d2017-04-14 21:58:16 +0200393 private void connectDevices(Set<RestSBDevice> devices) {
394 //Precomputing the devices to be removed
395 Set<RestSBDevice> toBeRemoved = new HashSet<>(controller.getDevices().values());
396 toBeRemoved.removeAll(devices);
397 //Adding new devices
398 devices.stream()
399 .filter(device -> {
400 device.setActive(false);
401 controller.addDevice(device);
402 return testDeviceConnection(device);
403 })
404 .forEach(device -> {
405 deviceAdded(device);
406 });
407 //Removing devices not wanted anymore
408 toBeRemoved.forEach(device -> deviceRemoved(device.deviceId()));
409 }
410
Michal Machd8099742017-06-19 14:32:35 +0200411 private ScheduledFuture schedulePolling() {
412 return portStatisticsExecutor.scheduleAtFixedRate(this::executePortStatisticsUpdate,
413 DEFAULT_POLL_FREQUENCY_SECONDS / 2,
414 DEFAULT_POLL_FREQUENCY_SECONDS,
415 TimeUnit.SECONDS);
416 }
417
418 private void executePortStatisticsUpdate() {
419 controller.getDevices().keySet().forEach(this::updatePortStatistics);
420 }
421
422 private void updatePortStatistics(DeviceId deviceId) {
423 Device device = deviceService.getDevice(deviceId);
424 checkNotNull(device, "device cannot be null");
425
426 if (device.is(PortStatisticsDiscovery.class)) {
427 PortStatisticsDiscovery portStatisticsDiscovery = device.as(PortStatisticsDiscovery.class);
428 Collection<PortStatistics> portStatistics = portStatisticsDiscovery.discoverPortStatistics();
429 if (portStatistics != null && !portStatistics.isEmpty()) {
430 providerService.updatePortStatistics(deviceId, portStatistics);
431 }
432 } else {
433 log.debug("No port statistics getter behaviour for device {}", deviceId);
434 }
435 }
436
Andrea Campanella6c71a052016-04-22 11:56:31 -0700437 private void discoverPorts(DeviceId deviceId) {
438 Device device = deviceService.getDevice(deviceId);
439 //TODO remove when PortDiscovery is removed from master
440 if (device.is(PortDiscovery.class)) {
441 PortDiscovery portConfig = device.as(PortDiscovery.class);
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600442 providerService.updatePorts(deviceId, portConfig.getPorts());
443 } else {
Andrea Campanella6c71a052016-04-22 11:56:31 -0700444 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
445 device.as(DeviceDescriptionDiscovery.class);
446 providerService.updatePorts(deviceId, deviceDescriptionDiscovery.discoverPortDetails());
Andrea Campanella6c71a052016-04-22 11:56:31 -0700447 }
448 }
449
Michele Santuaric372c222017-01-12 09:41:25 +0100450 private boolean testDeviceConnection(RestSBDevice dev) {
Andrea Campanella945ded22016-01-07 13:17:43 -0800451 try {
Palash Kala4c71ee72017-05-24 17:43:59 +0900452 Callable<Boolean> connectionSuccess;
453
Michele Santuaric372c222017-01-12 09:41:25 +0100454 if (dev.testUrl().isPresent()) {
Palash Kala4c71ee72017-05-24 17:43:59 +0900455 connectionSuccess = new Callable<Boolean>() {
456 @Override
457 public Boolean call() throws Exception {
458 return controller
459 .get(dev.deviceId(), dev.testUrl().get(), JSON) != null;
460 }
461 };
462 } else {
463 connectionSuccess = new Callable<Boolean>() {
464 @Override
465 public Boolean call() throws Exception {
466 return controller.get(dev.deviceId(), "", JSON) != null;
467 }
468 };
Michele Santuaric372c222017-01-12 09:41:25 +0100469 }
Palash Kala4c71ee72017-05-24 17:43:59 +0900470
471 Future<Boolean> future = executor.submit(connectionSuccess);
472 try {
473 Boolean result = future.get(REST_TIMEOUT_SEC, TimeUnit.SECONDS);
474 return result;
475 } catch (TimeoutException ex) {
476 log.warn("Connection to device {} timed out", dev.deviceId());
477 return false;
478 } catch (InterruptedException ex) {
479 log.warn("Connection to device {} interrupted", dev.deviceId());
480 return false;
481 } catch (ExecutionException ex) {
482 log.warn("Connection to device {} had a execution exception", dev.deviceId());
483 return false;
484 }
Michele Santuaric372c222017-01-12 09:41:25 +0100485
Andrea Campanellac6ecc632016-03-10 17:57:06 -0800486 } catch (ProcessingException e) {
Michele Santuaric372c222017-01-12 09:41:25 +0100487 log.warn("Cannot connect to device {}", dev, e);
Andrea Campanella945ded22016-01-07 13:17:43 -0800488 }
489 return false;
490 }
491
492 private class InternalNetworkConfigListener implements NetworkConfigListener {
Andrea Campanella945ded22016-01-07 13:17:43 -0800493 @Override
494 public void event(NetworkConfigEvent event) {
Andrea Campanella59b549d2017-04-14 21:58:16 +0200495 if (event.configClass().equals(RestDeviceConfig.class)) {
496 executor.execute(RestDeviceProvider.this::createAndConnectDevices);
497 } else {
498 log.warn("Injecting device via this Json is deprecated, " +
499 "please put configuration under devices/");
500 executor.execute(RestDeviceProvider.this::createDevices);
501 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800502 }
503
504 @Override
505 public boolean isRelevant(NetworkConfigEvent event) {
Andrea Campanella59b549d2017-04-14 21:58:16 +0200506 return (event.configClass().equals(RestDeviceConfig.class) ||
507 event.configClass().equals(RestProviderConfig.class)) &&
Andrea Campanella945ded22016-01-07 13:17:43 -0800508 (event.type() == CONFIG_ADDED ||
509 event.type() == CONFIG_UPDATED);
510 }
511 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700512
513 @Override
514 public void changePortState(DeviceId deviceId, PortNumber portNumber,
515 boolean enable) {
516 // TODO if required
517 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800518}