blob: 3e97a3d1b4f7f0a4b7a9260cc171f4b1d1501bdc [file] [log] [blame]
Andrea Campanella945ded22016-01-07 13:17:43 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
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;
Yuta HIGUCHIfc667052017-12-05 18:17:22 -080027import org.onlab.util.SharedExecutors;
Michal Machd8099742017-06-19 14:32:35 +020028import org.onlab.util.SharedScheduledExecutorService;
29import org.onlab.util.SharedScheduledExecutors;
Andrea Campanella945ded22016-01-07 13:17:43 -080030import org.onosproject.core.ApplicationId;
31import org.onosproject.core.CoreService;
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;
fahadnaeemkhan02ffa712017-12-01 19:49:45 -080040import org.onosproject.net.behaviour.PortAdmin;
Andrea Campanellad8d92db2016-01-14 16:24:41 -080041import org.onosproject.net.behaviour.PortDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -080042import org.onosproject.net.config.ConfigFactory;
43import org.onosproject.net.config.NetworkConfigEvent;
44import org.onosproject.net.config.NetworkConfigListener;
45import org.onosproject.net.config.NetworkConfigRegistry;
Andrea Campanella59b549d2017-04-14 21:58:16 +020046import org.onosproject.net.config.basics.SubjectFactories;
Andrea Campanella945ded22016-01-07 13:17:43 -080047import org.onosproject.net.device.DefaultDeviceDescription;
48import org.onosproject.net.device.DeviceDescription;
Andrea Campanella6c71a052016-04-22 11:56:31 -070049import org.onosproject.net.device.DeviceDescriptionDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -080050import org.onosproject.net.device.DeviceProvider;
51import org.onosproject.net.device.DeviceProviderRegistry;
52import org.onosproject.net.device.DeviceProviderService;
Andrea Campanella6c71a052016-04-22 11:56:31 -070053import org.onosproject.net.device.DeviceService;
Michal Machd8099742017-06-19 14:32:35 +020054import org.onosproject.net.device.PortStatistics;
55import org.onosproject.net.device.PortStatisticsDiscovery;
Michele Santuaric372c222017-01-12 09:41:25 +010056import org.onosproject.net.driver.DefaultDriverData;
57import org.onosproject.net.driver.DefaultDriverHandler;
58import org.onosproject.net.driver.Driver;
59import org.onosproject.net.driver.DriverData;
60import org.onosproject.net.driver.DriverHandler;
61import org.onosproject.net.driver.DriverService;
Andrea Campanella945ded22016-01-07 13:17:43 -080062import org.onosproject.net.provider.AbstractProvider;
63import org.onosproject.net.provider.ProviderId;
Andrea Campanella59b549d2017-04-14 21:58:16 +020064import org.onosproject.protocol.rest.DefaultRestSBDevice;
Andrea Campanella945ded22016-01-07 13:17:43 -080065import org.onosproject.protocol.rest.RestSBController;
66import org.onosproject.protocol.rest.RestSBDevice;
67import org.slf4j.Logger;
68
Andrea Campanellac6ecc632016-03-10 17:57:06 -080069import javax.ws.rs.ProcessingException;
Michal Mach67acb692017-06-21 12:05:36 +020070import javax.ws.rs.core.MediaType;
Michal Machd8099742017-06-19 14:32:35 +020071import java.util.Collection;
Andrea Campanella945ded22016-01-07 13:17:43 -080072import java.util.HashSet;
Andrea Campanella59b549d2017-04-14 21:58:16 +020073import java.util.List;
Andrea Campanella945ded22016-01-07 13:17:43 -080074import java.util.Set;
Palash Kala4c71ee72017-05-24 17:43:59 +090075import java.util.concurrent.Callable;
fahadnaeemkhan02ffa712017-12-01 19:49:45 -080076import java.util.concurrent.CompletableFuture;
Palash Kala4c71ee72017-05-24 17:43:59 +090077import java.util.concurrent.ExecutionException;
Andrea Campanella784ee0f2016-02-17 15:50:59 -080078import java.util.concurrent.ExecutorService;
79import java.util.concurrent.Executors;
Palash Kala4c71ee72017-05-24 17:43:59 +090080import java.util.concurrent.Future;
Michal Machd8099742017-06-19 14:32:35 +020081import java.util.concurrent.ScheduledFuture;
Palash Kala4c71ee72017-05-24 17:43:59 +090082import java.util.concurrent.TimeUnit;
83import java.util.concurrent.TimeoutException;
Andrea Campanella59b549d2017-04-14 21:58:16 +020084import java.util.stream.Collectors;
Andrea Campanella945ded22016-01-07 13:17:43 -080085
Michele Santuaric372c222017-01-12 09:41:25 +010086import static com.google.common.base.Preconditions.checkNotNull;
Andrea Campanella784ee0f2016-02-17 15:50:59 -080087import static org.onlab.util.Tools.groupedThreads;
Andrea Campanella945ded22016-01-07 13:17:43 -080088import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_ADDED;
Yuta HIGUCHIfc667052017-12-05 18:17:22 -080089import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_REMOVED;
Andrea Campanella945ded22016-01-07 13:17:43 -080090import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UPDATED;
Andrea Campanella945ded22016-01-07 13:17:43 -080091import static org.slf4j.LoggerFactory.getLogger;
92
93/**
94 * Provider for devices that use REST as means of configuration communication.
95 */
96@Component(immediate = true)
97public class RestDeviceProvider extends AbstractProvider
98 implements DeviceProvider {
99 private static final String APP_NAME = "org.onosproject.restsb";
Andrea Campanella59b549d2017-04-14 21:58:16 +0200100 protected static final String REST = "rest";
Andrea Campanella945ded22016-01-07 13:17:43 -0800101 private static final String PROVIDER = "org.onosproject.provider.rest.device";
102 private static final String IPADDRESS = "ipaddress";
Michal Mach67acb692017-06-21 12:05:36 +0200103 private static final String ISNOTNULL = "Rest device is not null";
Michele Santuaric372c222017-01-12 09:41:25 +0100104 private static final String UNKNOWN = "unknown";
Palash Kala4c71ee72017-05-24 17:43:59 +0900105 private static final int REST_TIMEOUT_SEC = 5;
Michal Machd8099742017-06-19 14:32:35 +0200106 private static final int DEFAULT_POLL_FREQUENCY_SECONDS = 30;
Georgios Katsikas6a4d1662017-07-27 13:22:31 +0200107 private static final int EXECUTOR_THREAD_POOL_SIZE = 8;
Andrea Campanella945ded22016-01-07 13:17:43 -0800108 private final Logger log = getLogger(getClass());
109
110 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
111 protected DeviceProviderRegistry providerRegistry;
112
113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
114 protected RestSBController controller;
115
116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
117 protected NetworkConfigRegistry cfgService;
118
119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
120 protected CoreService coreService;
121
Andrea Campanellad8d92db2016-01-14 16:24:41 -0800122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Andrea Campanella6c71a052016-04-22 11:56:31 -0700123 protected DeviceService deviceService;
Andrea Campanellad8d92db2016-01-14 16:24:41 -0800124
Michele Santuaric372c222017-01-12 09:41:25 +0100125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
126 protected DriverService driverService;
127
Andrea Campanella945ded22016-01-07 13:17:43 -0800128 private DeviceProviderService providerService;
Michele Santuaric372c222017-01-12 09:41:25 +0100129 private ApplicationId appId;
Andrea Campanella945ded22016-01-07 13:17:43 -0800130
Michal Mach13072e22017-06-21 09:12:24 +0200131 private ExecutorService executor;
Michal Mach67acb692017-06-21 12:05:36 +0200132 private final SharedScheduledExecutorService portStatisticsExecutor =
133 SharedScheduledExecutors.getPoolThreadExecutor();
Andrea Campanella784ee0f2016-02-17 15:50:59 -0800134
Michal Mach67acb692017-06-21 12:05:36 +0200135 private final List<ConfigFactory> factories = ImmutableList.of(
Andrea Campanella59b549d2017-04-14 21:58:16 +0200136 new ConfigFactory<DeviceId, RestDeviceConfig>(SubjectFactories.DEVICE_SUBJECT_FACTORY,
137 RestDeviceConfig.class,
138 REST) {
139 @Override
140 public RestDeviceConfig createConfig() {
141 return new RestDeviceConfig();
142 }
143 });
144
Michal Mach67acb692017-06-21 12:05:36 +0200145 private final NetworkConfigListener configListener = new InternalNetworkConfigListener();
Andrea Campanella945ded22016-01-07 13:17:43 -0800146
Michal Machd8099742017-06-19 14:32:35 +0200147 private ScheduledFuture<?> scheduledTask;
Andrea Campanella784ee0f2016-02-17 15:50:59 -0800148
Andrea Campanella945ded22016-01-07 13:17:43 -0800149
150 @Activate
151 public void activate() {
152 appId = coreService.registerApplication(APP_NAME);
153 providerService = providerRegistry.register(this);
Andrea Campanella59b549d2017-04-14 21:58:16 +0200154 factories.forEach(cfgService::registerConfigFactory);
Georgios Katsikas6a4d1662017-07-27 13:22:31 +0200155 executor = Executors.newFixedThreadPool(
156 EXECUTOR_THREAD_POOL_SIZE, groupedThreads("onos/restsbprovider", "device-installer-%d", log)
157 );
Michal Mach67acb692017-06-21 12:05:36 +0200158 cfgService.addListener(configListener);
Andrea Campanella59b549d2017-04-14 21:58:16 +0200159 executor.execute(RestDeviceProvider.this::createAndConnectDevices);
Michal Machd8099742017-06-19 14:32:35 +0200160 scheduledTask = schedulePolling();
Andrea Campanella945ded22016-01-07 13:17:43 -0800161 log.info("Started");
162 }
163
Andrea Campanella945ded22016-01-07 13:17:43 -0800164 @Deactivate
165 public void deactivate() {
Michal Mach67acb692017-06-21 12:05:36 +0200166 cfgService.removeListener(configListener);
Andrea Campanella86294db2016-03-07 11:42:49 -0800167 controller.getDevices().keySet().forEach(this::deviceRemoved);
Andrea Campanella945ded22016-01-07 13:17:43 -0800168 providerRegistry.unregister(this);
169 providerService = null;
Andrea Campanella59b549d2017-04-14 21:58:16 +0200170 factories.forEach(cfgService::unregisterConfigFactory);
Michal Machd8099742017-06-19 14:32:35 +0200171 scheduledTask.cancel(true);
Lukasz Ryba4da35c52017-06-20 09:14:11 +0200172 executor.shutdown();
Andrea Campanella945ded22016-01-07 13:17:43 -0800173 log.info("Stopped");
174 }
175
176 public RestDeviceProvider() {
177 super(new ProviderId(REST, PROVIDER));
178 }
179
180 @Override
181 public void triggerProbe(DeviceId deviceId) {
182 // TODO: This will be implemented later.
183 log.info("Triggering probe on device {}", deviceId);
184 }
185
186 @Override
187 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
188 // TODO: This will be implemented later.
189 }
190
Andrea Campanella945ded22016-01-07 13:17:43 -0800191 @Override
192 public boolean isReachable(DeviceId deviceId) {
193 RestSBDevice restDevice = controller.getDevice(deviceId);
194 if (restDevice == null) {
Michele Santuaric372c222017-01-12 09:41:25 +0100195 restDevice = controller.getProxySBDevice(deviceId);
196 if (restDevice == null) {
197 log.debug("the requested device id: " +
198 deviceId.toString() +
199 " is not associated to any REST or REST " +
200 "proxy Device");
201 return false;
202 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800203 }
204 return restDevice.isActive();
205 }
206
Michele Santuaric372c222017-01-12 09:41:25 +0100207 private void deviceAdded(RestSBDevice restSBDev) {
208 checkNotNull(restSBDev, ISNOTNULL);
209
210 //check if the server is controlling a single or multiple devices
211 if (restSBDev.isProxy()) {
212
213 Driver driver = driverService.getDriver(restSBDev.manufacturer().get(),
214 restSBDev.hwVersion().get(),
215 restSBDev.swVersion().get());
216
217 if (driver != null && driver.hasBehaviour(DevicesDiscovery.class)) {
218
219 //Creates the driver to communicate with the server
220 DevicesDiscovery devicesDiscovery =
221 devicesDiscovery(restSBDev, driver);
222 Set<DeviceId> deviceIds = devicesDiscovery.deviceIds();
223 restSBDev.setActive(true);
Michal Mach67acb692017-06-21 12:05:36 +0200224 deviceIds.forEach(deviceId -> {
Michele Santuaric372c222017-01-12 09:41:25 +0100225 controller.addProxiedDevice(deviceId, restSBDev);
226 DeviceDescription devDesc =
227 devicesDiscovery.deviceDetails(deviceId);
228 checkNotNull(devDesc,
229 "deviceDescription cannot be null");
230 providerService.deviceConnected(
231 deviceId, mergeAnn(restSBDev.deviceId(), devDesc));
232
233 if (driver.hasBehaviour(DeviceDescriptionDiscovery.class)) {
234 DriverHandler h = driverService.createHandler(deviceId);
235 DeviceDescriptionDiscovery devDisc =
236 h.behaviour(DeviceDescriptionDiscovery.class);
237 providerService.updatePorts(deviceId,
238 devDisc.discoverPortDetails());
239 }
240
241 checkAndUpdateDevice(deviceId);
Michele Santuaric372c222017-01-12 09:41:25 +0100242 });
243 } else {
244 log.warn("Driver not found for {}", restSBDev);
245 }
246 } else {
247 DeviceId deviceId = restSBDev.deviceId();
248 ChassisId cid = new ChassisId();
249 String ipAddress = restSBDev.ip().toString();
250 SparseAnnotations annotations = DefaultAnnotations.builder()
251 .set(IPADDRESS, ipAddress)
252 .set(AnnotationKeys.PROTOCOL, REST.toUpperCase())
253 .build();
254 DeviceDescription deviceDescription = new DefaultDeviceDescription(
255 deviceId.uri(),
256 Device.Type.SWITCH,
257 UNKNOWN, UNKNOWN,
258 UNKNOWN, UNKNOWN,
259 cid,
260 annotations);
261 restSBDev.setActive(true);
262 providerService.deviceConnected(deviceId, deviceDescription);
263 checkAndUpdateDevice(deviceId);
Michele Santuaric372c222017-01-12 09:41:25 +0100264 }
265 }
266
267 private DefaultDeviceDescription mergeAnn(DeviceId devId, DeviceDescription desc) {
268 return new DefaultDeviceDescription(
269 desc,
270 DefaultAnnotations.merge(
271 DefaultAnnotations.builder()
272 .set(AnnotationKeys.PROTOCOL, REST.toUpperCase())
273 // The rest server added as annotation to the device
274 .set(AnnotationKeys.REST_SERVER, devId.toString())
275 .build(),
276 desc.annotations()));
277 }
278
279 private DevicesDiscovery devicesDiscovery(RestSBDevice restSBDevice, Driver driver) {
280 DriverData driverData = new DefaultDriverData(driver, restSBDevice.deviceId());
281 DevicesDiscovery devicesDiscovery = driver.createBehaviour(driverData,
282 DevicesDiscovery.class);
283 devicesDiscovery.setHandler(new DefaultDriverHandler(driverData));
284 return devicesDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -0800285 }
286
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600287 private void checkAndUpdateDevice(DeviceId deviceId) {
288 if (deviceService.getDevice(deviceId) == null) {
289 log.warn("Device {} has not been added to store, " +
290 "maybe due to a problem in connectivity", deviceId);
291 } else {
292 boolean isReachable = isReachable(deviceId);
293 if (isReachable && deviceService.isAvailable(deviceId)) {
294 Device device = deviceService.getDevice(deviceId);
295 if (device.is(DeviceDescriptionDiscovery.class)) {
Michele Santuaric372c222017-01-12 09:41:25 +0100296 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
297 device.as(DeviceDescriptionDiscovery.class);
298 DeviceDescription updatedDeviceDescription =
299 deviceDescriptionDiscovery.discoverDeviceDetails();
300 if (updatedDeviceDescription != null &&
301 !descriptionEquals(device, updatedDeviceDescription)) {
302 providerService.deviceConnected(
303 deviceId,
304 new DefaultDeviceDescription(
305 updatedDeviceDescription, true,
306 updatedDeviceDescription.annotations()));
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600307 //if ports are not discovered, retry the discovery
308 if (deviceService.getPorts(deviceId).isEmpty()) {
309 discoverPorts(deviceId);
310 }
311 }
312 } else {
313 log.warn("No DeviceDescriptionDiscovery behaviour for device {}", deviceId);
314 }
315 } else if (!isReachable && deviceService.isAvailable(deviceId)) {
316 providerService.deviceDisconnected(deviceId);
317 }
318 }
319 }
320
321 private boolean descriptionEquals(Device device, DeviceDescription updatedDeviceDescription) {
Michele Santuarid2c8f212017-01-09 18:23:45 +0100322 return Objects.equal(device.id().uri(), updatedDeviceDescription.deviceUri())
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600323 && Objects.equal(device.type(), updatedDeviceDescription.type())
324 && Objects.equal(device.manufacturer(), updatedDeviceDescription.manufacturer())
325 && Objects.equal(device.hwVersion(), updatedDeviceDescription.hwVersion())
326 && Objects.equal(device.swVersion(), updatedDeviceDescription.swVersion())
327 && Objects.equal(device.serialNumber(), updatedDeviceDescription.serialNumber())
328 && Objects.equal(device.chassisId(), updatedDeviceDescription.chassisId())
329 && Objects.equal(device.annotations(), updatedDeviceDescription.annotations());
330 }
331
Andrea Campanella86294db2016-03-07 11:42:49 -0800332 private void deviceRemoved(DeviceId deviceId) {
Michele Santuaric372c222017-01-12 09:41:25 +0100333 checkNotNull(deviceId, ISNOTNULL);
Andrea Campanella945ded22016-01-07 13:17:43 -0800334 providerService.deviceDisconnected(deviceId);
Michal Mach67acb692017-06-21 12:05:36 +0200335 controller.getProxiedDevices(deviceId).forEach(device -> {
Michele Santuaric372c222017-01-12 09:41:25 +0100336 controller.removeProxiedDevice(device);
337 providerService.deviceDisconnected(device);
338 });
Andrea Campanella86294db2016-03-07 11:42:49 -0800339 controller.removeDevice(deviceId);
Andrea Campanella945ded22016-01-07 13:17:43 -0800340 }
341
Andrea Campanella59b549d2017-04-14 21:58:16 +0200342 //Method to connect devices provided via net-cfg under devices/ tree
343 private void createAndConnectDevices() {
344 Set<DeviceId> deviceSubjects =
345 cfgService.getSubjects(DeviceId.class, RestDeviceConfig.class);
346 connectDevices(deviceSubjects.stream()
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800347 .filter(deviceId -> deviceService.getDevice(deviceId) == null)
348 .map(deviceId -> {
349 RestDeviceConfig config =
350 cfgService.getConfig(deviceId, RestDeviceConfig.class);
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800351 return toInactiveRestSBDevice(config);
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800352 }).collect(Collectors.toSet()));
Andrea Campanella59b549d2017-04-14 21:58:16 +0200353 }
354
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800355 private RestSBDevice toInactiveRestSBDevice(RestDeviceConfig config) {
356 return new DefaultRestSBDevice(config.ip(),
357 config.port(),
358 config.username(),
359 config.password(),
360 config.protocol(),
361 config.url(),
362 false,
363 config.testUrl(),
364 config.manufacturer(),
365 config.hwVersion(),
366 config.swVersion(),
367 config.authenticationScheme(),
368 config.token()
369 );
370 }
371
Andrea Campanella59b549d2017-04-14 21:58:16 +0200372 private void connectDevices(Set<RestSBDevice> devices) {
373 //Precomputing the devices to be removed
374 Set<RestSBDevice> toBeRemoved = new HashSet<>(controller.getDevices().values());
375 toBeRemoved.removeAll(devices);
376 //Adding new devices
377 devices.stream()
378 .filter(device -> {
379 device.setActive(false);
380 controller.addDevice(device);
381 return testDeviceConnection(device);
382 })
Michal Mach67acb692017-06-21 12:05:36 +0200383 .forEach(this::deviceAdded);
Andrea Campanella59b549d2017-04-14 21:58:16 +0200384 //Removing devices not wanted anymore
385 toBeRemoved.forEach(device -> deviceRemoved(device.deviceId()));
386 }
387
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800388 private void connectDevice(RestSBDevice device) {
389 // TODO borrowed from above,
390 // not sure why setting it to inactive
391 device.setActive(false);
392 controller.addDevice(device);
393 if (testDeviceConnection(device)) {
394 deviceAdded(device);
395 }
396 }
397
Michal Machd8099742017-06-19 14:32:35 +0200398 private ScheduledFuture schedulePolling() {
399 return portStatisticsExecutor.scheduleAtFixedRate(this::executePortStatisticsUpdate,
400 DEFAULT_POLL_FREQUENCY_SECONDS / 2,
401 DEFAULT_POLL_FREQUENCY_SECONDS,
402 TimeUnit.SECONDS);
403 }
404
405 private void executePortStatisticsUpdate() {
406 controller.getDevices().keySet().forEach(this::updatePortStatistics);
407 }
408
409 private void updatePortStatistics(DeviceId deviceId) {
410 Device device = deviceService.getDevice(deviceId);
411 checkNotNull(device, "device cannot be null");
412
413 if (device.is(PortStatisticsDiscovery.class)) {
414 PortStatisticsDiscovery portStatisticsDiscovery = device.as(PortStatisticsDiscovery.class);
415 Collection<PortStatistics> portStatistics = portStatisticsDiscovery.discoverPortStatistics();
416 if (portStatistics != null && !portStatistics.isEmpty()) {
417 providerService.updatePortStatistics(deviceId, portStatistics);
418 }
419 } else {
420 log.debug("No port statistics getter behaviour for device {}", deviceId);
421 }
422 }
423
Andrea Campanella6c71a052016-04-22 11:56:31 -0700424 private void discoverPorts(DeviceId deviceId) {
425 Device device = deviceService.getDevice(deviceId);
426 //TODO remove when PortDiscovery is removed from master
427 if (device.is(PortDiscovery.class)) {
428 PortDiscovery portConfig = device.as(PortDiscovery.class);
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600429 providerService.updatePorts(deviceId, portConfig.getPorts());
430 } else {
Andrea Campanella6c71a052016-04-22 11:56:31 -0700431 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
432 device.as(DeviceDescriptionDiscovery.class);
433 providerService.updatePorts(deviceId, deviceDescriptionDiscovery.discoverPortDetails());
Andrea Campanella6c71a052016-04-22 11:56:31 -0700434 }
435 }
436
Michele Santuaric372c222017-01-12 09:41:25 +0100437 private boolean testDeviceConnection(RestSBDevice dev) {
Andrea Campanella945ded22016-01-07 13:17:43 -0800438 try {
Palash Kala4c71ee72017-05-24 17:43:59 +0900439 Callable<Boolean> connectionSuccess;
440
Michele Santuaric372c222017-01-12 09:41:25 +0100441 if (dev.testUrl().isPresent()) {
Michal Mach67acb692017-06-21 12:05:36 +0200442 connectionSuccess = () ->
443 controller.get(dev.deviceId(), dev.testUrl().get(), MediaType.APPLICATION_JSON_TYPE) != null;
Palash Kala4c71ee72017-05-24 17:43:59 +0900444 } else {
Michal Mach67acb692017-06-21 12:05:36 +0200445 connectionSuccess = () ->
446 controller.get(dev.deviceId(), "", MediaType.APPLICATION_JSON_TYPE) != null;
Michele Santuaric372c222017-01-12 09:41:25 +0100447 }
Palash Kala4c71ee72017-05-24 17:43:59 +0900448
449 Future<Boolean> future = executor.submit(connectionSuccess);
450 try {
Michal Mach67acb692017-06-21 12:05:36 +0200451 return future.get(REST_TIMEOUT_SEC, TimeUnit.SECONDS);
Palash Kala4c71ee72017-05-24 17:43:59 +0900452 } catch (TimeoutException ex) {
453 log.warn("Connection to device {} timed out", dev.deviceId());
454 return false;
455 } catch (InterruptedException ex) {
456 log.warn("Connection to device {} interrupted", dev.deviceId());
457 return false;
458 } catch (ExecutionException ex) {
459 log.warn("Connection to device {} had a execution exception", dev.deviceId());
460 return false;
461 }
Michele Santuaric372c222017-01-12 09:41:25 +0100462
Andrea Campanellac6ecc632016-03-10 17:57:06 -0800463 } catch (ProcessingException e) {
Michele Santuaric372c222017-01-12 09:41:25 +0100464 log.warn("Cannot connect to device {}", dev, e);
Andrea Campanella945ded22016-01-07 13:17:43 -0800465 }
466 return false;
467 }
468
469 private class InternalNetworkConfigListener implements NetworkConfigListener {
Andrea Campanella945ded22016-01-07 13:17:43 -0800470 @Override
471 public void event(NetworkConfigEvent event) {
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800472 ExecutorService bg = SharedExecutors.getSingleThreadExecutor();
473 if (event.type() == CONFIG_REMOVED) {
474 DeviceId did = (DeviceId) event.subject();
475 bg.execute(() -> deviceRemoved(did));
476 } else {
477 // CONFIG_ADDED or CONFIG_UPDATED
478 RestDeviceConfig cfg = (RestDeviceConfig) event.config().get();
479 RestSBDevice restSBDevice = toInactiveRestSBDevice(cfg);
480 bg.execute(() -> connectDevice(restSBDevice));
481 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800482 }
483
484 @Override
485 public boolean isRelevant(NetworkConfigEvent event) {
Yuta HIGUCHI872fdbe2017-12-05 15:34:28 -0800486 return event.configClass().equals(RestDeviceConfig.class) &&
Andrea Campanella945ded22016-01-07 13:17:43 -0800487 (event.type() == CONFIG_ADDED ||
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800488 event.type() == CONFIG_UPDATED ||
489 event.type() == CONFIG_REMOVED);
Andrea Campanella945ded22016-01-07 13:17:43 -0800490 }
491 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700492
493 @Override
494 public void changePortState(DeviceId deviceId, PortNumber portNumber,
495 boolean enable) {
fahadnaeemkhan482951f2017-08-24 16:35:17 -0700496 Device device = deviceService.getDevice(deviceId);
497 if (device != null) {
498 if (device.is(PortAdmin.class)) {
499 PortAdmin portAdmin = device.as(PortAdmin.class);
500 CompletableFuture<Boolean> modified;
501 if (enable) {
502 modified = portAdmin.enable(portNumber);
503 } else {
504 modified = portAdmin.disable(portNumber);
505 }
506 modified.thenAcceptAsync(result -> {
507 if (!result) {
508 log.warn("Device {} port {} state can't be changed to {}",
509 deviceId, portNumber, enable);
510 }
511 });
512
513 } else {
514 log.warn("Device {} does not support PortAdmin behavior", deviceId);
515 }
516 } else {
517 log.warn("unable to get the device {}, port {} state can't be changed to {}",
518 deviceId, portNumber, enable);
519 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700520 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800521}