blob: 550ca5994b11a4585328d3233df22922d4ba0da1 [file] [log] [blame]
Andrea Campanella241896c2017-05-10 13:11:04 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Andrea Campanella241896c2017-05-10 13:11:04 -07003 *
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.general.device.impl;
18
19import com.google.common.annotations.Beta;
Andrea Campanellabc112a92017-06-26 19:06:43 +020020import com.google.common.collect.ImmutableSet;
21import com.google.common.collect.Maps;
Andrea Campanella241896c2017-05-10 13:11:04 -070022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
Andrea Campanella19090322017-08-22 10:31:37 +020025import org.apache.felix.scr.annotations.Modified;
26import org.apache.felix.scr.annotations.Property;
Andrea Campanella241896c2017-05-10 13:11:04 -070027import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
29import org.onlab.packet.ChassisId;
30import org.onlab.util.ItemNotFoundException;
Andrea Campanella19090322017-08-22 10:31:37 +020031import org.onlab.util.Tools;
Andrea Campanella4929a812017-10-09 18:38:23 +020032import org.onosproject.cfg.ComponentConfigService;
Andrea Campanella14e196d2017-07-24 18:11:36 +020033import org.onosproject.cluster.ClusterService;
34import org.onosproject.cluster.LeadershipService;
35import org.onosproject.cluster.NodeId;
Andrea Campanella241896c2017-05-10 13:11:04 -070036import org.onosproject.core.CoreService;
Andrea Campanella14e196d2017-07-24 18:11:36 +020037import org.onosproject.mastership.MastershipService;
Andrea Campanella241896c2017-05-10 13:11:04 -070038import org.onosproject.net.AnnotationKeys;
39import org.onosproject.net.DefaultAnnotations;
40import org.onosproject.net.Device;
41import org.onosproject.net.DeviceId;
42import org.onosproject.net.MastershipRole;
43import org.onosproject.net.PortNumber;
44import org.onosproject.net.SparseAnnotations;
Carmelo Cascone87892e22017-11-13 16:01:29 -080045import org.onosproject.net.behaviour.PiPipelineProgrammable;
Andrea Campanella241896c2017-05-10 13:11:04 -070046import org.onosproject.net.behaviour.PortAdmin;
47import org.onosproject.net.config.ConfigFactory;
48import org.onosproject.net.config.NetworkConfigEvent;
49import org.onosproject.net.config.NetworkConfigListener;
50import org.onosproject.net.config.NetworkConfigRegistry;
51import org.onosproject.net.config.basics.BasicDeviceConfig;
52import org.onosproject.net.config.basics.SubjectFactories;
Andrea Campanella1e573442018-05-17 17:07:13 +020053import org.onosproject.net.device.ChannelEvent;
54import org.onosproject.net.device.ChannelListener;
Andrea Campanella241896c2017-05-10 13:11:04 -070055import org.onosproject.net.device.DefaultDeviceDescription;
56import org.onosproject.net.device.DeviceDescription;
57import org.onosproject.net.device.DeviceDescriptionDiscovery;
58import org.onosproject.net.device.DeviceEvent;
59import org.onosproject.net.device.DeviceHandshaker;
60import org.onosproject.net.device.DeviceListener;
61import org.onosproject.net.device.DeviceProvider;
62import org.onosproject.net.device.DeviceProviderRegistry;
63import org.onosproject.net.device.DeviceProviderService;
64import org.onosproject.net.device.DeviceService;
65import org.onosproject.net.device.PortDescription;
66import org.onosproject.net.device.PortStatistics;
67import org.onosproject.net.device.PortStatisticsDiscovery;
68import org.onosproject.net.driver.Behaviour;
69import org.onosproject.net.driver.DefaultDriverData;
70import org.onosproject.net.driver.DefaultDriverHandler;
71import org.onosproject.net.driver.Driver;
72import org.onosproject.net.driver.DriverData;
73import org.onosproject.net.driver.DriverService;
Carmelo Cascone59f57de2017-07-11 19:55:09 -040074import org.onosproject.net.pi.model.PiPipeconf;
Andrea Campanellabc112a92017-06-26 19:06:43 +020075import org.onosproject.net.pi.model.PiPipeconfId;
Carmelo Cascone39c28ca2017-11-15 13:03:57 -080076import org.onosproject.net.pi.service.PiPipeconfConfig;
77import org.onosproject.net.pi.service.PiPipeconfService;
Andrea Campanella241896c2017-05-10 13:11:04 -070078import org.onosproject.net.provider.AbstractProvider;
79import org.onosproject.net.provider.ProviderId;
80import org.onosproject.provider.general.device.api.GeneralProviderDeviceConfig;
Andrea Campanella19090322017-08-22 10:31:37 +020081import org.osgi.service.component.ComponentContext;
Andrea Campanella241896c2017-05-10 13:11:04 -070082import org.slf4j.Logger;
83
Ray Milkeyb68bbbc2017-12-18 10:05:49 -080084import java.security.SecureRandom;
Andrea Campanella241896c2017-05-10 13:11:04 -070085import java.util.ArrayList;
86import java.util.Collection;
Andrea Campanellabc112a92017-06-26 19:06:43 +020087import java.util.Collections;
Andrea Campanella19090322017-08-22 10:31:37 +020088import java.util.Dictionary;
Andrea Campanella241896c2017-05-10 13:11:04 -070089import java.util.List;
Thomas Vachuska5b38dc02018-05-10 15:24:40 -070090import java.util.Map;
Andrea Campanellace111932017-09-18 16:59:56 +090091import java.util.Objects;
Andrea Campanellabc112a92017-06-26 19:06:43 +020092import java.util.Set;
Andrea Campanella241896c2017-05-10 13:11:04 -070093import java.util.concurrent.CompletableFuture;
Andrea Campanella19090322017-08-22 10:31:37 +020094import java.util.concurrent.ConcurrentHashMap;
Andrea Campanellabc112a92017-06-26 19:06:43 +020095import java.util.concurrent.ConcurrentMap;
96import java.util.concurrent.CopyOnWriteArraySet;
Andrea Campanella241896c2017-05-10 13:11:04 -070097import java.util.concurrent.ExecutionException;
98import java.util.concurrent.ScheduledExecutorService;
Andrea Campanella19090322017-08-22 10:31:37 +020099import java.util.concurrent.ScheduledFuture;
Andrea Campanella241896c2017-05-10 13:11:04 -0700100import java.util.concurrent.TimeUnit;
101import java.util.concurrent.TimeoutException;
Andrea Campanellabc112a92017-06-26 19:06:43 +0200102import java.util.concurrent.locks.Lock;
103import java.util.concurrent.locks.ReentrantLock;
Andrea Campanella241896c2017-05-10 13:11:04 -0700104
105import static java.util.concurrent.Executors.newScheduledThreadPool;
106import static org.onlab.util.Tools.groupedThreads;
107import static org.onosproject.net.device.DeviceEvent.Type;
108import static org.slf4j.LoggerFactory.getLogger;
109
110/**
111 * Provider which uses drivers to detect device and do initial handshake
112 * and channel establishment with devices. Any other provider specific operation
113 * is also delegated to the DeviceHandshaker driver.
114 */
115@Beta
116@Component(immediate = true)
117public class GeneralDeviceProvider extends AbstractProvider
118 implements DeviceProvider {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200119 public static final String DRIVER = "driver";
Andrea Campanella14e196d2017-07-24 18:11:36 +0200120 public static final int REACHABILITY_TIMEOUT = 10;
121 public static final String DEPLOY = "deploy-";
122 public static final String PIPECONF_TOPIC = "-pipeconf";
Andrea Campanella1e573442018-05-17 17:07:13 +0200123 public static final String CHECK = "check-";
124 public static final String CONNECTION = "-connection";
125 private static final String POLL_FREQUENCY = "pollFrequency";
Andrea Campanella14e196d2017-07-24 18:11:36 +0200126
Andrea Campanella241896c2017-05-10 13:11:04 -0700127 private final Logger log = getLogger(getClass());
128
129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
130 protected DeviceProviderRegistry providerRegistry;
131
132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Andrea Campanella4929a812017-10-09 18:38:23 +0200133 protected ComponentConfigService componentConfigService;
134
135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Andrea Campanella241896c2017-05-10 13:11:04 -0700136 protected NetworkConfigRegistry cfgService;
137
138 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
139 protected CoreService coreService;
140
141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected DeviceService deviceService;
143
144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected DriverService driverService;
146
147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Andrea Campanella14e196d2017-07-24 18:11:36 +0200148 protected MastershipService mastershipService;
149
150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Andrea Campanellabc112a92017-06-26 19:06:43 +0200151 protected PiPipeconfService piPipeconfService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700152
Andrea Campanella14e196d2017-07-24 18:11:36 +0200153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected ClusterService clusterService;
155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
157 protected LeadershipService leadershipService;
158
Andrea Campanella19090322017-08-22 10:31:37 +0200159 private static final int DEFAULT_POLL_FREQUENCY_SECONDS = 10;
Andrea Campanella1e573442018-05-17 17:07:13 +0200160 @Property(name = POLL_FREQUENCY, intValue = DEFAULT_POLL_FREQUENCY_SECONDS,
Andrea Campanella19090322017-08-22 10:31:37 +0200161 label = "Configure poll frequency for port status and statistics; " +
162 "default is 10 sec")
163 private int pollFrequency = DEFAULT_POLL_FREQUENCY_SECONDS;
164
Andrea Campanella1e573442018-05-17 17:07:13 +0200165 private static final int DEVICE_AVAILABILITY_POLL_FREQUENCY_SECONDS = 10;
166 @Property(name = "deviceAvailabilityPollFrequency", intValue = DEVICE_AVAILABILITY_POLL_FREQUENCY_SECONDS,
167 label = "Configure poll frequency for checking device availability; " +
168 "default is 10 sec")
169 private int deviceAvailabilityPollFrequency = DEVICE_AVAILABILITY_POLL_FREQUENCY_SECONDS;
170
Andrea Campanella241896c2017-05-10 13:11:04 -0700171 protected static final String APP_NAME = "org.onosproject.generaldeviceprovider";
172 protected static final String URI_SCHEME = "device";
173 protected static final String CFG_SCHEME = "generalprovider";
174 private static final String DEVICE_PROVIDER_PACKAGE = "org.onosproject.general.provider.device";
175 private static final int CORE_POOL_SIZE = 10;
176 private static final String UNKNOWN = "unknown";
Andrea Campanella19090322017-08-22 10:31:37 +0200177
Andrea Campanellabc112a92017-06-26 19:06:43 +0200178 //FIXME this will be removed when the configuration is synced at the source.
179 private static final Set<String> PIPELINE_CONFIGURABLE_PROTOCOLS = ImmutableSet.of("p4runtime");
Andrea Campanellabc112a92017-06-26 19:06:43 +0200180
Andrea Campanella19090322017-08-22 10:31:37 +0200181 private static final ConcurrentMap<DeviceId, Lock> ENTRY_LOCKS = Maps.newConcurrentMap();
Andrea Campanellabc112a92017-06-26 19:06:43 +0200182 //FIXME to be removed when netcfg will issue device events in a bundle or
183 //ensures all configuration needed is present
184 private Set<DeviceId> deviceConfigured = new CopyOnWriteArraySet<>();
185 private Set<DeviceId> driverConfigured = new CopyOnWriteArraySet<>();
186 private Set<DeviceId> pipelineConfigured = new CopyOnWriteArraySet<>();
Andrea Campanella241896c2017-05-10 13:11:04 -0700187
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700188 private final Map<DeviceId, DeviceHandshaker> handshakers = Maps.newConcurrentMap();
189
Andrea Campanella241896c2017-05-10 13:11:04 -0700190
191 protected ScheduledExecutorService connectionExecutor
192 = newScheduledThreadPool(CORE_POOL_SIZE,
Andrea Campanella19090322017-08-22 10:31:37 +0200193 groupedThreads("onos/generaldeviceprovider-device",
194 "connection-executor-%d", log));
Andrea Campanella241896c2017-05-10 13:11:04 -0700195 protected ScheduledExecutorService portStatsExecutor
196 = newScheduledThreadPool(CORE_POOL_SIZE,
Andrea Campanella19090322017-08-22 10:31:37 +0200197 groupedThreads("onos/generaldeviceprovider-port-stats",
198 "port-stats-executor-%d", log));
Andrea Campanella1e573442018-05-17 17:07:13 +0200199 protected ScheduledExecutorService availabilityCheckExecutor
200 = newScheduledThreadPool(CORE_POOL_SIZE,
201 groupedThreads("onos/generaldeviceprovider-availability-check",
202 "availability-check-executor-%d", log));
Andrea Campanella19090322017-08-22 10:31:37 +0200203 protected ConcurrentMap<DeviceId, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
Andrea Campanella241896c2017-05-10 13:11:04 -0700204
205 protected DeviceProviderService providerService;
206 private InternalDeviceListener deviceListener = new InternalDeviceListener();
207
208 protected final ConfigFactory factory =
209 new ConfigFactory<DeviceId, GeneralProviderDeviceConfig>(
210 SubjectFactories.DEVICE_SUBJECT_FACTORY,
211 GeneralProviderDeviceConfig.class, CFG_SCHEME) {
212 @Override
213 public GeneralProviderDeviceConfig createConfig() {
214 return new GeneralProviderDeviceConfig();
215 }
216 };
217
218 protected final NetworkConfigListener cfgListener = new InternalNetworkConfigListener();
Andrea Campanella1e573442018-05-17 17:07:13 +0200219 private ChannelListener channelListener = new InternalChannelListener();
Andrea Campanella241896c2017-05-10 13:11:04 -0700220
221
222 @Activate
Andrea Campanella1e573442018-05-17 17:07:13 +0200223 public void activate(ComponentContext context) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700224 providerService = providerRegistry.register(this);
Andrea Campanella4929a812017-10-09 18:38:23 +0200225 componentConfigService.registerProperties(getClass());
Andrea Campanella241896c2017-05-10 13:11:04 -0700226 coreService.registerApplication(APP_NAME);
227 cfgService.registerConfigFactory(factory);
228 cfgService.addListener(cfgListener);
229 deviceService.addListener(deviceListener);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700230 handshakers.clear();
Andrea Campanella241896c2017-05-10 13:11:04 -0700231 //This will fail if ONOS has CFG and drivers which depend on this provider
232 // are activated, failing due to not finding the driver.
233 cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class)
234 .forEach(did -> connectionExecutor.execute(() -> connectDevice(did)));
Andrea Campanella1e573442018-05-17 17:07:13 +0200235 //Initiating a periodic check to see if any device is available again and reconnect it.
236 availabilityCheckExecutor.scheduleAtFixedRate(this::scheduleDevicePolling, deviceAvailabilityPollFrequency,
237 deviceAvailabilityPollFrequency, TimeUnit.SECONDS);
238 modified(context);
Andrea Campanella241896c2017-05-10 13:11:04 -0700239 log.info("Started");
240 }
241
Andrea Campanella19090322017-08-22 10:31:37 +0200242 @Modified
243 public void modified(ComponentContext context) {
244 if (context != null) {
245 Dictionary<?, ?> properties = context.getProperties();
Andrea Campanella1e573442018-05-17 17:07:13 +0200246 pollFrequency = Tools.getIntegerProperty(properties, POLL_FREQUENCY,
Andrea Campanella19090322017-08-22 10:31:37 +0200247 DEFAULT_POLL_FREQUENCY_SECONDS);
248 log.info("Configured. Poll frequency is configured to {} seconds", pollFrequency);
249 }
250
251 if (!scheduledTasks.isEmpty()) {
252 //cancel all previous tasks
253 scheduledTasks.values().forEach(task -> task.cancel(false));
254 //resubmit task with new timeout.
255 Set<DeviceId> deviceSubjects =
256 cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class);
257 deviceSubjects.forEach(deviceId -> {
258 if (!compareScheme(deviceId)) {
259 // not under my scheme, skipping
260 log.debug("{} is not my scheme, skipping", deviceId);
261 return;
262 }
Andrea Campanella1e573442018-05-17 17:07:13 +0200263 scheduledTasks.put(deviceId, scheduleStatistcsPolling(deviceId, true));
Andrea Campanella19090322017-08-22 10:31:37 +0200264 });
265 }
Andrea Campanella19090322017-08-22 10:31:37 +0200266 }
267
Andrea Campanella241896c2017-05-10 13:11:04 -0700268 @Deactivate
269 public void deactivate() {
270 portStatsExecutor.shutdown();
Andrea Campanella1e573442018-05-17 17:07:13 +0200271 availabilityCheckExecutor.shutdown();
Andrea Campanella4929a812017-10-09 18:38:23 +0200272 componentConfigService.unregisterProperties(getClass(), false);
Andrea Campanella241896c2017-05-10 13:11:04 -0700273 cfgService.removeListener(cfgListener);
274 //Not Removing the device so they can still be used from other driver providers
275 //cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class)
276 // .forEach(did -> connectionExecutor.execute(() -> disconnectDevice(did)));
277 connectionExecutor.shutdown();
278 deviceService.removeListener(deviceListener);
279 providerRegistry.unregister(this);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700280 handshakers.clear();
Andrea Campanella241896c2017-05-10 13:11:04 -0700281 providerService = null;
282 cfgService.unregisterConfigFactory(factory);
283 log.info("Stopped");
284 }
285
286 public GeneralDeviceProvider() {
287 super(new ProviderId(URI_SCHEME, DEVICE_PROVIDER_PACKAGE));
288 }
289
290
291 @Override
292 public void triggerProbe(DeviceId deviceId) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700293 // TODO Really don't see the point of this in non OF Context,
Andrea Campanella241896c2017-05-10 13:11:04 -0700294 // for now testing reachability, can be moved to no-op
295 log.debug("Triggering probe equals testing reachability on device {}", deviceId);
296 isReachable(deviceId);
297 }
298
299 @Override
300 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
Andrea Campanella14e196d2017-07-24 18:11:36 +0200301 log.info("Received role {} for device {}", newRole, deviceId);
Andrea Campanella241896c2017-05-10 13:11:04 -0700302 CompletableFuture<MastershipRole> roleReply = getHandshaker(deviceId).roleChanged(newRole);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200303 roleReply.thenAcceptAsync(mastership -> {
304 providerService.receivedRoleReply(deviceId, newRole, mastership);
305 if (!mastership.equals(MastershipRole.MASTER) && scheduledTasks.get(deviceId) != null) {
306 scheduledTasks.get(deviceId).cancel(false);
307 scheduledTasks.remove(deviceId);
308 } else if (mastership.equals(MastershipRole.MASTER) && scheduledTasks.get(deviceId) == null) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200309 scheduledTasks.put(deviceId, scheduleStatistcsPolling(deviceId, false));
Andrea Campanella14e196d2017-07-24 18:11:36 +0200310 updatePortStatistics(deviceId);
311 }
312 });
Andrea Campanella241896c2017-05-10 13:11:04 -0700313 }
314
315 @Override
316 public boolean isReachable(DeviceId deviceId) {
Andrea Campanella14e196d2017-07-24 18:11:36 +0200317 log.debug("Testing reachability for device {}", deviceId);
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100318
319 DeviceHandshaker handshaker = getHandshaker(deviceId);
320 if (handshaker == null) {
321 return false;
322 }
323
324 CompletableFuture<Boolean> reachable = handshaker.isReachable();
Andrea Campanella241896c2017-05-10 13:11:04 -0700325 try {
Andrea Campanella14e196d2017-07-24 18:11:36 +0200326 return reachable.get(REACHABILITY_TIMEOUT, TimeUnit.SECONDS);
Andrea Campanella241896c2017-05-10 13:11:04 -0700327 } catch (InterruptedException | ExecutionException | TimeoutException e) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200328 log.warn("Device {} is not reachable {}", deviceId, e.getMessage());
329 log.debug("Exception", e);
Andrea Campanella241896c2017-05-10 13:11:04 -0700330 return false;
331 }
332 }
333
334 @Override
335 public void changePortState(DeviceId deviceId, PortNumber portNumber,
336 boolean enable) {
337 if (deviceService.getDevice(deviceId).is(PortAdmin.class)) {
338
339 PortAdmin portAdmin = getPortAdmin(deviceId);
340 CompletableFuture<Boolean> modified;
341 if (enable) {
342 modified = portAdmin.enable(portNumber);
343 } else {
344 modified = portAdmin.disable(portNumber);
345 }
346 modified.thenAcceptAsync(result -> {
347 if (!result) {
348 log.warn("Your device {} port {} status can't be changed to {}",
Andrea Campanella19090322017-08-22 10:31:37 +0200349 deviceId, portNumber, enable);
Andrea Campanella241896c2017-05-10 13:11:04 -0700350 }
351 });
352
353 } else {
354 log.warn("Device {} does not support PortAdmin behaviour", deviceId);
355 }
356 }
357
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700358 @Override
359 public void triggerDisconnect(DeviceId deviceId) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200360 log.debug("Triggering disconnection of device {}", deviceId);
361 connectionExecutor.execute(() -> {
362 disconnectDevice(deviceId).whenComplete((success, ex) -> {
363 checkAndConnect(deviceId);
364 });
365 });
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700366 }
367
Andrea Campanella241896c2017-05-10 13:11:04 -0700368 private DeviceHandshaker getHandshaker(DeviceId deviceId) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700369 return handshakers.computeIfAbsent(deviceId, id -> {
370 Driver driver = getDriver(deviceId);
371 return driver == null ? null :
372 getBehaviour(driver, DeviceHandshaker.class,
373 new DefaultDriverData(driver, deviceId));
374 });
Andrea Campanella241896c2017-05-10 13:11:04 -0700375 }
376
377 private PortAdmin getPortAdmin(DeviceId deviceId) {
378 Driver driver = getDriver(deviceId);
379 return getBehaviour(driver, PortAdmin.class,
Andrea Campanella19090322017-08-22 10:31:37 +0200380 new DefaultDriverData(driver, deviceId));
Andrea Campanella241896c2017-05-10 13:11:04 -0700381
382 }
383
384 private Driver getDriver(DeviceId deviceId) {
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100385 Driver driver = null;
Andrea Campanella241896c2017-05-10 13:11:04 -0700386 try {
387 driver = driverService.getDriver(deviceId);
388 } catch (ItemNotFoundException e) {
389 log.debug("Falling back to configuration to fetch driver " +
Andrea Campanella19090322017-08-22 10:31:37 +0200390 "for device {}", deviceId);
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100391 BasicDeviceConfig cfg = cfgService.getConfig(deviceId, BasicDeviceConfig.class);
392 if (cfg != null) {
393 driver = driverService.getDriver(cfg.driver());
394 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700395 }
396 return driver;
397 }
398
399 //needed since the device manager will not return the driver through implementation()
400 // method since the device is not pushed to the core so for the connectDevice
401 // we need to work around that in order to test before calling
402 // store.createOrUpdateDevice
403 private <T extends Behaviour> T getBehaviour(Driver driver, Class<T> type,
404 DriverData data) {
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100405 if (driver != null && driver.hasBehaviour(type)) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700406 DefaultDriverHandler handler = new DefaultDriverHandler(data);
407 return driver.createBehaviour(handler, type);
408 } else {
409 return null;
410 }
411 }
412
413 //Connects a general device
414 private void connectDevice(DeviceId deviceId) {
415 //retrieve the configuration
416 GeneralProviderDeviceConfig providerConfig =
417 cfgService.getConfig(deviceId, GeneralProviderDeviceConfig.class);
418 BasicDeviceConfig basicDeviceConfig =
419 cfgService.getConfig(deviceId, BasicDeviceConfig.class);
420
421 if (providerConfig == null || basicDeviceConfig == null) {
422 log.error("Configuration is NULL: basic config {}, general provider " +
Andrea Campanella19090322017-08-22 10:31:37 +0200423 "config {}", basicDeviceConfig, providerConfig);
Andrea Campanella241896c2017-05-10 13:11:04 -0700424 } else {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200425 log.info("Connecting to device {} with driver {}", deviceId, basicDeviceConfig.driver());
Andrea Campanella241896c2017-05-10 13:11:04 -0700426
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700427 DeviceHandshaker handshaker = getHandshaker(deviceId);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200428 if (handshaker == null) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700429 log.error("Device {} does not support DeviceHandshaker behaviour", deviceId);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200430 return;
Andrea Campanella241896c2017-05-10 13:11:04 -0700431 }
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700432 Driver driver = handshaker.handler().driver();
Frank Wang554ce972017-09-06 09:56:43 +0800433
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700434 addConfigData(providerConfig, handshaker.data());
Andrea Campanellabc112a92017-06-26 19:06:43 +0200435
436 //Connecting to the device
437 CompletableFuture<Boolean> connected = handshaker.connect();
438
439 connected.thenAcceptAsync(result -> {
440 if (result) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200441 handshaker.addChannelListener(channelListener);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200442 //Populated with the default values obtained by the driver
443 ChassisId cid = new ChassisId();
444 SparseAnnotations annotations = DefaultAnnotations.builder()
445 .set(AnnotationKeys.PROTOCOL,
Andrea Campanella19090322017-08-22 10:31:37 +0200446 providerConfig.protocolsInfo().keySet().toString())
Andrea Campanellabc112a92017-06-26 19:06:43 +0200447 .build();
448 DeviceDescription description =
449 new DefaultDeviceDescription(deviceId.uri(), Device.Type.SWITCH,
Andrea Campanella19090322017-08-22 10:31:37 +0200450 driver.manufacturer(), driver.hwVersion(),
451 driver.swVersion(), UNKNOWN,
Yi Tseng92494fb2017-12-05 15:14:53 -0800452 cid, true, annotations);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200453 //Empty list of ports
454 List<PortDescription> ports = new ArrayList<>();
455
Andrea Campanellabf9e5ce2017-12-06 14:26:36 +0100456 DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(driver,
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700457 DeviceDescriptionDiscovery.class, handshaker.data());
Andrea Campanellabf9e5ce2017-12-06 14:26:36 +0100458 if (deviceDiscovery != null) {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200459 DeviceDescription newdescription = deviceDiscovery.discoverDeviceDetails();
460 if (newdescription != null) {
461 description = newdescription;
462 }
463 ports = deviceDiscovery.discoverPortDetails();
Andrea Campanellabf9e5ce2017-12-06 14:26:36 +0100464 } else {
465 log.info("No Device Description Discovery for device {}, no update for " +
466 "description or ports.", deviceId);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200467 }
468
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700469 if (!handlePipeconf(deviceId, driver, handshaker.data(), true)) {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400470 // Something went wrong during handling of pipeconf.
471 // We already logged the error.
472 handshaker.disconnect();
473 return;
Andrea Campanellabc112a92017-06-26 19:06:43 +0200474 }
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400475 advertiseDevice(deviceId, description, ports);
476
Andrea Campanellabc112a92017-06-26 19:06:43 +0200477 } else {
478 log.warn("Can't connect to device {}", deviceId);
479 }
480 });
Andrea Campanella241896c2017-05-10 13:11:04 -0700481 }
482 }
483
Andrea Campanella14e196d2017-07-24 18:11:36 +0200484 private void connectStandbyDevice(DeviceId deviceId) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700485 // if device is pipeline programmable we merge pipeconf + base driver for every other role
Andrea Campanella14e196d2017-07-24 18:11:36 +0200486 GeneralProviderDeviceConfig providerConfig =
487 cfgService.getConfig(deviceId, GeneralProviderDeviceConfig.class);
488
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700489 DeviceHandshaker handshaker = getHandshaker(deviceId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200490 if (handshaker == null) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700491 log.error("Device {} does not support DeviceHandshaker behaviour", deviceId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200492 return;
493 }
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700494 addConfigData(providerConfig, handshaker.data());
Andrea Campanella14e196d2017-07-24 18:11:36 +0200495
496 //Connecting to the device
497 handshaker.connect().thenAcceptAsync(result -> {
498 if (result) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200499 handshaker.addChannelListener(channelListener);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700500 handlePipeconf(deviceId, handshaker.handler().driver(), handshaker.data(), false);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200501 }
502 });
503 }
504
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400505 /**
506 * Handles the case of a device that is pipeline programmable. Returns true if the operation wa successful and the
507 * device can be registered to the core, false otherwise.
508 */
Andrea Campanella14e196d2017-07-24 18:11:36 +0200509 private boolean handlePipeconf(DeviceId deviceId, Driver driver, DriverData driverData, boolean deployPipeconf) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700510 PiPipelineProgrammable pipelineProg =
511 getBehaviour(driver, PiPipelineProgrammable.class, driverData);
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400512
513 if (pipelineProg == null) {
514 // Device is not pipeline programmable.
515 return true;
516 }
517
Andrea Campanella14e196d2017-07-24 18:11:36 +0200518 PiPipeconf pipeconf = getPipeconf(deviceId, pipelineProg);
519
520 if (pipeconf != null) {
Andrea Campanella14e196d2017-07-24 18:11:36 +0200521 PiPipeconfId pipeconfId = pipeconf.id();
522
523 try {
524 if (deployPipeconf) {
525 if (!pipelineProg.deployPipeconf(pipeconf).get()) {
526 log.error("Unable to deploy pipeconf {} to {}, aborting device discovery",
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700527 pipeconfId, deviceId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200528 return false;
529 }
530 }
531 } catch (InterruptedException | ExecutionException e) {
532 log.warn("Exception occurred while deploying pipeconf {} to device {}", pipeconf.id(), deviceId, e);
533 return false;
534 }
535 try {
536 if (!piPipeconfService.bindToDevice(pipeconfId, deviceId).get()) {
537 log.error("Unable to merge driver {} for device {} with pipeconf {}, aborting device discovery",
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700538 driver.name(), deviceId, pipeconfId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200539 return false;
540 }
541 } catch (InterruptedException | ExecutionException e) {
542 log.warn("Exception occurred while binding pipeconf {} to device {}", pipeconf.id(), deviceId, e);
543 return false;
544 }
545 } else {
546 return false;
547 }
548
549 return true;
550 }
551
552 private PiPipeconf getPipeconf(DeviceId deviceId, PiPipelineProgrammable pipelineProg) {
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400553 PiPipeconfId pipeconfId = piPipeconfService.ofDevice(deviceId).orElseGet(() -> {
554 // No pipeconf has been associated with this device.
555 // Check if device driver provides a default one.
556 if (pipelineProg.getDefaultPipeconf().isPresent()) {
557 PiPipeconf defaultPipeconf = pipelineProg.getDefaultPipeconf().get();
558 log.info("Using default pipeconf {} for {}", defaultPipeconf.id(), deviceId);
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400559 return defaultPipeconf.id();
560 } else {
561 return null;
562 }
563 });
564
565 if (pipeconfId == null) {
566 log.warn("Device {} is pipeline programmable but no pipeconf can be associated to it.", deviceId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200567 return null;
Carmelo Cascone1fb27d32017-08-25 20:40:20 +0200568 }
569
570 if (!piPipeconfService.getPipeconf(pipeconfId).isPresent()) {
571 log.warn("Pipeconf {} is not registered", pipeconfId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200572 return null;
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400573 }
574
Andrea Campanella14e196d2017-07-24 18:11:36 +0200575 return piPipeconfService.getPipeconf(pipeconfId).get();
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400576 }
577
Andrea Campanellabc112a92017-06-26 19:06:43 +0200578 private void advertiseDevice(DeviceId deviceId, DeviceDescription description, List<PortDescription> ports) {
579 providerService.deviceConnected(deviceId, description);
580 providerService.updatePorts(deviceId, ports);
581 }
582
Andrea Campanella1e573442018-05-17 17:07:13 +0200583 private CompletableFuture<Boolean> disconnectDevice(DeviceId deviceId) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700584 log.info("Disconnecting for device {}", deviceId);
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100585
Andrea Campanella1e573442018-05-17 17:07:13 +0200586 CompletableFuture<Boolean> disconnectError = new CompletableFuture<>();
587
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700588 DeviceHandshaker handshaker = handshakers.remove(deviceId);
589 if (handshaker != null) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200590 handshaker.disconnect().thenAcceptAsync(result -> {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700591 if (result) {
592 log.info("Disconnected device {}", deviceId);
593 providerService.deviceDisconnected(deviceId);
Andrea Campanella1e573442018-05-17 17:07:13 +0200594 disconnectError.complete(true);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700595 } else {
Andrea Campanella1e573442018-05-17 17:07:13 +0200596 disconnectError.complete(false);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700597 log.warn("Device {} was unable to disconnect", deviceId);
598 }
599 });
Andrea Campanella241896c2017-05-10 13:11:04 -0700600 } else {
601 //gracefully ignoring.
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700602 log.warn("No DeviceHandshaker for device {}, no guarantees of complete " +
603 "shutdown of communication", deviceId);
Andrea Campanella1e573442018-05-17 17:07:13 +0200604 disconnectError.complete(false);
Andrea Campanella241896c2017-05-10 13:11:04 -0700605 }
Andrea Campanella19090322017-08-22 10:31:37 +0200606 ScheduledFuture<?> pollingStatisticsTask = scheduledTasks.get(deviceId);
607 if (pollingStatisticsTask != null) {
608 pollingStatisticsTask.cancel(true);
Andrea Campanella1e573442018-05-17 17:07:13 +0200609 scheduledTasks.remove(deviceId);
Andrea Campanella19090322017-08-22 10:31:37 +0200610 }
Andrea Campanella1e573442018-05-17 17:07:13 +0200611 return disconnectError;
Andrea Campanella241896c2017-05-10 13:11:04 -0700612 }
613
614 //Needed to catch the exception in the executors since are not rethrown otherwise.
615 private Runnable exceptionSafe(Runnable runnable) {
616 return () -> {
617 try {
618 runnable.run();
619 } catch (Exception e) {
620 log.error("Unhandled Exception", e);
621 }
622 };
623 }
624
625 private void updatePortStatistics(DeviceId deviceId) {
Andrea Campanellace111932017-09-18 16:59:56 +0900626 Device device = deviceService.getDevice(deviceId);
627 if (!Objects.isNull(device) && deviceService.isAvailable(deviceId) &&
628 device.is(PortStatisticsDiscovery.class)) {
629 Collection<PortStatistics> statistics = device.as(PortStatisticsDiscovery.class)
630 .discoverPortStatistics();
631 //updating statistcs only if not empty
632 if (!statistics.isEmpty()) {
633 providerService.updatePortStatistics(deviceId, statistics);
634 }
635 } else {
636 log.debug("Can't update port statistics for device {}", deviceId);
Andrea Campanella19090322017-08-22 10:31:37 +0200637 }
638 }
639
640 private boolean compareScheme(DeviceId deviceId) {
641 return deviceId.uri().getScheme().equals(URI_SCHEME);
Andrea Campanella241896c2017-05-10 13:11:04 -0700642 }
643
644 /**
645 * Listener for configuration events.
646 */
647 private class InternalNetworkConfigListener implements NetworkConfigListener {
648
Andrea Campanella241896c2017-05-10 13:11:04 -0700649 @Override
650 public void event(NetworkConfigEvent event) {
651 DeviceId deviceId = (DeviceId) event.subject();
652 //Assuming that the deviceId comes with uri 'device:'
Andrea Campanella19090322017-08-22 10:31:37 +0200653 if (!compareScheme(deviceId)) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700654 // not under my scheme, skipping
655 log.debug("{} is not my scheme, skipping", deviceId);
656 return;
657 }
Andrea Campanellace111932017-09-18 16:59:56 +0900658 if (deviceService.getDevice(deviceId) != null && deviceService.isAvailable(deviceId)) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700659 log.info("Device {} is already connected to ONOS and is available", deviceId);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200660 return;
661 }
Andrea Campanella14e196d2017-07-24 18:11:36 +0200662 NodeId leaderNodeId = leadershipService.runForLeadership(DEPLOY + deviceId.toString() + PIPECONF_TOPIC)
663 .leader().nodeId();
664 NodeId localNodeId = clusterService.getLocalNode().id();
665 if (localNodeId.equals(leaderNodeId)) {
666 if (processEvent(event, deviceId)) {
667 log.debug("{} is leader for {}, initiating the connection and deploying pipeline", leaderNodeId,
668 deviceId);
669 checkAndSubmitDeviceTask(deviceId);
670 }
671 } else {
672 if (processEvent(event, deviceId)) {
673 log.debug("{} is not leader for {}, initiating connection but not deploying pipeline, {} is LEADER",
674 localNodeId, deviceId, leaderNodeId);
675 connectionExecutor.submit(exceptionSafe(() -> connectStandbyDevice(deviceId)));
676 //FIXME this will be removed when config is synced
677 cleanUpConfigInfo(deviceId);
678 }
679 }
Andrea Campanella14e196d2017-07-24 18:11:36 +0200680 }
681
682 private boolean processEvent(NetworkConfigEvent event, DeviceId deviceId) {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200683 //FIXME to be removed when netcfg will issue device events in a bundle or
684 // ensure all configuration needed is present
685 Lock lock = ENTRY_LOCKS.computeIfAbsent(deviceId, key -> new ReentrantLock());
686 lock.lock();
687 try {
688 if (event.configClass().equals(GeneralProviderDeviceConfig.class)) {
689 //FIXME we currently assume that p4runtime devices are pipeline configurable.
690 //If we want to connect a p4runtime device with no pipeline
691 if (event.config().isPresent() &&
692 Collections.disjoint(ImmutableSet.copyOf(event.config().get().node().fieldNames()),
Andrea Campanella19090322017-08-22 10:31:37 +0200693 PIPELINE_CONFIGURABLE_PROTOCOLS)) {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200694 pipelineConfigured.add(deviceId);
695 }
696 deviceConfigured.add(deviceId);
697 } else if (event.configClass().equals(BasicDeviceConfig.class)) {
698 if (event.config().isPresent() && event.config().get().node().has(DRIVER)) {
699 //TODO add check for pipeline and add it to the pipeline list if no
700 // p4runtime is present.
701 driverConfigured.add(deviceId);
702 }
703 } else if (event.configClass().equals(PiPipeconfConfig.class)) {
704 if (event.config().isPresent()
705 && event.config().get().node().has(PiPipeconfConfig.PIPIPECONFID)) {
706 pipelineConfigured.add(deviceId);
707 }
708 }
709 //if the device has no "pipeline configurable protocol it will be present
710 // in the pipelineConfigured
711 if (deviceConfigured.contains(deviceId) && driverConfigured.contains(deviceId)
712 && pipelineConfigured.contains(deviceId)) {
Andrea Campanella14e196d2017-07-24 18:11:36 +0200713 return true;
Andrea Campanellabc112a92017-06-26 19:06:43 +0200714 } else {
715 if (deviceConfigured.contains(deviceId) && driverConfigured.contains(deviceId)) {
716 log.debug("Waiting for pipeline configuration for device {}", deviceId);
717 } else if (pipelineConfigured.contains(deviceId) && driverConfigured.contains(deviceId)) {
718 log.debug("Waiting for device configuration for device {}", deviceId);
719 } else if (pipelineConfigured.contains(deviceId) && deviceConfigured.contains(deviceId)) {
720 log.debug("Waiting for driver configuration for device {}", deviceId);
721 } else if (driverConfigured.contains(deviceId)) {
722 log.debug("Only driver configuration for device {}", deviceId);
723 } else if (deviceConfigured.contains(deviceId)) {
724 log.debug("Only device configuration for device {}", deviceId);
725 }
726 }
Andrea Campanella14e196d2017-07-24 18:11:36 +0200727 return false;
Andrea Campanellabc112a92017-06-26 19:06:43 +0200728 } finally {
729 lock.unlock();
Andrea Campanella241896c2017-05-10 13:11:04 -0700730 }
731 }
732
733 @Override
734 public boolean isRelevant(NetworkConfigEvent event) {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200735 return (event.configClass().equals(GeneralProviderDeviceConfig.class) ||
736 event.configClass().equals(BasicDeviceConfig.class) ||
737 event.configClass().equals(PiPipeconfConfig.class)) &&
Andrea Campanella241896c2017-05-10 13:11:04 -0700738 (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
739 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED);
740 }
741 }
742
Andrea Campanellabc112a92017-06-26 19:06:43 +0200743 private void checkAndSubmitDeviceTask(DeviceId deviceId) {
744 connectionExecutor.submit(exceptionSafe(() -> connectDevice(deviceId)));
745 //FIXME this will be removed when configuration is synced.
Andrea Campanella14e196d2017-07-24 18:11:36 +0200746 cleanUpConfigInfo(deviceId);
747
748 }
749
750 private void addConfigData(GeneralProviderDeviceConfig providerConfig, DriverData driverData) {
751 //Storing deviceKeyId and all other config values
752 // as data in the driver with protocol_<info>
753 // name as the key. e.g protocol_ip
754 providerConfig.protocolsInfo()
755 .forEach((protocol, deviceInfoConfig) -> {
756 deviceInfoConfig.configValues()
757 .forEach((k, v) -> driverData.set(protocol + "_" + k, v));
758 driverData.set(protocol + "_key", deviceInfoConfig.deviceKeyId());
759 });
760 }
761
762 private void cleanUpConfigInfo(DeviceId deviceId) {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200763 deviceConfigured.remove(deviceId);
764 driverConfigured.remove(deviceId);
765 pipelineConfigured.remove(deviceId);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200766 }
767
Andrea Campanella1e573442018-05-17 17:07:13 +0200768 private ScheduledFuture<?> scheduleStatistcsPolling(DeviceId deviceId, boolean randomize) {
Andrea Campanella19090322017-08-22 10:31:37 +0200769 int delay = 0;
770 if (randomize) {
Ray Milkeyb68bbbc2017-12-18 10:05:49 -0800771 delay = new SecureRandom().nextInt(10);
Andrea Campanella19090322017-08-22 10:31:37 +0200772 }
773 return portStatsExecutor.scheduleAtFixedRate(
774 exceptionSafe(() -> updatePortStatistics(deviceId)),
775 delay, pollFrequency, TimeUnit.SECONDS);
776 }
777
Andrea Campanella1e573442018-05-17 17:07:13 +0200778 private void scheduleDevicePolling() {
779 cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class).forEach(this::checkAndConnect);
780 }
781
782 private void checkAndConnect(DeviceId deviceId) {
783 // Let's try and reconnect to a device which is stored in the net-cfg.
784 // One of the following conditions must be satisfied:
785 // 1) device is null in the store meaning that is was never connected or it was administratively removed
786 // 2) the device is not available and there is no MASTER instance, meaning the device lost
787 // it's connection to ONOS at some point in the past.
788 // We also check that the general device provider config and the driver config are present.
789 // We do not check for reachability using isReachable(deviceId) since the behaviour of this method
790 // can vary depending on protocol nuances. We leave this check to the device handshaker
791 // at later stages of the connection process.
792 // IF the conditions are not met but instead the device is present in the store, available and this instance is
793 // MASTER but is not reachable we remove it from the store.
794
795 if ((deviceService.getDevice(deviceId) == null || (!deviceService.isAvailable(deviceId) &&
796 mastershipService.getMasterFor(deviceId) == null)) && configIsPresent(deviceId)) {
797 log.debug("Trying to re-connect to device {}", deviceId);
798 NodeId leaderNodeId = leadershipService.runForLeadership(CHECK + deviceId.toString() + CONNECTION)
799 .leader().nodeId();
800 NodeId localNodeId = clusterService.getLocalNode().id();
801 if (localNodeId.equals(leaderNodeId)) {
802 log.debug("{} is leader for {}, initiating the connection", leaderNodeId,
803 deviceId);
804 checkAndSubmitDeviceTask(deviceId);
805 } else {
806 log.debug("{} is not leader for {}, initiating connection, {} is LEADER",
807 localNodeId, deviceId, leaderNodeId);
808 connectionExecutor.submit(exceptionSafe(() -> connectStandbyDevice(deviceId)));
809 //FIXME this will be removed when config is synced
810 cleanUpConfigInfo(deviceId);
811 }
812 } else if ((deviceService.getDevice(deviceId) != null && deviceService.isAvailable(deviceId)
813 && mastershipService.isLocalMaster(deviceId) && !isReachable(deviceId) && configIsPresent(deviceId))) {
814 log.info("Removing available but unreachable device {}", deviceId);
815 disconnectDevice(deviceId);
816 providerService.deviceDisconnected(deviceId);
817 }
818 }
819
820 private boolean configIsPresent(DeviceId deviceId) {
821 boolean present = cfgService.getConfig(deviceId, GeneralProviderDeviceConfig.class) != null
822 && cfgService.getConfig(deviceId, BasicDeviceConfig.class) != null;
823 if (!present) {
824 log.warn("Configuration for device {} is not complete", deviceId);
825 }
826 return present;
827 }
828
Andrea Campanella241896c2017-05-10 13:11:04 -0700829 /**
830 * Listener for core device events.
831 */
832 private class InternalDeviceListener implements DeviceListener {
833 @Override
834 public void event(DeviceEvent event) {
Andrea Campanellace111932017-09-18 16:59:56 +0900835 DeviceId deviceId = event.subject().id();
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700836 // FIXME handling for mastership change scenario missing?
Andrea Campanella241896c2017-05-10 13:11:04 -0700837
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700838 // For now this is scheduled periodically, when streaming API will
839 // be available we check and base it on the streaming API (e.g. gNMI)
840 if (mastershipService.isLocalMaster(deviceId)) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200841 scheduledTasks.put(deviceId, scheduleStatistcsPolling(deviceId, false));
Andrea Campanella241896c2017-05-10 13:11:04 -0700842 }
843 }
844
845 @Override
846 public boolean isRelevant(DeviceEvent event) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700847 return event.type() == Type.DEVICE_ADDED &&
848 event.subject().id().toString().startsWith(URI_SCHEME.toLowerCase());
Andrea Campanella241896c2017-05-10 13:11:04 -0700849 }
850 }
Andrea Campanella1e573442018-05-17 17:07:13 +0200851
852 /**
853 * Listener for device channel events.
854 */
855 private class InternalChannelListener implements ChannelListener {
856
857 @Override
858 public void event(ChannelEvent event) {
859 DeviceId deviceId = event.subject();
860 if (event.type().equals(ChannelEvent.Type.CHANNEL_DISCONNECTED)) {
861 //let's properly handle device disconnection
862 CompletableFuture<Boolean> disconnection = disconnectDevice(deviceId);
863 disconnection.thenAcceptAsync(result -> {
864 //If master notifying of disconnection to the core.
865 if (mastershipService.isLocalMaster(deviceId)) {
866 log.info("Disconnecting unreachable device {}, due to error on channel", deviceId);
867 providerService.deviceDisconnected(deviceId);
868 }
869 });
870
871 }
872 //TODO evaluate other type of reactions.
873 }
874
875 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700876}