blob: 4c0e0482d91d4ea2e4f76b337c386230ec0e3412 [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 Campanella945ded22016-01-07 13:17:43 -0800167 providerRegistry.unregister(this);
168 providerService = null;
Andrea Campanella59b549d2017-04-14 21:58:16 +0200169 factories.forEach(cfgService::unregisterConfigFactory);
Michal Machd8099742017-06-19 14:32:35 +0200170 scheduledTask.cancel(true);
Lukasz Ryba4da35c52017-06-20 09:14:11 +0200171 executor.shutdown();
Andrea Campanella945ded22016-01-07 13:17:43 -0800172 log.info("Stopped");
173 }
174
175 public RestDeviceProvider() {
176 super(new ProviderId(REST, PROVIDER));
177 }
178
179 @Override
180 public void triggerProbe(DeviceId deviceId) {
181 // TODO: This will be implemented later.
182 log.info("Triggering probe on device {}", deviceId);
183 }
184
185 @Override
186 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
187 // TODO: This will be implemented later.
188 }
189
Andrea Campanella945ded22016-01-07 13:17:43 -0800190 @Override
191 public boolean isReachable(DeviceId deviceId) {
192 RestSBDevice restDevice = controller.getDevice(deviceId);
193 if (restDevice == null) {
Michele Santuaric372c222017-01-12 09:41:25 +0100194 restDevice = controller.getProxySBDevice(deviceId);
195 if (restDevice == null) {
196 log.debug("the requested device id: " +
197 deviceId.toString() +
198 " is not associated to any REST or REST " +
199 "proxy Device");
200 return false;
201 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800202 }
203 return restDevice.isActive();
204 }
205
Michele Santuaric372c222017-01-12 09:41:25 +0100206 private void deviceAdded(RestSBDevice restSBDev) {
207 checkNotNull(restSBDev, ISNOTNULL);
208
209 //check if the server is controlling a single or multiple devices
210 if (restSBDev.isProxy()) {
211
212 Driver driver = driverService.getDriver(restSBDev.manufacturer().get(),
213 restSBDev.hwVersion().get(),
214 restSBDev.swVersion().get());
215
216 if (driver != null && driver.hasBehaviour(DevicesDiscovery.class)) {
217
218 //Creates the driver to communicate with the server
219 DevicesDiscovery devicesDiscovery =
220 devicesDiscovery(restSBDev, driver);
221 Set<DeviceId> deviceIds = devicesDiscovery.deviceIds();
222 restSBDev.setActive(true);
Michal Mach67acb692017-06-21 12:05:36 +0200223 deviceIds.forEach(deviceId -> {
Michele Santuaric372c222017-01-12 09:41:25 +0100224 controller.addProxiedDevice(deviceId, restSBDev);
225 DeviceDescription devDesc =
226 devicesDiscovery.deviceDetails(deviceId);
227 checkNotNull(devDesc,
228 "deviceDescription cannot be null");
229 providerService.deviceConnected(
230 deviceId, mergeAnn(restSBDev.deviceId(), devDesc));
231
232 if (driver.hasBehaviour(DeviceDescriptionDiscovery.class)) {
233 DriverHandler h = driverService.createHandler(deviceId);
234 DeviceDescriptionDiscovery devDisc =
235 h.behaviour(DeviceDescriptionDiscovery.class);
236 providerService.updatePorts(deviceId,
237 devDisc.discoverPortDetails());
238 }
239
240 checkAndUpdateDevice(deviceId);
Michele Santuaric372c222017-01-12 09:41:25 +0100241 });
242 } else {
243 log.warn("Driver not found for {}", restSBDev);
244 }
245 } else {
246 DeviceId deviceId = restSBDev.deviceId();
247 ChassisId cid = new ChassisId();
248 String ipAddress = restSBDev.ip().toString();
249 SparseAnnotations annotations = DefaultAnnotations.builder()
250 .set(IPADDRESS, ipAddress)
251 .set(AnnotationKeys.PROTOCOL, REST.toUpperCase())
252 .build();
253 DeviceDescription deviceDescription = new DefaultDeviceDescription(
254 deviceId.uri(),
255 Device.Type.SWITCH,
256 UNKNOWN, UNKNOWN,
257 UNKNOWN, UNKNOWN,
258 cid,
259 annotations);
260 restSBDev.setActive(true);
261 providerService.deviceConnected(deviceId, deviceDescription);
262 checkAndUpdateDevice(deviceId);
Michele Santuaric372c222017-01-12 09:41:25 +0100263 }
264 }
265
266 private DefaultDeviceDescription mergeAnn(DeviceId devId, DeviceDescription desc) {
267 return new DefaultDeviceDescription(
268 desc,
269 DefaultAnnotations.merge(
270 DefaultAnnotations.builder()
271 .set(AnnotationKeys.PROTOCOL, REST.toUpperCase())
272 // The rest server added as annotation to the device
273 .set(AnnotationKeys.REST_SERVER, devId.toString())
274 .build(),
275 desc.annotations()));
276 }
277
278 private DevicesDiscovery devicesDiscovery(RestSBDevice restSBDevice, Driver driver) {
279 DriverData driverData = new DefaultDriverData(driver, restSBDevice.deviceId());
280 DevicesDiscovery devicesDiscovery = driver.createBehaviour(driverData,
281 DevicesDiscovery.class);
282 devicesDiscovery.setHandler(new DefaultDriverHandler(driverData));
283 return devicesDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -0800284 }
285
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600286 private void checkAndUpdateDevice(DeviceId deviceId) {
287 if (deviceService.getDevice(deviceId) == null) {
288 log.warn("Device {} has not been added to store, " +
289 "maybe due to a problem in connectivity", deviceId);
290 } else {
291 boolean isReachable = isReachable(deviceId);
292 if (isReachable && deviceService.isAvailable(deviceId)) {
293 Device device = deviceService.getDevice(deviceId);
294 if (device.is(DeviceDescriptionDiscovery.class)) {
Michele Santuaric372c222017-01-12 09:41:25 +0100295 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
296 device.as(DeviceDescriptionDiscovery.class);
297 DeviceDescription updatedDeviceDescription =
298 deviceDescriptionDiscovery.discoverDeviceDetails();
299 if (updatedDeviceDescription != null &&
300 !descriptionEquals(device, updatedDeviceDescription)) {
301 providerService.deviceConnected(
302 deviceId,
303 new DefaultDeviceDescription(
304 updatedDeviceDescription, true,
305 updatedDeviceDescription.annotations()));
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600306 //if ports are not discovered, retry the discovery
307 if (deviceService.getPorts(deviceId).isEmpty()) {
308 discoverPorts(deviceId);
309 }
310 }
311 } else {
312 log.warn("No DeviceDescriptionDiscovery behaviour for device {}", deviceId);
313 }
314 } else if (!isReachable && deviceService.isAvailable(deviceId)) {
315 providerService.deviceDisconnected(deviceId);
316 }
317 }
318 }
319
320 private boolean descriptionEquals(Device device, DeviceDescription updatedDeviceDescription) {
Michele Santuarid2c8f212017-01-09 18:23:45 +0100321 return Objects.equal(device.id().uri(), updatedDeviceDescription.deviceUri())
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600322 && Objects.equal(device.type(), updatedDeviceDescription.type())
323 && Objects.equal(device.manufacturer(), updatedDeviceDescription.manufacturer())
324 && Objects.equal(device.hwVersion(), updatedDeviceDescription.hwVersion())
325 && Objects.equal(device.swVersion(), updatedDeviceDescription.swVersion())
326 && Objects.equal(device.serialNumber(), updatedDeviceDescription.serialNumber())
327 && Objects.equal(device.chassisId(), updatedDeviceDescription.chassisId())
328 && Objects.equal(device.annotations(), updatedDeviceDescription.annotations());
329 }
330
Andrea Campanella86294db2016-03-07 11:42:49 -0800331 private void deviceRemoved(DeviceId deviceId) {
Michele Santuaric372c222017-01-12 09:41:25 +0100332 checkNotNull(deviceId, ISNOTNULL);
Andrea Campanella945ded22016-01-07 13:17:43 -0800333 providerService.deviceDisconnected(deviceId);
Michal Mach67acb692017-06-21 12:05:36 +0200334 controller.getProxiedDevices(deviceId).forEach(device -> {
Michele Santuaric372c222017-01-12 09:41:25 +0100335 controller.removeProxiedDevice(device);
336 providerService.deviceDisconnected(device);
337 });
Andrea Campanella86294db2016-03-07 11:42:49 -0800338 controller.removeDevice(deviceId);
Andrea Campanella945ded22016-01-07 13:17:43 -0800339 }
340
Andrea Campanella59b549d2017-04-14 21:58:16 +0200341 //Method to connect devices provided via net-cfg under devices/ tree
342 private void createAndConnectDevices() {
343 Set<DeviceId> deviceSubjects =
344 cfgService.getSubjects(DeviceId.class, RestDeviceConfig.class);
345 connectDevices(deviceSubjects.stream()
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800346 .filter(deviceId -> deviceService.getDevice(deviceId) == null)
347 .map(deviceId -> {
348 RestDeviceConfig config =
349 cfgService.getConfig(deviceId, RestDeviceConfig.class);
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800350 return toInactiveRestSBDevice(config);
fahadnaeemkhan02ffa712017-12-01 19:49:45 -0800351 }).collect(Collectors.toSet()));
Andrea Campanella59b549d2017-04-14 21:58:16 +0200352 }
353
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800354 private RestSBDevice toInactiveRestSBDevice(RestDeviceConfig config) {
355 return new DefaultRestSBDevice(config.ip(),
356 config.port(),
357 config.username(),
358 config.password(),
359 config.protocol(),
360 config.url(),
361 false,
362 config.testUrl(),
363 config.manufacturer(),
364 config.hwVersion(),
365 config.swVersion(),
366 config.authenticationScheme(),
367 config.token()
368 );
369 }
370
Andrea Campanella59b549d2017-04-14 21:58:16 +0200371 private void connectDevices(Set<RestSBDevice> devices) {
372 //Precomputing the devices to be removed
373 Set<RestSBDevice> toBeRemoved = new HashSet<>(controller.getDevices().values());
374 toBeRemoved.removeAll(devices);
375 //Adding new devices
376 devices.stream()
377 .filter(device -> {
378 device.setActive(false);
379 controller.addDevice(device);
380 return testDeviceConnection(device);
381 })
Michal Mach67acb692017-06-21 12:05:36 +0200382 .forEach(this::deviceAdded);
Andrea Campanella59b549d2017-04-14 21:58:16 +0200383 //Removing devices not wanted anymore
384 toBeRemoved.forEach(device -> deviceRemoved(device.deviceId()));
385 }
386
Yuta HIGUCHIfc667052017-12-05 18:17:22 -0800387 private void connectDevice(RestSBDevice device) {
388 // TODO borrowed from above,
389 // not sure why setting it to inactive
390 device.setActive(false);
391 controller.addDevice(device);
392 if (testDeviceConnection(device)) {
393 deviceAdded(device);
394 }
395 }
396
Michal Machd8099742017-06-19 14:32:35 +0200397 private ScheduledFuture schedulePolling() {
398 return portStatisticsExecutor.scheduleAtFixedRate(this::executePortStatisticsUpdate,
399 DEFAULT_POLL_FREQUENCY_SECONDS / 2,
400 DEFAULT_POLL_FREQUENCY_SECONDS,
401 TimeUnit.SECONDS);
402 }
403
404 private void executePortStatisticsUpdate() {
405 controller.getDevices().keySet().forEach(this::updatePortStatistics);
406 }
407
408 private void updatePortStatistics(DeviceId deviceId) {
409 Device device = deviceService.getDevice(deviceId);
410 checkNotNull(device, "device cannot be null");
411
412 if (device.is(PortStatisticsDiscovery.class)) {
413 PortStatisticsDiscovery portStatisticsDiscovery = device.as(PortStatisticsDiscovery.class);
414 Collection<PortStatistics> portStatistics = portStatisticsDiscovery.discoverPortStatistics();
415 if (portStatistics != null && !portStatistics.isEmpty()) {
416 providerService.updatePortStatistics(deviceId, portStatistics);
417 }
418 } else {
419 log.debug("No port statistics getter behaviour for device {}", deviceId);
420 }
421 }
422
Andrea Campanella6c71a052016-04-22 11:56:31 -0700423 private void discoverPorts(DeviceId deviceId) {
424 Device device = deviceService.getDevice(deviceId);
425 //TODO remove when PortDiscovery is removed from master
426 if (device.is(PortDiscovery.class)) {
427 PortDiscovery portConfig = device.as(PortDiscovery.class);
Konstantinos Kanonakis3cd85552016-11-17 10:11:13 -0600428 providerService.updatePorts(deviceId, portConfig.getPorts());
429 } else {
Andrea Campanella6c71a052016-04-22 11:56:31 -0700430 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
431 device.as(DeviceDescriptionDiscovery.class);
432 providerService.updatePorts(deviceId, deviceDescriptionDiscovery.discoverPortDetails());
Andrea Campanella6c71a052016-04-22 11:56:31 -0700433 }
434 }
435
Michele Santuaric372c222017-01-12 09:41:25 +0100436 private boolean testDeviceConnection(RestSBDevice dev) {
Andrea Campanella945ded22016-01-07 13:17:43 -0800437 try {
Palash Kala4c71ee72017-05-24 17:43:59 +0900438 Callable<Boolean> connectionSuccess;
439
Michele Santuaric372c222017-01-12 09:41:25 +0100440 if (dev.testUrl().isPresent()) {
Michal Mach67acb692017-06-21 12:05:36 +0200441 connectionSuccess = () ->
442 controller.get(dev.deviceId(), dev.testUrl().get(), MediaType.APPLICATION_JSON_TYPE) != null;
Palash Kala4c71ee72017-05-24 17:43:59 +0900443 } else {
Michal Mach67acb692017-06-21 12:05:36 +0200444 connectionSuccess = () ->
445 controller.get(dev.deviceId(), "", MediaType.APPLICATION_JSON_TYPE) != null;
Michele Santuaric372c222017-01-12 09:41:25 +0100446 }
Palash Kala4c71ee72017-05-24 17:43:59 +0900447
448 Future<Boolean> future = executor.submit(connectionSuccess);
449 try {
Michal Mach67acb692017-06-21 12:05:36 +0200450 return future.get(REST_TIMEOUT_SEC, TimeUnit.SECONDS);
Palash Kala4c71ee72017-05-24 17:43:59 +0900451 } catch (TimeoutException ex) {
452 log.warn("Connection to device {} timed out", dev.deviceId());
453 return false;
454 } catch (InterruptedException ex) {
455 log.warn("Connection to device {} interrupted", dev.deviceId());
Ray Milkey5c7d4882018-02-05 14:50:39 -0800456 Thread.currentThread().interrupt();
Palash Kala4c71ee72017-05-24 17:43:59 +0900457 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}