blob: 6b19cc8ff1f6022033f24eb068601561c164d526 [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,
pierventre475290e2021-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);
pierventre475290e2021-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 }
pierventre475290e2021-04-09 14:32:11 +0200645
646 if (deviceService.getDevice(deviceId) != null
647 && deviceService.isAvailable(deviceId) == available) {
648 // Other nodes might have advertised this device before us.
649 return;
650 }
Carmelo Casconed51a5552019-04-13 01:22:25 -0700651 providerService.deviceConnected(deviceId, getDeviceDescription(
652 deviceId, available));
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800653 }
654
655 private boolean probeAvailability(DeviceHandshaker handshaker) {
Carmelo Cascone61469462019-03-05 23:59:11 -0800656 return Futures.getUnchecked(handshaker.probeAvailability());
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800657 }
658
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800659 private void markOfflineIfNeeded(DeviceId deviceId) {
660 assertDeviceRegistered(deviceId);
661 if (deviceService.isAvailable(deviceId)) {
662 providerService.deviceDisconnected(deviceId);
663 }
664 }
665
Carmelo Cascone4b616312019-04-17 14:15:45 -0700666 private void doCheckupAndRepair(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800667
Carmelo Cascone4b616312019-04-17 14:15:45 -0700668 // This task should be invoked periodically for each device known by
669 // this provider, or as a consequence of events signaling potential
670 // availability changes of the device. We check that everything is in
671 // order, repair what's wrong, and eventually mark the the device as
672 // available (or not) in the core.
673
674 if (!configIsPresent(deviceId)) {
675 // We should have a connection only for devices in the config.
676 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
677 return;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800678 }
679
Carmelo Cascone4b616312019-04-17 14:15:45 -0700680 final DeviceHandshaker handshaker = handshakersWithListeners.get(deviceId);
681 if (handshaker == null) {
682 // Device in config but we have not initiated a connection.
683 // Perhaps we missed the config event?
684 submitTask(deviceId, TaskType.CONNECTION_SETUP);
685 return;
686 }
687
688 // If here, we have a handshaker meaning we already connected once to
689 // the device...
690 if (!handshaker.hasConnection()) {
691 // ... but now the driver reports there is NOT a connection.
692 // Perhaps the netcfg changed and we didn't pick the event?
693 log.warn("Re-establishing lost connection to {}", deviceId);
694 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
695 submitTask(deviceId, TaskType.CONNECTION_SETUP);
696 return;
697 }
698
699 // If here, device should be registered in the core.
700 assertDeviceRegistered(deviceId);
701
702 if (!handshaker.isReachable()) {
703 // Device appears to be offline.
704 markOfflineIfNeeded(deviceId);
705 // While we expect the protocol layer to implement some sort of
706 // connection backoff mechanism and to signal availability via
707 // CHANNEL_OPEN events, we stimulate some channel activity now.
708 // Trigger probe over the network and forget about it (not waiting
709 // for future to complete). If channel is ready, we expect to come
710 // back here via a CHANNEL_OPEN event.
711 handshaker.probeReachability();
712 return;
713 }
714
715 // If here, device is reachable. Now do mastership and availability
716 // checkups. To avoid overload of checkup tasks which might involve
717 // sending messages over the network and triggering mastership
718 // elections. We require a minimum interval of 1/3 of the configured
719 // checkupInterval between consecutive checkup tasks when the device is
720 // known to be available.
721
722 final Long lastCheckup = lastCheckups.get(deviceId);
723 final boolean isAvailable = deviceService.isAvailable(deviceId);
724 if (isAvailable && lastCheckup != null &&
725 (currentTimeMillis() - lastCheckup) < (checkupInterval * 1000 / 3)) {
726 if (log.isDebugEnabled()) {
727 log.debug("Dropping checkup task for {} as it happened recently",
728 deviceId);
729 }
730 return;
731 }
732 lastCheckups.put(deviceId, currentTimeMillis());
733
734 // Make sure device has a valid mastership role.
735 final MastershipRole expectedRole = mastershipService.getLocalRole(deviceId);
736 if (expectedRole == MastershipRole.NONE) {
737 log.debug("Detected invalid role ({}) for {}, waiting for mastership " +
738 "service to fix this...",
739 expectedRole, deviceId);
740 // Gentle nudge to fix things...
741 mastershipService.requestRoleForSync(deviceId);
742 return;
743 }
744
745 final MastershipRole deviceRole = handshaker.getRole();
746 if (expectedRole != deviceRole) {
747 // FIXME: we should be checking the mastership term as well.
748 log.debug("Detected role mismatch for {}, core expects {}, " +
749 "but device reports {}, waiting for mastership " +
750 "service to fix this...",
751 deviceId, expectedRole, deviceRole);
752 // Gentle nudge to fix things...
753 providerService.receivedRoleReply(deviceId, deviceRole);
754 return;
755 }
756
757 // Check and update availability, which differently from reachability
758 // describes the ability of the device to forward packets.
759 if (probeAvailability(handshaker)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800760 // Device ready to do its job.
761 createOrUpdateDevice(deviceId, true);
762 } else {
763 markOfflineIfNeeded(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700764 if (isPipelineProgrammable(deviceId)) {
765 // If reachable, but not available, and pipeline programmable,
766 // there is a high chance it's because the pipeline is not READY
767 // (independently from what the pipeconf watchdog reports, as
768 // the status there might be outdated). Encourage pipeconf
769 // watchdog to perform a pipeline probe ASAP.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800770 pipeconfWatchdogService.triggerProbe(deviceId);
771 }
772 }
773 }
774
775 private void handleMastershipResponse(DeviceId deviceId, MastershipRole response) {
776 assertDeviceRegistered(deviceId);
777 log.debug("Device {} asserted role {}", deviceId, response);
778 providerService.receivedRoleReply(deviceId, response);
779 }
780
781 private void handleNotMaster(DeviceId deviceId) {
782 assertDeviceRegistered(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700783 handleMastershipResponse(deviceId, handshakerOrFail(deviceId).getRole());
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800784 }
785
786 private void assertDeviceRegistered(DeviceId deviceId) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700787 if (!deviceIsRegistered(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800788 throw new DeviceTaskException("device not registered in the core");
789 }
790 }
791
Carmelo Cascone4b616312019-04-17 14:15:45 -0700792 private boolean deviceIsRegistered(DeviceId deviceId) {
793 return deviceService.getDevice(deviceId) != null;
794 }
795
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800796 private void handleConnectionTeardown(DeviceId deviceId) {
797 if (deviceService.getDevice(deviceId) != null
798 && deviceService.isAvailable(deviceId)) {
799 providerService.deviceDisconnected(deviceId);
800 }
801 final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
802 handshaker.removeDeviceAgentListener(id());
803 handshakersWithListeners.remove(deviceId);
804 handshaker.disconnect();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700805 lastCheckups.remove(deviceId);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800806 }
807
808 private void bindPipeconfIfRequired(DeviceId deviceId) {
809 if (pipeconfService.getPipeconf(deviceId).isPresent()
810 || !isPipelineProgrammable(deviceId)) {
811 // Nothing to do.
812 // Device has already a pipeconf or is not programmable.
813 return;
814 }
815 // Get pipeconf from netcfg or driver (default one).
816 final PiPipelineProgrammable pipelineProg = getBehaviour(
817 deviceId, PiPipelineProgrammable.class);
818 final PiPipeconfId pipeconfId = getPipeconfId(deviceId, pipelineProg);
819 if (pipeconfId == null) {
820 throw new DeviceTaskException("unable to find pipeconf");
821 }
Carmelo Cascone4b616312019-04-17 14:15:45 -0700822 if (!pipeconfService.getPipeconf(pipeconfId).isPresent()) {
823 throw new DeviceTaskException(format(
824 "pipeconf %s not registered", pipeconfId));
825 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800826 // Store binding in pipeconf service.
827 pipeconfService.bindToDevice(pipeconfId, deviceId);
828 }
829
830 private PiPipeconfId getPipeconfId(DeviceId deviceId, PiPipelineProgrammable pipelineProg) {
831 // Places to look for a pipeconf ID (in priority order)):
832 // 1) netcfg
833 // 2) device driver (default one)
834 final PiPipeconfId pipeconfId = getPipeconfFromCfg(deviceId);
835 if (pipeconfId != null && !pipeconfId.id().isEmpty()) {
836 return pipeconfId;
837 }
838 if (pipelineProg != null
839 && pipelineProg.getDefaultPipeconf().isPresent()) {
840 final PiPipeconf defaultPipeconf = pipelineProg.getDefaultPipeconf().get();
841 log.info("Using default pipeconf {} for {}", defaultPipeconf.id(), deviceId);
842 return defaultPipeconf.id();
843 }
844 return null;
845 }
846
847 private PiPipeconfId getPipeconfFromCfg(DeviceId deviceId) {
848 BasicDeviceConfig config = cfgService.getConfig(
849 deviceId, BasicDeviceConfig.class);
850 if (config == null) {
851 return null;
852 }
853 return config.pipeconf() != null
854 ? new PiPipeconfId(config.pipeconf()) : null;
855 }
856
857 private DeviceHandshaker handshakerOrFail(DeviceId deviceId) {
858 final DeviceHandshaker handshaker = getBehaviour(
859 deviceId, DeviceHandshaker.class);
860 if (handshaker == null) {
861 throw new DeviceTaskException("missing handshaker behavior");
862 }
863 return handshaker;
864 }
865
Carmelo Cascone4b616312019-04-17 14:15:45 -0700866 private boolean configIsPresent(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800867 final BasicDeviceConfig basicDeviceCfg = cfgService.getConfig(
868 deviceId, BasicDeviceConfig.class);
869 return basicDeviceCfg != null && !isNullOrEmpty(basicDeviceCfg.driver());
870 }
871
872 private void assertConfig(DeviceId deviceId) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700873 if (!configIsPresent(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800874 throw new DeviceTaskException("configuration is not complete");
875 }
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700876 }
877
Andrea Campanella241896c2017-05-10 13:11:04 -0700878 private Driver getDriver(DeviceId deviceId) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700879 try {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200880 // DriverManager checks first using basic device config.
881 return driverService.getDriver(deviceId);
Andrea Campanella241896c2017-05-10 13:11:04 -0700882 } catch (ItemNotFoundException e) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200883 log.error("Driver not found for {}", deviceId);
884 return null;
Andrea Campanella241896c2017-05-10 13:11:04 -0700885 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700886 }
887
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700888 private <T extends Behaviour> T getBehaviour(DeviceId deviceId, Class<T> type) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700889 Driver driver = getDriver(deviceId);
890 if (driver == null) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700891 return null;
892 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700893 if (!driver.hasBehaviour(type)) {
894 return null;
895 }
896 final DriverData data = new DefaultDriverData(driver, deviceId);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700897 final DefaultDriverHandler handler = new DefaultDriverHandler(data);
898 return driver.createBehaviour(handler, type);
Andrea Campanella241896c2017-05-10 13:11:04 -0700899 }
900
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800901 private boolean hasBehaviour(DeviceId deviceId, Class<? extends Behaviour> type) {
902 Driver driver = getDriver(deviceId);
903 if (driver == null) {
904 return false;
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200905 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800906 return driver.hasBehaviour(type);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700907 }
908
909 private DeviceDescription getDeviceDescription(
910 DeviceId deviceId, boolean defaultAvailable) {
911 // Get one from driver or forge.
912 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
913 deviceId, DeviceDescriptionDiscovery.class);
Yi Tsengd7716482018-10-31 15:34:30 -0700914 if (deviceDiscovery == null) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700915 return forgeDeviceDescription(deviceId, defaultAvailable);
916 }
Yi Tsengd7716482018-10-31 15:34:30 -0700917
918 final DeviceDescription d = deviceDiscovery.discoverDeviceDetails();
919 if (d == null) {
920 return forgeDeviceDescription(deviceId, defaultAvailable);
921 }
922 // Enforce defaultAvailable flag over the one obtained from driver.
923 return new DefaultDeviceDescription(d, defaultAvailable, d.annotations());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700924 }
925
926 private List<PortDescription> getPortDetails(DeviceId deviceId) {
927 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
928 deviceId, DeviceDescriptionDiscovery.class);
929 if (deviceDiscovery != null) {
930 return deviceDiscovery.discoverPortDetails();
931 } else {
932 return Collections.emptyList();
933 }
934 }
935
936 private DeviceDescription forgeDeviceDescription(
937 DeviceId deviceId, boolean defaultAvailable) {
938 // Uses handshaker and provider config to get driver data.
939 final DeviceHandshaker handshaker = getBehaviour(
940 deviceId, DeviceHandshaker.class);
941 final Driver driver = handshaker != null
942 ? handshaker.handler().driver() : null;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700943 return new DefaultDeviceDescription(
944 deviceId.uri(),
945 Device.Type.SWITCH,
946 driver != null ? driver.manufacturer() : UNKNOWN,
947 driver != null ? driver.hwVersion() : UNKNOWN,
948 driver != null ? driver.swVersion() : UNKNOWN,
949 UNKNOWN,
950 new ChassisId(),
951 defaultAvailable,
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800952 DefaultAnnotations.EMPTY);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700953 }
954
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800955 static boolean myScheme(DeviceId deviceId) {
956 return deviceId.uri().getScheme().equals(URI_SCHEME);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200957 }
958
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700959 private boolean isPipelineProgrammable(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800960 return hasBehaviour(deviceId, PiPipelineProgrammable.class);
Carmelo Casconede3b6842018-09-05 17:45:10 -0700961 }
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700962
963 private class InternalDeviceListener implements DeviceListener {
964 @Override
965 public void event(DeviceEvent event) {
966 log.info("Triggering disconnect for device {}", event.subject().id());
967 triggerDisconnect(event.subject().id());
968 }
969
970 @Override
971 public boolean isRelevant(DeviceEvent event) {
Thomas Vachuska24c0ca42019-08-29 18:19:16 -0700972 return DeviceEvent.Type.DEVICE_REMOVED == event.type() && myScheme(event.subject().id());
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700973 }
974 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700975}