blob: b892460bbdffe7d1e4d881cb8ab44e7b13c8135b [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
Andrea Campanellabc112a92017-06-26 19:06:43 +020019import com.google.common.collect.Maps;
Carmelo Cascone1dfc7862019-04-17 16:37:44 -070020import com.google.common.collect.Sets;
Carmelo Cascone61469462019-03-05 23:59:11 -080021import com.google.common.util.concurrent.Futures;
Andrea Campanella241896c2017-05-10 13:11:04 -070022import org.onlab.packet.ChassisId;
23import org.onlab.util.ItemNotFoundException;
Carmelo Cascone4b616312019-04-17 14:15:45 -070024import org.onlab.util.SharedScheduledExecutors;
Andrea Campanella19090322017-08-22 10:31:37 +020025import org.onlab.util.Tools;
Andrea Campanella4929a812017-10-09 18:38:23 +020026import org.onosproject.cfg.ComponentConfigService;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080027import org.onosproject.cluster.ClusterService;
28import org.onosproject.cluster.NodeId;
Andrea Campanella241896c2017-05-10 13:11:04 -070029import org.onosproject.core.CoreService;
Yi Tsenge616d752018-11-27 10:53:27 -080030import org.onosproject.gnmi.api.GnmiController;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080031import org.onosproject.mastership.MastershipInfo;
Andrea Campanella14e196d2017-07-24 18:11:36 +020032import org.onosproject.mastership.MastershipService;
Andrea Campanella241896c2017-05-10 13:11:04 -070033import org.onosproject.net.DefaultAnnotations;
34import org.onosproject.net.Device;
35import org.onosproject.net.DeviceId;
36import org.onosproject.net.MastershipRole;
37import org.onosproject.net.PortNumber;
Carmelo Cascone87892e22017-11-13 16:01:29 -080038import org.onosproject.net.behaviour.PiPipelineProgrammable;
Andrea Campanella241896c2017-05-10 13:11:04 -070039import org.onosproject.net.behaviour.PortAdmin;
Andrea Campanella241896c2017-05-10 13:11:04 -070040import org.onosproject.net.config.NetworkConfigEvent;
41import org.onosproject.net.config.NetworkConfigListener;
42import org.onosproject.net.config.NetworkConfigRegistry;
43import org.onosproject.net.config.basics.BasicDeviceConfig;
Andrea Campanella241896c2017-05-10 13:11:04 -070044import org.onosproject.net.device.DefaultDeviceDescription;
Thomas Vachuska1b3cf362019-08-29 17:11:18 -070045import org.onosproject.net.device.DeviceAdminService;
Carmelo Casconee5b28722018-06-22 17:28:28 +020046import org.onosproject.net.device.DeviceAgentEvent;
47import org.onosproject.net.device.DeviceAgentListener;
Andrea Campanella241896c2017-05-10 13:11:04 -070048import org.onosproject.net.device.DeviceDescription;
49import org.onosproject.net.device.DeviceDescriptionDiscovery;
Thomas Vachuska1b3cf362019-08-29 17:11:18 -070050import org.onosproject.net.device.DeviceEvent;
Andrea Campanella241896c2017-05-10 13:11:04 -070051import org.onosproject.net.device.DeviceHandshaker;
Thomas Vachuska1b3cf362019-08-29 17:11:18 -070052import org.onosproject.net.device.DeviceListener;
Andrea Campanella241896c2017-05-10 13:11:04 -070053import org.onosproject.net.device.DeviceProvider;
54import org.onosproject.net.device.DeviceProviderRegistry;
55import org.onosproject.net.device.DeviceProviderService;
Andrea Campanella241896c2017-05-10 13:11:04 -070056import org.onosproject.net.device.PortDescription;
Andrea Campanella241896c2017-05-10 13:11:04 -070057import org.onosproject.net.driver.Behaviour;
58import org.onosproject.net.driver.DefaultDriverData;
59import org.onosproject.net.driver.DefaultDriverHandler;
60import org.onosproject.net.driver.Driver;
61import org.onosproject.net.driver.DriverData;
62import org.onosproject.net.driver.DriverService;
Carmelo Cascone59f57de2017-07-11 19:55:09 -040063import org.onosproject.net.pi.model.PiPipeconf;
Andrea Campanellabc112a92017-06-26 19:06:43 +020064import org.onosproject.net.pi.model.PiPipeconfId;
Carmelo Cascone39c28ca2017-11-15 13:03:57 -080065import org.onosproject.net.pi.service.PiPipeconfService;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070066import org.onosproject.net.pi.service.PiPipeconfWatchdogEvent;
67import org.onosproject.net.pi.service.PiPipeconfWatchdogListener;
68import org.onosproject.net.pi.service.PiPipeconfWatchdogService;
Andrea Campanella241896c2017-05-10 13:11:04 -070069import org.onosproject.net.provider.AbstractProvider;
70import org.onosproject.net.provider.ProviderId;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080071import org.onosproject.provider.general.device.impl.DeviceTaskExecutor.DeviceTaskException;
Andrea Campanella19090322017-08-22 10:31:37 +020072import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070073import org.osgi.service.component.annotations.Activate;
74import org.osgi.service.component.annotations.Component;
75import org.osgi.service.component.annotations.Deactivate;
76import org.osgi.service.component.annotations.Modified;
77import org.osgi.service.component.annotations.Reference;
78import org.osgi.service.component.annotations.ReferenceCardinality;
Andrea Campanella241896c2017-05-10 13:11:04 -070079import org.slf4j.Logger;
80
Andrea Campanellabc112a92017-06-26 19:06:43 +020081import java.util.Collections;
Andrea Campanella19090322017-08-22 10:31:37 +020082import java.util.Dictionary;
Andrea Campanella241896c2017-05-10 13:11:04 -070083import java.util.List;
Thomas Vachuska5b38dc02018-05-10 15:24:40 -070084import java.util.Map;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080085import java.util.Objects;
Carmelo Cascone1dfc7862019-04-17 16:37:44 -070086import java.util.Set;
Andrea Campanella241896c2017-05-10 13:11:04 -070087import java.util.concurrent.CompletableFuture;
Carmelo Casconee5b28722018-06-22 17:28:28 +020088import java.util.concurrent.ExecutorService;
Andrea Campanella19090322017-08-22 10:31:37 +020089import java.util.concurrent.ScheduledFuture;
Andrea Campanella241896c2017-05-10 13:11:04 -070090import java.util.concurrent.TimeUnit;
Andrea Campanella241896c2017-05-10 13:11:04 -070091
Carmelo Cascone3977ea42019-02-28 13:43:42 -080092import static com.google.common.base.Preconditions.checkNotNull;
93import static com.google.common.base.Strings.isNullOrEmpty;
Carmelo Cascone61469462019-03-05 23:59:11 -080094import static java.lang.String.format;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080095import static java.lang.System.currentTimeMillis;
Carmelo Casconee5b28722018-06-22 17:28:28 +020096import static java.util.concurrent.Executors.newFixedThreadPool;
Andrea Campanella241896c2017-05-10 13:11:04 -070097import static org.onlab.util.Tools.groupedThreads;
Carmelo Cascone4b616312019-04-17 14:15:45 -070098import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.CHECKUP_INTERVAL;
99import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.CHECKUP_INTERVAL_DEFAULT;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800100import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.STATS_POLL_INTERVAL;
101import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.STATS_POLL_INTERVAL_DEFAULT;
Andrea Campanella241896c2017-05-10 13:11:04 -0700102import static org.slf4j.LoggerFactory.getLogger;
103
104/**
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800105 * Provider which uses drivers to discover devices, perform initial handshake,
106 * and notify the core of disconnection events. The implementation listens for
107 * events from netcfg or the drivers (via {@link DeviceAgentListener}) andP
108 * schedules task for each event.
Andrea Campanella241896c2017-05-10 13:11:04 -0700109 */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700110@Component(immediate = true,
111 property = {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700112 CHECKUP_INTERVAL + ":Integer=" + CHECKUP_INTERVAL_DEFAULT,
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800113 STATS_POLL_INTERVAL + ":Integer=" + STATS_POLL_INTERVAL_DEFAULT,
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700114 })
Andrea Campanella241896c2017-05-10 13:11:04 -0700115public class GeneralDeviceProvider extends AbstractProvider
116 implements DeviceProvider {
Carmelo Casconee5b28722018-06-22 17:28:28 +0200117
Andrea Campanella241896c2017-05-10 13:11:04 -0700118 private final Logger log = getLogger(getClass());
119
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800120 private static final String APP_NAME = "org.onosproject.generaldeviceprovider";
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700121 private static final String URI_SCHEME = "device";
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700122 private static final String DEVICE_PROVIDER_PACKAGE =
123 "org.onosproject.general.provider.device";
124 private static final int CORE_POOL_SIZE = 10;
125 private static final String UNKNOWN = "unknown";
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700126
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700127 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200128 private DeviceProviderRegistry providerRegistry;
Andrea Campanella241896c2017-05-10 13:11:04 -0700129
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700130 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200131 private ComponentConfigService componentConfigService;
Andrea Campanella4929a812017-10-09 18:38:23 +0200132
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700133 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200134 private NetworkConfigRegistry cfgService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700135
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200137 private CoreService coreService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700138
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700139 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700140 private DeviceAdminService deviceService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700141
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700142 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200143 private DriverService driverService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700144
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700145 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200146 private MastershipService mastershipService;
Andrea Campanella14e196d2017-07-24 18:11:36 +0200147
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700148 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800149 private ClusterService clusterService;
150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700152 private PiPipeconfService pipeconfService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700153
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700154 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700155 private PiPipeconfWatchdogService pipeconfWatchdogService;
Andrea Campanella14e196d2017-07-24 18:11:36 +0200156
Yi Tsenge616d752018-11-27 10:53:27 -0800157 // FIXME: no longer general if we add a dependency to a protocol-specific
158 // service. Possible solutions are: rename this provider to
159 // StratumDeviceProvider, find a way to allow this provider to register for
160 // protocol specific events (e.g. port events) via drivers (similar to
161 // DeviceAgentListener).
162 @Reference(cardinality = ReferenceCardinality.MANDATORY)
163 private GnmiController gnmiController;
164
165 private GnmiDeviceStateSubscriber gnmiDeviceStateSubscriber;
166
Carmelo Cascone61469462019-03-05 23:59:11 -0800167 /**
168 * Configure interval for checking device availability; default is 10 sec.
169 */
Carmelo Cascone4b616312019-04-17 14:15:45 -0700170 private int checkupInterval = CHECKUP_INTERVAL_DEFAULT;
Andrea Campanella19090322017-08-22 10:31:37 +0200171
Carmelo Cascone61469462019-03-05 23:59:11 -0800172 /**
173 * Configure poll frequency for port status and stats; default is 10 sec.
174 */
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800175 private int statsPollInterval = STATS_POLL_INTERVAL_DEFAULT;
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200176
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700177 private final Map<DeviceId, DeviceHandshaker> handshakersWithListeners = Maps.newConcurrentMap();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700178 private final Map<DeviceId, Long> lastCheckups = Maps.newConcurrentMap();
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700179 private final InternalPipeconfWatchdogListener pipeconfWatchdogListener = new InternalPipeconfWatchdogListener();
Carmelo Casconee5b28722018-06-22 17:28:28 +0200180 private final NetworkConfigListener cfgListener = new InternalNetworkConfigListener();
181 private final DeviceAgentListener deviceAgentListener = new InternalDeviceAgentListener();
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700182 private final DeviceListener deviceListener = new InternalDeviceListener();
Andrea Campanella241896c2017-05-10 13:11:04 -0700183
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800184 private ExecutorService mainExecutor;
185 private DeviceTaskExecutor<TaskType> taskExecutor;
Carmelo Cascone4b616312019-04-17 14:15:45 -0700186 private ScheduledFuture<?> checkupTask;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800187 private StatsPoller statsPoller;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700188 private DeviceProviderService providerService;
189
190 public GeneralDeviceProvider() {
191 super(new ProviderId(URI_SCHEME, DEVICE_PROVIDER_PACKAGE));
192 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700193
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800194 protected DeviceProviderService providerService() {
195 return providerService;
196 }
197
Andrea Campanella241896c2017-05-10 13:11:04 -0700198 @Activate
Andrea Campanella1e573442018-05-17 17:07:13 +0200199 public void activate(ComponentContext context) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800200 mainExecutor = newFixedThreadPool(CORE_POOL_SIZE, groupedThreads(
Carmelo Cascone4b616312019-04-17 14:15:45 -0700201 "onos/gdp", "%d", log));
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800202 taskExecutor = new DeviceTaskExecutor<>(mainExecutor);
Andrea Campanella241896c2017-05-10 13:11:04 -0700203 providerService = providerRegistry.register(this);
Andrea Campanella4929a812017-10-09 18:38:23 +0200204 componentConfigService.registerProperties(getClass());
Andrea Campanella241896c2017-05-10 13:11:04 -0700205 coreService.registerApplication(APP_NAME);
Andrea Campanella241896c2017-05-10 13:11:04 -0700206 cfgService.addListener(cfgListener);
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700207 deviceService.addListener(deviceListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700208 pipeconfWatchdogService.addListener(pipeconfWatchdogListener);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800209 gnmiDeviceStateSubscriber = new GnmiDeviceStateSubscriber(
210 gnmiController, deviceService, mastershipService, providerService);
Yi Tsenge616d752018-11-27 10:53:27 -0800211 gnmiDeviceStateSubscriber.activate();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700212 startOrReschedulePeriodicCheckupTasks();
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800213 statsPoller = new StatsPoller(deviceService, mastershipService, providerService);
214 statsPoller.activate(statsPollInterval);
215 modified(context);
Andrea Campanella241896c2017-05-10 13:11:04 -0700216 log.info("Started");
217 }
218
Andrea Campanella19090322017-08-22 10:31:37 +0200219 @Modified
220 public void modified(ComponentContext context) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200221 if (context == null) {
222 return;
Andrea Campanella19090322017-08-22 10:31:37 +0200223 }
224
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200225 Dictionary<?, ?> properties = context.getProperties();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700226 final int oldCheckupInterval = checkupInterval;
227 checkupInterval = Tools.getIntegerProperty(
228 properties, CHECKUP_INTERVAL, CHECKUP_INTERVAL_DEFAULT);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200229 log.info("Configured. {} is configured to {} seconds",
Carmelo Cascone4b616312019-04-17 14:15:45 -0700230 CHECKUP_INTERVAL, checkupInterval);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800231 final int oldStatsPollFrequency = statsPollInterval;
232 statsPollInterval = Tools.getIntegerProperty(
233 properties, STATS_POLL_INTERVAL, STATS_POLL_INTERVAL_DEFAULT);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200234 log.info("Configured. {} is configured to {} seconds",
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800235 STATS_POLL_INTERVAL, statsPollInterval);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200236
Carmelo Cascone4b616312019-04-17 14:15:45 -0700237 if (oldCheckupInterval != checkupInterval) {
238 startOrReschedulePeriodicCheckupTasks();
Andrea Campanella19090322017-08-22 10:31:37 +0200239 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200240
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800241 if (oldStatsPollFrequency != statsPollInterval) {
242 statsPoller.reschedule(statsPollInterval);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200243 }
Andrea Campanella19090322017-08-22 10:31:37 +0200244 }
245
Andrea Campanella241896c2017-05-10 13:11:04 -0700246 @Deactivate
247 public void deactivate() {
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700248 deviceService.removeListener(deviceListener);
249
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800250 // Shutdown stats poller.
251 statsPoller.deactivate();
252 statsPoller = null;
Carmelo Cascone4b616312019-04-17 14:15:45 -0700253 // Shutdown periodic checkup task.
254 checkupTask.cancel(false);
255 checkupTask = null;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800256 // Shutdown main and task executor.
257 taskExecutor.cancel();
258 taskExecutor = null;
259 mainExecutor.shutdownNow();
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700260 try {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800261 mainExecutor.awaitTermination(5, TimeUnit.SECONDS);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700262 } catch (InterruptedException e) {
263 log.warn("connectionExecutor not terminated properly");
264 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800265 mainExecutor = null;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700266 // Remove all device agent listeners
267 handshakersWithListeners.values().forEach(h -> h.removeDeviceAgentListener(id()));
268 handshakersWithListeners.clear();
269 // Other cleanup.
Carmelo Cascone4b616312019-04-17 14:15:45 -0700270 lastCheckups.clear();
Andrea Campanella4929a812017-10-09 18:38:23 +0200271 componentConfigService.unregisterProperties(getClass(), false);
Andrea Campanella241896c2017-05-10 13:11:04 -0700272 cfgService.removeListener(cfgListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700273 pipeconfWatchdogService.removeListener(pipeconfWatchdogListener);
Andrea Campanella241896c2017-05-10 13:11:04 -0700274 providerRegistry.unregister(this);
275 providerService = null;
Yi Tsenge616d752018-11-27 10:53:27 -0800276 gnmiDeviceStateSubscriber.deactivate();
277 gnmiDeviceStateSubscriber = null;
Andrea Campanella241896c2017-05-10 13:11:04 -0700278 log.info("Stopped");
279 }
280
Andrea Campanella241896c2017-05-10 13:11:04 -0700281 @Override
282 public void triggerProbe(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800283 checkNotNull(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700284 submitTask(deviceId, TaskType.CHECKUP);
Andrea Campanella241896c2017-05-10 13:11:04 -0700285 }
286
287 @Override
288 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800289 final MastershipInfo mastershipInfo = mastershipService.getMastershipFor(deviceId);
290 final NodeId localNodeId = clusterService.getLocalNode().id();
291
292 if (!mastershipInfo.getRole(localNodeId).equals(newRole)) {
293 log.warn("Inconsistent mastership info for {}! Requested {}, but " +
294 "mastership service reports {}, will apply the latter...",
295 deviceId, newRole, mastershipInfo.getRole(localNodeId));
296 newRole = mastershipInfo.getRole(localNodeId);
297 }
298
Carmelo Cascone4b616312019-04-17 14:15:45 -0700299 final DeviceHandshaker handshaker = getBehaviour(
300 deviceId, DeviceHandshaker.class);
301 if (handshaker == null) {
302 log.error("Null handshaker. Unable to notify role {} to {}",
303 newRole, deviceId);
304 return;
305 }
306
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800307 // Derive preference value.
308 final int preference;
309 switch (newRole) {
310 case MASTER:
311 preference = 0;
312 break;
313 case STANDBY:
314 preference = mastershipInfo.backups().indexOf(localNodeId) + 1;
315 if (preference == 0) {
316 // Not found in list.
317 log.error("Unable to derive mastership preference for {}, " +
318 "requested role {} but local node ID was " +
319 "not found among list of backup nodes " +
Carmelo Cascone4b616312019-04-17 14:15:45 -0700320 "reported by mastership service",
321 deviceId, newRole);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800322 return;
323 }
324 break;
325 case NONE:
326 // No preference for NONE, apply as is.
327 log.info("Notifying role {} to {}", newRole, deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700328 handshaker.roleChanged(newRole);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800329 return;
330 default:
331 log.error("Unrecognized mastership role {}", newRole);
332 return;
333 }
334
335 log.info("Notifying role {} (preference {}) for term {} to {}",
336 newRole, preference, mastershipInfo.term(), deviceId);
337
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800338 try {
339 handshaker.roleChanged(preference, mastershipInfo.term());
340 } catch (UnsupportedOperationException e) {
341 // Preference-based method not supported.
342 handshaker.roleChanged(newRole);
343 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700344 }
345
346 @Override
347 public boolean isReachable(DeviceId deviceId) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700348 final DeviceHandshaker handshaker = getBehaviour(
349 deviceId, DeviceHandshaker.class);
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100350 if (handshaker == null) {
351 return false;
352 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800353 return handshaker.isReachable();
Andrea Campanella241896c2017-05-10 13:11:04 -0700354 }
355
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800356 @Override
357 public boolean isAvailable(DeviceId deviceId) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700358 final DeviceHandshaker handshaker = getBehaviour(
359 deviceId, DeviceHandshaker.class);
360 if (handshaker == null) {
361 return false;
362 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800363 try {
364 // Try without probing the device...
365 return handshaker.isAvailable();
366 } catch (UnsupportedOperationException e) {
367 // Driver does not support that.
368 return probeAvailability(handshaker);
369 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700370 }
371
Andrea Campanella241896c2017-05-10 13:11:04 -0700372 @Override
373 public void changePortState(DeviceId deviceId, PortNumber portNumber,
374 boolean enable) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200375 if (!deviceService.getDevice(deviceId).is(PortAdmin.class)) {
376 log.warn("Missing PortAdmin behaviour on {}, aborting port state change",
377 deviceId);
378 return;
Andrea Campanella241896c2017-05-10 13:11:04 -0700379 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200380 final PortAdmin portAdmin = deviceService.getDevice(deviceId)
381 .as(PortAdmin.class);
382 final CompletableFuture<Boolean> modifyTask = enable
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200383 ? portAdmin.enable(portNumber)
384 : portAdmin.disable(portNumber);
Carmelo Cascone61469462019-03-05 23:59:11 -0800385 final String descr = format("%s port %s on %s",
386 (enable ? "enable" : "disable"),
387 portNumber, deviceId);
388 modifyTask.whenComplete((success, ex) -> {
389 if (ex != null) {
390 log.error("Exception while trying to " + descr, ex);
391 } else if (!success) {
392 log.warn("Unable to " + descr);
393 }
394 });
Andrea Campanella241896c2017-05-10 13:11:04 -0700395 }
396
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700397 @Override
398 public void triggerDisconnect(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800399 checkNotNull(deviceId);
400 log.info("Triggering disconnection of device {}", deviceId);
401 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
402 }
403
404 /**
405 * Listener for configuration events.
406 */
407 private class InternalNetworkConfigListener implements NetworkConfigListener {
408 @Override
409 public void event(NetworkConfigEvent event) {
410 DeviceId deviceId = (DeviceId) event.subject();
411 switch (event.type()) {
412 case CONFIG_ADDED:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700413 if (configIsPresent(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800414 submitTask(deviceId, TaskType.CONNECTION_SETUP);
415 }
416 break;
417 case CONFIG_UPDATED:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700418 if (configIsPresent(deviceId) && mgmtAddrUpdated(event)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800419 submitTask(deviceId, TaskType.CONNECTION_UPDATE);
420 }
421 break;
422 case CONFIG_REMOVED:
423 if (event.configClass().equals(BasicDeviceConfig.class)) {
424 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
425 }
426 break;
427 default:
428 // Ignore
429 break;
430 }
431 }
432
433 private boolean mgmtAddrUpdated(NetworkConfigEvent event) {
434 if (!event.prevConfig().isPresent() || !event.config().isPresent()) {
435 return false;
436 }
437 final BasicDeviceConfig prev = (BasicDeviceConfig) event.prevConfig().get();
438 final BasicDeviceConfig current = (BasicDeviceConfig) event.config().get();
439 return !Objects.equals(prev.managementAddress(), current.managementAddress());
440 }
441
442 @Override
443 public boolean isRelevant(NetworkConfigEvent event) {
444 return event.configClass().equals(BasicDeviceConfig.class) &&
445 (event.subject() instanceof DeviceId) &&
446 myScheme((DeviceId) event.subject());
447 }
448 }
449
450 /**
451 * Listener for device agent events.
452 */
453 private class InternalDeviceAgentListener implements DeviceAgentListener {
454 @Override
455 public void event(DeviceAgentEvent event) {
456 DeviceId deviceId = event.subject();
457 switch (event.type()) {
458 case CHANNEL_OPEN:
459 submitTask(deviceId, TaskType.CHANNEL_OPEN);
460 break;
461 case CHANNEL_CLOSED:
462 case CHANNEL_ERROR:
463 submitTask(deviceId, TaskType.CHANNEL_CLOSED);
464 break;
465 case ROLE_MASTER:
466 submitTask(deviceId, TaskType.ROLE_MASTER);
467 break;
468 case ROLE_STANDBY:
469 submitTask(deviceId, TaskType.ROLE_STANDBY);
470 break;
471 case ROLE_NONE:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700472 // FIXME: in case of device disconnection, agents will
473 // signal role NONE, preventing the DeviceManager to mark
474 // the device as offline, as only the master can do that. We
475 // should change the DeviceManager. For now, we disable
476 // signaling role NONE.
477 // submitTask(deviceId, TaskType.ROLE_NONE);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800478 break;
479 case NOT_MASTER:
480 submitTask(deviceId, TaskType.NOT_MASTER);
481 break;
482 default:
483 log.warn("Unrecognized device agent event {}", event.type());
484 }
485 }
486 }
487
488 /**
489 * Pipeline event listener.
490 */
491 private class InternalPipeconfWatchdogListener implements PiPipeconfWatchdogListener {
492 @Override
493 public void event(PiPipeconfWatchdogEvent event) {
494 final DeviceId deviceId = event.subject();
495 switch (event.type()) {
496 case PIPELINE_READY:
497 submitTask(deviceId, TaskType.PIPELINE_READY);
498 break;
499 case PIPELINE_UNKNOWN:
500 submitTask(deviceId, TaskType.PIPELINE_NOT_READY);
501 break;
502 default:
503 break;
504 }
505 }
506
507 @Override
508 public boolean isRelevant(PiPipeconfWatchdogEvent event) {
509 return myScheme(event.subject());
510 }
511 }
512
Carmelo Cascone4b616312019-04-17 14:15:45 -0700513 private void startOrReschedulePeriodicCheckupTasks() {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800514 synchronized (this) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700515 if (checkupTask != null) {
516 checkupTask.cancel(false);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800517 }
Carmelo Cascone4b616312019-04-17 14:15:45 -0700518 checkupTask = SharedScheduledExecutors.getPoolThreadExecutor()
519 .scheduleAtFixedRate(
520 this::submitCheckupTasksForAllDevices,
521 1,
522 checkupInterval,
pierventreb4120ff2021-04-09 14:32:11 +0200523 TimeUnit.SECONDS,
524 true);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800525 }
526 }
527
Carmelo Cascone4b616312019-04-17 14:15:45 -0700528 private void submitCheckupTasksForAllDevices() {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800529 // Async trigger a task for all devices in the cfg.
Carmelo Cascone4b616312019-04-17 14:15:45 -0700530 log.debug("Submitting checkup task for all devices...");
Carmelo Cascone1dfc7862019-04-17 16:37:44 -0700531 final Set<DeviceId> deviceToCheck = Sets.newHashSet();
532 // All devices in the core and in the config that we care about.
533 deviceService.getDevices().forEach(d -> {
534 if (myScheme(d.id())) {
535 deviceToCheck.add(d.id());
536 }
537 });
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800538 cfgService.getSubjects(DeviceId.class).stream()
539 .filter(GeneralDeviceProvider::myScheme)
Carmelo Cascone1dfc7862019-04-17 16:37:44 -0700540 .filter(this::configIsPresent)
541 .forEach(deviceToCheck::add);
542 deviceToCheck.forEach(d -> submitTask(d, TaskType.CHECKUP));
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800543 }
544
545 /**
546 * Type of tasks performed by this provider.
547 */
548 enum TaskType {
549 CONNECTION_SETUP,
550 CONNECTION_UPDATE,
551 CONNECTION_TEARDOWN,
552 PIPELINE_READY,
553 CHANNEL_OPEN,
554 CHANNEL_CLOSED,
555 PIPELINE_NOT_READY,
Carmelo Cascone4b616312019-04-17 14:15:45 -0700556 CHECKUP,
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800557 ROLE_MASTER,
558 ROLE_NONE,
559 ROLE_STANDBY,
560 NOT_MASTER,
561 }
562
563 private void submitTask(DeviceId deviceId, TaskType taskType) {
564 taskExecutor.submit(deviceId, taskType, taskRunnable(deviceId, taskType));
565 }
566
567 private Runnable taskRunnable(DeviceId deviceId, TaskType taskType) {
568 switch (taskType) {
569 case CONNECTION_SETUP:
570 return () -> handleConnectionSetup(deviceId);
571 case CONNECTION_UPDATE:
572 return () -> handleConnectionUpdate(deviceId);
573 case CONNECTION_TEARDOWN:
574 return () -> handleConnectionTeardown(deviceId);
575 case CHANNEL_OPEN:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700576 case CHECKUP:
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800577 case PIPELINE_READY:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700578 return () -> doCheckupAndRepair(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700579 case CHANNEL_CLOSED:
580 case PIPELINE_NOT_READY:
581 return () -> markOfflineIfNeeded(deviceId);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800582 case ROLE_MASTER:
583 return () -> handleMastershipResponse(deviceId, MastershipRole.MASTER);
584 case ROLE_STANDBY:
585 return () -> handleMastershipResponse(deviceId, MastershipRole.STANDBY);
586 case ROLE_NONE:
587 return () -> handleMastershipResponse(deviceId, MastershipRole.NONE);
588 case NOT_MASTER:
589 return () -> handleNotMaster(deviceId);
590 default:
591 throw new IllegalArgumentException("Unrecognized task type " + taskType);
592 }
593 }
594
595 private void handleConnectionSetup(DeviceId deviceId) {
596 assertConfig(deviceId);
597 // Bind pipeconf (if any and if device is capable).
598 bindPipeconfIfRequired(deviceId);
599 // Get handshaker.
600 final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700601 if (handshaker.hasConnection() || handshakersWithListeners.containsKey(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800602 throw new DeviceTaskException("connection already exists");
603 }
604 // Add device agent listener.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800605 handshakersWithListeners.put(deviceId, handshaker);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700606 handshaker.addDeviceAgentListener(id(), deviceAgentListener);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800607 // Start connection via handshaker.
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700608 if (!handshaker.connect()) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800609 // Failed! Remove listeners.
610 handshaker.removeDeviceAgentListener(id());
611 handshakersWithListeners.remove(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700612 // Clean up connection state leftovers.
613 handshaker.disconnect();
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800614 throw new DeviceTaskException("connection failed");
615 }
616 createOrUpdateDevice(deviceId, false);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800617 // From here we expect a CHANNEL_OPEN event to update availability.
618 }
619
620 private void handleConnectionUpdate(DeviceId deviceId) {
621 assertConfig(deviceId);
622 final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700623 if (!handshaker.hasConnection()) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800624 // If driver reports that a connection still exists, perhaps the
625 // part of the netcfg that changed does not affect the connection.
626 // Otherwise, remove any previous connection state from the old
627 // netcfg and create a new one.
628 log.warn("Detected change of connection endpoints for {}, will " +
629 "tear down existing connection and set up a new one...",
630 deviceId);
631 handleConnectionTeardown(deviceId);
632 handleConnectionSetup(deviceId);
633 }
634 }
635
636 private void createOrUpdateDevice(DeviceId deviceId, boolean available) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800637 assertConfig(deviceId);
pierventreb4120ff2021-04-09 14:32:11 +0200638
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700639 if (available) {
Carmelo Casconed51a5552019-04-13 01:22:25 -0700640 // Push port descriptions. If marking online, make sure to update
641 // ports before other subsystems pick up the device event.
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700642 final List<PortDescription> ports = getPortDetails(deviceId);
643 providerService.updatePorts(deviceId, ports);
644 }
pierventreb4120ff2021-04-09 14:32:11 +0200645
pierventree1f80102021-10-01 22:01:22 +0200646 DeviceDescription deviceDescription = getDeviceDescription(deviceId, available);
647 DeviceDescription storeDescription = providerService.getDeviceDescription(deviceId);
648 if (deviceService.getDevice(deviceId) != null &&
649 deviceService.isAvailable(deviceId) == available &&
650 storeDescription != null) {
651 /*
652 * FIXME SDFAB-650 rethink the APIs and abstractions around the DeviceStore.
653 * Device registration is a two-step process for the GDP. Initially, the device is
654 * registered with default avail. to false. Later, the checkup task will update the
655 * description with the default avail to true in order to mark it available. Today,
656 * there is only one API to mark online a device from the device provider which is
657 * deviceConnected which assumes an update on the device description. The device provider
658 * is the only one able to update the device description and we have to make sure that
659 * the default avail. is flipped to true as it is used to mark as online the device when
660 * it is created or updated. Otherwise, if an ONOS instance fails and restarts, when re-joining
661 * the cluster, it will get the device marked as offline and will not be able to update
662 * its status until it become the master. This process concurs with the markOnline done
663 * by the background thread in the DeviceManager and its the reason why we cannot just check
664 * the device availability but we need to compare also the desc. Checking here the equality,
665 * as in general we may want to upgrade the device description at run time.
666 */
667 DeviceDescription testDeviceDescription = DefaultDeviceDescription.copyReplacingAnnotation(
668 deviceDescription, storeDescription.annotations());
669 if (testDeviceDescription.equals(storeDescription)) {
670 return;
671 }
pierventreb4120ff2021-04-09 14:32:11 +0200672 }
pierventree1f80102021-10-01 22:01:22 +0200673
674 providerService.deviceConnected(deviceId, deviceDescription);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800675 }
676
677 private boolean probeAvailability(DeviceHandshaker handshaker) {
Carmelo Cascone61469462019-03-05 23:59:11 -0800678 return Futures.getUnchecked(handshaker.probeAvailability());
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800679 }
680
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800681 private void markOfflineIfNeeded(DeviceId deviceId) {
682 assertDeviceRegistered(deviceId);
683 if (deviceService.isAvailable(deviceId)) {
684 providerService.deviceDisconnected(deviceId);
685 }
686 }
687
Carmelo Cascone4b616312019-04-17 14:15:45 -0700688 private void doCheckupAndRepair(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800689
Carmelo Cascone4b616312019-04-17 14:15:45 -0700690 // This task should be invoked periodically for each device known by
691 // this provider, or as a consequence of events signaling potential
692 // availability changes of the device. We check that everything is in
693 // order, repair what's wrong, and eventually mark the the device as
694 // available (or not) in the core.
695
696 if (!configIsPresent(deviceId)) {
697 // We should have a connection only for devices in the config.
698 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
699 return;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800700 }
701
Carmelo Cascone4b616312019-04-17 14:15:45 -0700702 final DeviceHandshaker handshaker = handshakersWithListeners.get(deviceId);
703 if (handshaker == null) {
704 // Device in config but we have not initiated a connection.
705 // Perhaps we missed the config event?
706 submitTask(deviceId, TaskType.CONNECTION_SETUP);
707 return;
708 }
709
710 // If here, we have a handshaker meaning we already connected once to
711 // the device...
712 if (!handshaker.hasConnection()) {
713 // ... but now the driver reports there is NOT a connection.
714 // Perhaps the netcfg changed and we didn't pick the event?
715 log.warn("Re-establishing lost connection to {}", deviceId);
716 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
717 submitTask(deviceId, TaskType.CONNECTION_SETUP);
718 return;
719 }
720
721 // If here, device should be registered in the core.
722 assertDeviceRegistered(deviceId);
723
724 if (!handshaker.isReachable()) {
725 // Device appears to be offline.
726 markOfflineIfNeeded(deviceId);
727 // While we expect the protocol layer to implement some sort of
728 // connection backoff mechanism and to signal availability via
729 // CHANNEL_OPEN events, we stimulate some channel activity now.
730 // Trigger probe over the network and forget about it (not waiting
731 // for future to complete). If channel is ready, we expect to come
732 // back here via a CHANNEL_OPEN event.
733 handshaker.probeReachability();
734 return;
735 }
736
737 // If here, device is reachable. Now do mastership and availability
738 // checkups. To avoid overload of checkup tasks which might involve
739 // sending messages over the network and triggering mastership
740 // elections. We require a minimum interval of 1/3 of the configured
741 // checkupInterval between consecutive checkup tasks when the device is
742 // known to be available.
743
744 final Long lastCheckup = lastCheckups.get(deviceId);
745 final boolean isAvailable = deviceService.isAvailable(deviceId);
746 if (isAvailable && lastCheckup != null &&
747 (currentTimeMillis() - lastCheckup) < (checkupInterval * 1000 / 3)) {
748 if (log.isDebugEnabled()) {
749 log.debug("Dropping checkup task for {} as it happened recently",
750 deviceId);
751 }
752 return;
753 }
754 lastCheckups.put(deviceId, currentTimeMillis());
755
756 // Make sure device has a valid mastership role.
757 final MastershipRole expectedRole = mastershipService.getLocalRole(deviceId);
758 if (expectedRole == MastershipRole.NONE) {
759 log.debug("Detected invalid role ({}) for {}, waiting for mastership " +
760 "service to fix this...",
761 expectedRole, deviceId);
762 // Gentle nudge to fix things...
763 mastershipService.requestRoleForSync(deviceId);
764 return;
765 }
766
767 final MastershipRole deviceRole = handshaker.getRole();
768 if (expectedRole != deviceRole) {
769 // FIXME: we should be checking the mastership term as well.
770 log.debug("Detected role mismatch for {}, core expects {}, " +
771 "but device reports {}, waiting for mastership " +
772 "service to fix this...",
773 deviceId, expectedRole, deviceRole);
774 // Gentle nudge to fix things...
775 providerService.receivedRoleReply(deviceId, deviceRole);
776 return;
777 }
778
779 // Check and update availability, which differently from reachability
780 // describes the ability of the device to forward packets.
781 if (probeAvailability(handshaker)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800782 // Device ready to do its job.
783 createOrUpdateDevice(deviceId, true);
784 } else {
785 markOfflineIfNeeded(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700786 if (isPipelineProgrammable(deviceId)) {
787 // If reachable, but not available, and pipeline programmable,
788 // there is a high chance it's because the pipeline is not READY
789 // (independently from what the pipeconf watchdog reports, as
790 // the status there might be outdated). Encourage pipeconf
791 // watchdog to perform a pipeline probe ASAP.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800792 pipeconfWatchdogService.triggerProbe(deviceId);
793 }
794 }
795 }
796
797 private void handleMastershipResponse(DeviceId deviceId, MastershipRole response) {
798 assertDeviceRegistered(deviceId);
799 log.debug("Device {} asserted role {}", deviceId, response);
800 providerService.receivedRoleReply(deviceId, response);
801 }
802
803 private void handleNotMaster(DeviceId deviceId) {
804 assertDeviceRegistered(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700805 handleMastershipResponse(deviceId, handshakerOrFail(deviceId).getRole());
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800806 }
807
808 private void assertDeviceRegistered(DeviceId deviceId) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700809 if (!deviceIsRegistered(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800810 throw new DeviceTaskException("device not registered in the core");
811 }
812 }
813
Carmelo Cascone4b616312019-04-17 14:15:45 -0700814 private boolean deviceIsRegistered(DeviceId deviceId) {
815 return deviceService.getDevice(deviceId) != null;
816 }
817
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800818 private void handleConnectionTeardown(DeviceId deviceId) {
819 if (deviceService.getDevice(deviceId) != null
820 && deviceService.isAvailable(deviceId)) {
821 providerService.deviceDisconnected(deviceId);
822 }
823 final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
824 handshaker.removeDeviceAgentListener(id());
825 handshakersWithListeners.remove(deviceId);
826 handshaker.disconnect();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700827 lastCheckups.remove(deviceId);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800828 }
829
830 private void bindPipeconfIfRequired(DeviceId deviceId) {
831 if (pipeconfService.getPipeconf(deviceId).isPresent()
832 || !isPipelineProgrammable(deviceId)) {
833 // Nothing to do.
834 // Device has already a pipeconf or is not programmable.
835 return;
836 }
837 // Get pipeconf from netcfg or driver (default one).
838 final PiPipelineProgrammable pipelineProg = getBehaviour(
839 deviceId, PiPipelineProgrammable.class);
840 final PiPipeconfId pipeconfId = getPipeconfId(deviceId, pipelineProg);
841 if (pipeconfId == null) {
842 throw new DeviceTaskException("unable to find pipeconf");
843 }
Carmelo Cascone4b616312019-04-17 14:15:45 -0700844 if (!pipeconfService.getPipeconf(pipeconfId).isPresent()) {
845 throw new DeviceTaskException(format(
846 "pipeconf %s not registered", pipeconfId));
847 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800848 // Store binding in pipeconf service.
849 pipeconfService.bindToDevice(pipeconfId, deviceId);
850 }
851
852 private PiPipeconfId getPipeconfId(DeviceId deviceId, PiPipelineProgrammable pipelineProg) {
853 // Places to look for a pipeconf ID (in priority order)):
854 // 1) netcfg
855 // 2) device driver (default one)
856 final PiPipeconfId pipeconfId = getPipeconfFromCfg(deviceId);
857 if (pipeconfId != null && !pipeconfId.id().isEmpty()) {
858 return pipeconfId;
859 }
860 if (pipelineProg != null
861 && pipelineProg.getDefaultPipeconf().isPresent()) {
862 final PiPipeconf defaultPipeconf = pipelineProg.getDefaultPipeconf().get();
863 log.info("Using default pipeconf {} for {}", defaultPipeconf.id(), deviceId);
864 return defaultPipeconf.id();
865 }
866 return null;
867 }
868
869 private PiPipeconfId getPipeconfFromCfg(DeviceId deviceId) {
870 BasicDeviceConfig config = cfgService.getConfig(
871 deviceId, BasicDeviceConfig.class);
872 if (config == null) {
873 return null;
874 }
875 return config.pipeconf() != null
876 ? new PiPipeconfId(config.pipeconf()) : null;
877 }
878
879 private DeviceHandshaker handshakerOrFail(DeviceId deviceId) {
880 final DeviceHandshaker handshaker = getBehaviour(
881 deviceId, DeviceHandshaker.class);
882 if (handshaker == null) {
883 throw new DeviceTaskException("missing handshaker behavior");
884 }
885 return handshaker;
886 }
887
Carmelo Cascone4b616312019-04-17 14:15:45 -0700888 private boolean configIsPresent(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800889 final BasicDeviceConfig basicDeviceCfg = cfgService.getConfig(
890 deviceId, BasicDeviceConfig.class);
891 return basicDeviceCfg != null && !isNullOrEmpty(basicDeviceCfg.driver());
892 }
893
894 private void assertConfig(DeviceId deviceId) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700895 if (!configIsPresent(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800896 throw new DeviceTaskException("configuration is not complete");
897 }
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700898 }
899
Andrea Campanella241896c2017-05-10 13:11:04 -0700900 private Driver getDriver(DeviceId deviceId) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700901 try {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200902 // DriverManager checks first using basic device config.
903 return driverService.getDriver(deviceId);
Andrea Campanella241896c2017-05-10 13:11:04 -0700904 } catch (ItemNotFoundException e) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200905 log.error("Driver not found for {}", deviceId);
906 return null;
Andrea Campanella241896c2017-05-10 13:11:04 -0700907 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700908 }
909
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700910 private <T extends Behaviour> T getBehaviour(DeviceId deviceId, Class<T> type) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700911 Driver driver = getDriver(deviceId);
912 if (driver == null) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700913 return null;
914 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700915 if (!driver.hasBehaviour(type)) {
916 return null;
917 }
918 final DriverData data = new DefaultDriverData(driver, deviceId);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700919 final DefaultDriverHandler handler = new DefaultDriverHandler(data);
920 return driver.createBehaviour(handler, type);
Andrea Campanella241896c2017-05-10 13:11:04 -0700921 }
922
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800923 private boolean hasBehaviour(DeviceId deviceId, Class<? extends Behaviour> type) {
924 Driver driver = getDriver(deviceId);
925 if (driver == null) {
926 return false;
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200927 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800928 return driver.hasBehaviour(type);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700929 }
930
931 private DeviceDescription getDeviceDescription(
932 DeviceId deviceId, boolean defaultAvailable) {
933 // Get one from driver or forge.
934 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
935 deviceId, DeviceDescriptionDiscovery.class);
Yi Tsengd7716482018-10-31 15:34:30 -0700936 if (deviceDiscovery == null) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700937 return forgeDeviceDescription(deviceId, defaultAvailable);
938 }
Yi Tsengd7716482018-10-31 15:34:30 -0700939
940 final DeviceDescription d = deviceDiscovery.discoverDeviceDetails();
941 if (d == null) {
942 return forgeDeviceDescription(deviceId, defaultAvailable);
943 }
944 // Enforce defaultAvailable flag over the one obtained from driver.
945 return new DefaultDeviceDescription(d, defaultAvailable, d.annotations());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700946 }
947
948 private List<PortDescription> getPortDetails(DeviceId deviceId) {
949 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
950 deviceId, DeviceDescriptionDiscovery.class);
951 if (deviceDiscovery != null) {
952 return deviceDiscovery.discoverPortDetails();
953 } else {
954 return Collections.emptyList();
955 }
956 }
957
958 private DeviceDescription forgeDeviceDescription(
959 DeviceId deviceId, boolean defaultAvailable) {
960 // Uses handshaker and provider config to get driver data.
961 final DeviceHandshaker handshaker = getBehaviour(
962 deviceId, DeviceHandshaker.class);
963 final Driver driver = handshaker != null
964 ? handshaker.handler().driver() : null;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700965 return new DefaultDeviceDescription(
966 deviceId.uri(),
967 Device.Type.SWITCH,
968 driver != null ? driver.manufacturer() : UNKNOWN,
969 driver != null ? driver.hwVersion() : UNKNOWN,
970 driver != null ? driver.swVersion() : UNKNOWN,
971 UNKNOWN,
972 new ChassisId(),
973 defaultAvailable,
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800974 DefaultAnnotations.EMPTY);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700975 }
976
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800977 static boolean myScheme(DeviceId deviceId) {
978 return deviceId.uri().getScheme().equals(URI_SCHEME);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200979 }
980
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700981 private boolean isPipelineProgrammable(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800982 return hasBehaviour(deviceId, PiPipelineProgrammable.class);
Carmelo Casconede3b6842018-09-05 17:45:10 -0700983 }
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700984
985 private class InternalDeviceListener implements DeviceListener {
986 @Override
987 public void event(DeviceEvent event) {
988 log.info("Triggering disconnect for device {}", event.subject().id());
989 triggerDisconnect(event.subject().id());
990 }
991
992 @Override
993 public boolean isRelevant(DeviceEvent event) {
Thomas Vachuska24c0ca42019-08-29 18:19:16 -0700994 return DeviceEvent.Type.DEVICE_REMOVED == event.type() && myScheme(event.subject().id());
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700995 }
996 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700997}