blob: c91cfb24115f6bd464b687f8ce8526806b4fabfc [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;
pierventre0f663b02022-02-02 22:33:41 +010030import org.onosproject.drivers.gnmi.OpenConfigGnmiDeviceDescriptionDiscovery;
Yi Tsenge616d752018-11-27 10:53:27 -080031import org.onosproject.gnmi.api.GnmiController;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080032import org.onosproject.mastership.MastershipInfo;
Andrea Campanella14e196d2017-07-24 18:11:36 +020033import org.onosproject.mastership.MastershipService;
Andrea Campanella241896c2017-05-10 13:11:04 -070034import org.onosproject.net.DefaultAnnotations;
35import org.onosproject.net.Device;
36import org.onosproject.net.DeviceId;
37import org.onosproject.net.MastershipRole;
38import org.onosproject.net.PortNumber;
Carmelo Cascone87892e22017-11-13 16:01:29 -080039import org.onosproject.net.behaviour.PiPipelineProgrammable;
Andrea Campanella241896c2017-05-10 13:11:04 -070040import org.onosproject.net.behaviour.PortAdmin;
Andrea Campanella241896c2017-05-10 13:11:04 -070041import org.onosproject.net.config.NetworkConfigEvent;
42import org.onosproject.net.config.NetworkConfigListener;
43import org.onosproject.net.config.NetworkConfigRegistry;
44import org.onosproject.net.config.basics.BasicDeviceConfig;
Andrea Campanella241896c2017-05-10 13:11:04 -070045import org.onosproject.net.device.DefaultDeviceDescription;
Thomas Vachuska1b3cf362019-08-29 17:11:18 -070046import org.onosproject.net.device.DeviceAdminService;
Carmelo Casconee5b28722018-06-22 17:28:28 +020047import org.onosproject.net.device.DeviceAgentEvent;
48import org.onosproject.net.device.DeviceAgentListener;
Andrea Campanella241896c2017-05-10 13:11:04 -070049import org.onosproject.net.device.DeviceDescription;
50import org.onosproject.net.device.DeviceDescriptionDiscovery;
Thomas Vachuska1b3cf362019-08-29 17:11:18 -070051import org.onosproject.net.device.DeviceEvent;
Andrea Campanella241896c2017-05-10 13:11:04 -070052import org.onosproject.net.device.DeviceHandshaker;
Thomas Vachuska1b3cf362019-08-29 17:11:18 -070053import org.onosproject.net.device.DeviceListener;
Andrea Campanella241896c2017-05-10 13:11:04 -070054import org.onosproject.net.device.DeviceProvider;
55import org.onosproject.net.device.DeviceProviderRegistry;
56import org.onosproject.net.device.DeviceProviderService;
Andrea Campanella241896c2017-05-10 13:11:04 -070057import org.onosproject.net.device.PortDescription;
Andrea Campanella241896c2017-05-10 13:11:04 -070058import org.onosproject.net.driver.Behaviour;
59import org.onosproject.net.driver.DefaultDriverData;
60import org.onosproject.net.driver.DefaultDriverHandler;
61import org.onosproject.net.driver.Driver;
62import org.onosproject.net.driver.DriverData;
63import org.onosproject.net.driver.DriverService;
Carmelo Cascone59f57de2017-07-11 19:55:09 -040064import org.onosproject.net.pi.model.PiPipeconf;
Andrea Campanellabc112a92017-06-26 19:06:43 +020065import org.onosproject.net.pi.model.PiPipeconfId;
Carmelo Cascone39c28ca2017-11-15 13:03:57 -080066import org.onosproject.net.pi.service.PiPipeconfService;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070067import org.onosproject.net.pi.service.PiPipeconfWatchdogEvent;
68import org.onosproject.net.pi.service.PiPipeconfWatchdogListener;
69import org.onosproject.net.pi.service.PiPipeconfWatchdogService;
Andrea Campanella241896c2017-05-10 13:11:04 -070070import org.onosproject.net.provider.AbstractProvider;
71import org.onosproject.net.provider.ProviderId;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080072import org.onosproject.provider.general.device.impl.DeviceTaskExecutor.DeviceTaskException;
Andrea Campanella19090322017-08-22 10:31:37 +020073import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070074import org.osgi.service.component.annotations.Activate;
75import org.osgi.service.component.annotations.Component;
76import org.osgi.service.component.annotations.Deactivate;
77import org.osgi.service.component.annotations.Modified;
78import org.osgi.service.component.annotations.Reference;
79import org.osgi.service.component.annotations.ReferenceCardinality;
Andrea Campanella241896c2017-05-10 13:11:04 -070080import org.slf4j.Logger;
81
Andrea Campanellabc112a92017-06-26 19:06:43 +020082import java.util.Collections;
Andrea Campanella19090322017-08-22 10:31:37 +020083import java.util.Dictionary;
Andrea Campanella241896c2017-05-10 13:11:04 -070084import java.util.List;
Thomas Vachuska5b38dc02018-05-10 15:24:40 -070085import java.util.Map;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080086import java.util.Objects;
Carmelo Cascone1dfc7862019-04-17 16:37:44 -070087import java.util.Set;
Andrea Campanella241896c2017-05-10 13:11:04 -070088import java.util.concurrent.CompletableFuture;
Carmelo Casconee5b28722018-06-22 17:28:28 +020089import java.util.concurrent.ExecutorService;
Andrea Campanella19090322017-08-22 10:31:37 +020090import java.util.concurrent.ScheduledFuture;
Andrea Campanella241896c2017-05-10 13:11:04 -070091import java.util.concurrent.TimeUnit;
Andrea Campanella241896c2017-05-10 13:11:04 -070092
Carmelo Cascone3977ea42019-02-28 13:43:42 -080093import static com.google.common.base.Preconditions.checkNotNull;
94import static com.google.common.base.Strings.isNullOrEmpty;
Carmelo Cascone61469462019-03-05 23:59:11 -080095import static java.lang.String.format;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080096import static java.lang.System.currentTimeMillis;
Carmelo Casconee5b28722018-06-22 17:28:28 +020097import static java.util.concurrent.Executors.newFixedThreadPool;
Andrea Campanella241896c2017-05-10 13:11:04 -070098import static org.onlab.util.Tools.groupedThreads;
Carmelo Cascone4b616312019-04-17 14:15:45 -070099import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.CHECKUP_INTERVAL;
100import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.CHECKUP_INTERVAL_DEFAULT;
pierventre0f663b02022-02-02 22:33:41 +0100101import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.READ_PORT_ID;
102import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.READ_PORT_ID_DEFAULT;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800103import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.STATS_POLL_INTERVAL;
104import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.STATS_POLL_INTERVAL_DEFAULT;
Andrea Campanella241896c2017-05-10 13:11:04 -0700105import static org.slf4j.LoggerFactory.getLogger;
106
107/**
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800108 * Provider which uses drivers to discover devices, perform initial handshake,
109 * and notify the core of disconnection events. The implementation listens for
110 * events from netcfg or the drivers (via {@link DeviceAgentListener}) andP
111 * schedules task for each event.
Andrea Campanella241896c2017-05-10 13:11:04 -0700112 */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700113@Component(immediate = true,
114 property = {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700115 CHECKUP_INTERVAL + ":Integer=" + CHECKUP_INTERVAL_DEFAULT,
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800116 STATS_POLL_INTERVAL + ":Integer=" + STATS_POLL_INTERVAL_DEFAULT,
pierventre0f663b02022-02-02 22:33:41 +0100117 READ_PORT_ID + ":Boolean=" + READ_PORT_ID_DEFAULT,
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700118 })
Andrea Campanella241896c2017-05-10 13:11:04 -0700119public class GeneralDeviceProvider extends AbstractProvider
120 implements DeviceProvider {
Carmelo Casconee5b28722018-06-22 17:28:28 +0200121
Andrea Campanella241896c2017-05-10 13:11:04 -0700122 private final Logger log = getLogger(getClass());
123
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800124 private static final String APP_NAME = "org.onosproject.generaldeviceprovider";
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700125 private static final String URI_SCHEME = "device";
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700126 private static final String DEVICE_PROVIDER_PACKAGE =
127 "org.onosproject.general.provider.device";
128 private static final int CORE_POOL_SIZE = 10;
129 private static final String UNKNOWN = "unknown";
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700130
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200132 private DeviceProviderRegistry providerRegistry;
Andrea Campanella241896c2017-05-10 13:11:04 -0700133
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200135 private ComponentConfigService componentConfigService;
Andrea Campanella4929a812017-10-09 18:38:23 +0200136
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200138 private NetworkConfigRegistry cfgService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700139
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200141 private CoreService coreService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700142
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700144 private DeviceAdminService deviceService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700145
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200147 private DriverService driverService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700148
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200150 private MastershipService mastershipService;
Andrea Campanella14e196d2017-07-24 18:11:36 +0200151
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700152 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800153 private ClusterService clusterService;
154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700156 private PiPipeconfService pipeconfService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700157
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700159 private PiPipeconfWatchdogService pipeconfWatchdogService;
Andrea Campanella14e196d2017-07-24 18:11:36 +0200160
Yi Tsenge616d752018-11-27 10:53:27 -0800161 // FIXME: no longer general if we add a dependency to a protocol-specific
162 // service. Possible solutions are: rename this provider to
163 // StratumDeviceProvider, find a way to allow this provider to register for
164 // protocol specific events (e.g. port events) via drivers (similar to
165 // DeviceAgentListener).
166 @Reference(cardinality = ReferenceCardinality.MANDATORY)
167 private GnmiController gnmiController;
168
169 private GnmiDeviceStateSubscriber gnmiDeviceStateSubscriber;
170
Carmelo Cascone61469462019-03-05 23:59:11 -0800171 /**
172 * Configure interval for checking device availability; default is 10 sec.
173 */
Carmelo Cascone4b616312019-04-17 14:15:45 -0700174 private int checkupInterval = CHECKUP_INTERVAL_DEFAULT;
Andrea Campanella19090322017-08-22 10:31:37 +0200175
Carmelo Cascone61469462019-03-05 23:59:11 -0800176 /**
177 * Configure poll frequency for port status and stats; default is 10 sec.
178 */
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800179 private int statsPollInterval = STATS_POLL_INTERVAL_DEFAULT;
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200180
pierventre0f663b02022-02-02 22:33:41 +0100181 /**
182 * Configure read port-id for gnmi drivers; default is false.
183 */
184 private boolean readPortId = READ_PORT_ID_DEFAULT;
185
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700186 private final Map<DeviceId, DeviceHandshaker> handshakersWithListeners = Maps.newConcurrentMap();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700187 private final Map<DeviceId, Long> lastCheckups = Maps.newConcurrentMap();
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700188 private final InternalPipeconfWatchdogListener pipeconfWatchdogListener = new InternalPipeconfWatchdogListener();
Carmelo Casconee5b28722018-06-22 17:28:28 +0200189 private final NetworkConfigListener cfgListener = new InternalNetworkConfigListener();
190 private final DeviceAgentListener deviceAgentListener = new InternalDeviceAgentListener();
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700191 private final DeviceListener deviceListener = new InternalDeviceListener();
Andrea Campanella241896c2017-05-10 13:11:04 -0700192
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800193 private ExecutorService mainExecutor;
194 private DeviceTaskExecutor<TaskType> taskExecutor;
Carmelo Cascone4b616312019-04-17 14:15:45 -0700195 private ScheduledFuture<?> checkupTask;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800196 private StatsPoller statsPoller;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700197 private DeviceProviderService providerService;
198
199 public GeneralDeviceProvider() {
200 super(new ProviderId(URI_SCHEME, DEVICE_PROVIDER_PACKAGE));
201 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700202
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800203 protected DeviceProviderService providerService() {
204 return providerService;
205 }
206
Andrea Campanella241896c2017-05-10 13:11:04 -0700207 @Activate
Andrea Campanella1e573442018-05-17 17:07:13 +0200208 public void activate(ComponentContext context) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800209 mainExecutor = newFixedThreadPool(CORE_POOL_SIZE, groupedThreads(
Carmelo Cascone4b616312019-04-17 14:15:45 -0700210 "onos/gdp", "%d", log));
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800211 taskExecutor = new DeviceTaskExecutor<>(mainExecutor);
Andrea Campanella241896c2017-05-10 13:11:04 -0700212 providerService = providerRegistry.register(this);
Andrea Campanella4929a812017-10-09 18:38:23 +0200213 componentConfigService.registerProperties(getClass());
Andrea Campanella241896c2017-05-10 13:11:04 -0700214 coreService.registerApplication(APP_NAME);
Andrea Campanella241896c2017-05-10 13:11:04 -0700215 cfgService.addListener(cfgListener);
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700216 deviceService.addListener(deviceListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700217 pipeconfWatchdogService.addListener(pipeconfWatchdogListener);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800218 gnmiDeviceStateSubscriber = new GnmiDeviceStateSubscriber(
219 gnmiController, deviceService, mastershipService, providerService);
Yi Tsenge616d752018-11-27 10:53:27 -0800220 gnmiDeviceStateSubscriber.activate();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700221 startOrReschedulePeriodicCheckupTasks();
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800222 statsPoller = new StatsPoller(deviceService, mastershipService, providerService);
223 statsPoller.activate(statsPollInterval);
224 modified(context);
Andrea Campanella241896c2017-05-10 13:11:04 -0700225 log.info("Started");
226 }
227
Andrea Campanella19090322017-08-22 10:31:37 +0200228 @Modified
229 public void modified(ComponentContext context) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200230 if (context == null) {
231 return;
Andrea Campanella19090322017-08-22 10:31:37 +0200232 }
233
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200234 Dictionary<?, ?> properties = context.getProperties();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700235 final int oldCheckupInterval = checkupInterval;
236 checkupInterval = Tools.getIntegerProperty(
237 properties, CHECKUP_INTERVAL, CHECKUP_INTERVAL_DEFAULT);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200238 log.info("Configured. {} is configured to {} seconds",
Carmelo Cascone4b616312019-04-17 14:15:45 -0700239 CHECKUP_INTERVAL, checkupInterval);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800240 final int oldStatsPollFrequency = statsPollInterval;
241 statsPollInterval = Tools.getIntegerProperty(
242 properties, STATS_POLL_INTERVAL, STATS_POLL_INTERVAL_DEFAULT);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200243 log.info("Configured. {} is configured to {} seconds",
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800244 STATS_POLL_INTERVAL, statsPollInterval);
pierventre0f663b02022-02-02 22:33:41 +0100245 final boolean oldReaPortId = readPortId;
246 String strReadPortId = Tools.get(properties, READ_PORT_ID);
247 readPortId = Boolean.parseBoolean(strReadPortId);
248 log.info("Configured. {} is configured to {}",
249 READ_PORT_ID, readPortId);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200250
Carmelo Cascone4b616312019-04-17 14:15:45 -0700251 if (oldCheckupInterval != checkupInterval) {
252 startOrReschedulePeriodicCheckupTasks();
Andrea Campanella19090322017-08-22 10:31:37 +0200253 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200254
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800255 if (oldStatsPollFrequency != statsPollInterval) {
256 statsPoller.reschedule(statsPollInterval);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200257 }
pierventre0f663b02022-02-02 22:33:41 +0100258
259 if (oldReaPortId != readPortId) {
260 // FIXME temporary solution will be removed when the
261 // transition to p4rt translation is completed
262 OpenConfigGnmiDeviceDescriptionDiscovery.readPortId = readPortId;
263 }
Andrea Campanella19090322017-08-22 10:31:37 +0200264 }
265
Andrea Campanella241896c2017-05-10 13:11:04 -0700266 @Deactivate
267 public void deactivate() {
Thomas Vachuska1b3cf362019-08-29 17:11:18 -0700268 deviceService.removeListener(deviceListener);
269
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800270 // Shutdown stats poller.
271 statsPoller.deactivate();
272 statsPoller = null;
Carmelo Cascone4b616312019-04-17 14:15:45 -0700273 // Shutdown periodic checkup task.
274 checkupTask.cancel(false);
275 checkupTask = null;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800276 // Shutdown main and task executor.
277 taskExecutor.cancel();
278 taskExecutor = null;
279 mainExecutor.shutdownNow();
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700280 try {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800281 mainExecutor.awaitTermination(5, TimeUnit.SECONDS);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700282 } catch (InterruptedException e) {
283 log.warn("connectionExecutor not terminated properly");
284 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800285 mainExecutor = null;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700286 // Remove all device agent listeners
287 handshakersWithListeners.values().forEach(h -> h.removeDeviceAgentListener(id()));
288 handshakersWithListeners.clear();
289 // Other cleanup.
Carmelo Cascone4b616312019-04-17 14:15:45 -0700290 lastCheckups.clear();
Andrea Campanella4929a812017-10-09 18:38:23 +0200291 componentConfigService.unregisterProperties(getClass(), false);
Andrea Campanella241896c2017-05-10 13:11:04 -0700292 cfgService.removeListener(cfgListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700293 pipeconfWatchdogService.removeListener(pipeconfWatchdogListener);
Andrea Campanella241896c2017-05-10 13:11:04 -0700294 providerRegistry.unregister(this);
295 providerService = null;
Yi Tsenge616d752018-11-27 10:53:27 -0800296 gnmiDeviceStateSubscriber.deactivate();
297 gnmiDeviceStateSubscriber = null;
Andrea Campanella241896c2017-05-10 13:11:04 -0700298 log.info("Stopped");
299 }
300
Andrea Campanella241896c2017-05-10 13:11:04 -0700301 @Override
302 public void triggerProbe(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800303 checkNotNull(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700304 submitTask(deviceId, TaskType.CHECKUP);
Andrea Campanella241896c2017-05-10 13:11:04 -0700305 }
306
307 @Override
308 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800309 final MastershipInfo mastershipInfo = mastershipService.getMastershipFor(deviceId);
310 final NodeId localNodeId = clusterService.getLocalNode().id();
311
312 if (!mastershipInfo.getRole(localNodeId).equals(newRole)) {
313 log.warn("Inconsistent mastership info for {}! Requested {}, but " +
314 "mastership service reports {}, will apply the latter...",
315 deviceId, newRole, mastershipInfo.getRole(localNodeId));
316 newRole = mastershipInfo.getRole(localNodeId);
317 }
318
Carmelo Cascone4b616312019-04-17 14:15:45 -0700319 final DeviceHandshaker handshaker = getBehaviour(
320 deviceId, DeviceHandshaker.class);
321 if (handshaker == null) {
322 log.error("Null handshaker. Unable to notify role {} to {}",
323 newRole, deviceId);
324 return;
325 }
326
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800327 // Derive preference value.
328 final int preference;
329 switch (newRole) {
330 case MASTER:
331 preference = 0;
332 break;
333 case STANDBY:
334 preference = mastershipInfo.backups().indexOf(localNodeId) + 1;
335 if (preference == 0) {
336 // Not found in list.
337 log.error("Unable to derive mastership preference for {}, " +
338 "requested role {} but local node ID was " +
339 "not found among list of backup nodes " +
Carmelo Cascone4b616312019-04-17 14:15:45 -0700340 "reported by mastership service",
341 deviceId, newRole);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800342 return;
343 }
344 break;
345 case NONE:
346 // No preference for NONE, apply as is.
347 log.info("Notifying role {} to {}", newRole, deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700348 handshaker.roleChanged(newRole);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800349 return;
350 default:
351 log.error("Unrecognized mastership role {}", newRole);
352 return;
353 }
354
355 log.info("Notifying role {} (preference {}) for term {} to {}",
356 newRole, preference, mastershipInfo.term(), deviceId);
357
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800358 try {
359 handshaker.roleChanged(preference, mastershipInfo.term());
360 } catch (UnsupportedOperationException e) {
361 // Preference-based method not supported.
362 handshaker.roleChanged(newRole);
363 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700364 }
365
366 @Override
367 public boolean isReachable(DeviceId deviceId) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700368 final DeviceHandshaker handshaker = getBehaviour(
369 deviceId, DeviceHandshaker.class);
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100370 if (handshaker == null) {
371 return false;
372 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800373 return handshaker.isReachable();
Andrea Campanella241896c2017-05-10 13:11:04 -0700374 }
375
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800376 @Override
377 public boolean isAvailable(DeviceId deviceId) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700378 final DeviceHandshaker handshaker = getBehaviour(
379 deviceId, DeviceHandshaker.class);
380 if (handshaker == null) {
381 return false;
382 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800383 try {
384 // Try without probing the device...
385 return handshaker.isAvailable();
386 } catch (UnsupportedOperationException e) {
387 // Driver does not support that.
388 return probeAvailability(handshaker);
389 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700390 }
391
Andrea Campanella241896c2017-05-10 13:11:04 -0700392 @Override
393 public void changePortState(DeviceId deviceId, PortNumber portNumber,
394 boolean enable) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200395 if (!deviceService.getDevice(deviceId).is(PortAdmin.class)) {
396 log.warn("Missing PortAdmin behaviour on {}, aborting port state change",
397 deviceId);
398 return;
Andrea Campanella241896c2017-05-10 13:11:04 -0700399 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200400 final PortAdmin portAdmin = deviceService.getDevice(deviceId)
401 .as(PortAdmin.class);
402 final CompletableFuture<Boolean> modifyTask = enable
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200403 ? portAdmin.enable(portNumber)
404 : portAdmin.disable(portNumber);
Carmelo Cascone61469462019-03-05 23:59:11 -0800405 final String descr = format("%s port %s on %s",
406 (enable ? "enable" : "disable"),
407 portNumber, deviceId);
408 modifyTask.whenComplete((success, ex) -> {
409 if (ex != null) {
410 log.error("Exception while trying to " + descr, ex);
411 } else if (!success) {
412 log.warn("Unable to " + descr);
413 }
414 });
Andrea Campanella241896c2017-05-10 13:11:04 -0700415 }
416
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700417 @Override
418 public void triggerDisconnect(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800419 checkNotNull(deviceId);
420 log.info("Triggering disconnection of device {}", deviceId);
421 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
422 }
423
424 /**
425 * Listener for configuration events.
426 */
427 private class InternalNetworkConfigListener implements NetworkConfigListener {
428 @Override
429 public void event(NetworkConfigEvent event) {
430 DeviceId deviceId = (DeviceId) event.subject();
431 switch (event.type()) {
432 case CONFIG_ADDED:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700433 if (configIsPresent(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800434 submitTask(deviceId, TaskType.CONNECTION_SETUP);
435 }
436 break;
437 case CONFIG_UPDATED:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700438 if (configIsPresent(deviceId) && mgmtAddrUpdated(event)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800439 submitTask(deviceId, TaskType.CONNECTION_UPDATE);
440 }
441 break;
442 case CONFIG_REMOVED:
443 if (event.configClass().equals(BasicDeviceConfig.class)) {
444 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
445 }
446 break;
447 default:
448 // Ignore
449 break;
450 }
451 }
452
453 private boolean mgmtAddrUpdated(NetworkConfigEvent event) {
454 if (!event.prevConfig().isPresent() || !event.config().isPresent()) {
455 return false;
456 }
457 final BasicDeviceConfig prev = (BasicDeviceConfig) event.prevConfig().get();
458 final BasicDeviceConfig current = (BasicDeviceConfig) event.config().get();
459 return !Objects.equals(prev.managementAddress(), current.managementAddress());
460 }
461
462 @Override
463 public boolean isRelevant(NetworkConfigEvent event) {
464 return event.configClass().equals(BasicDeviceConfig.class) &&
465 (event.subject() instanceof DeviceId) &&
466 myScheme((DeviceId) event.subject());
467 }
468 }
469
470 /**
471 * Listener for device agent events.
472 */
473 private class InternalDeviceAgentListener implements DeviceAgentListener {
474 @Override
475 public void event(DeviceAgentEvent event) {
476 DeviceId deviceId = event.subject();
477 switch (event.type()) {
478 case CHANNEL_OPEN:
479 submitTask(deviceId, TaskType.CHANNEL_OPEN);
480 break;
481 case CHANNEL_CLOSED:
482 case CHANNEL_ERROR:
483 submitTask(deviceId, TaskType.CHANNEL_CLOSED);
484 break;
485 case ROLE_MASTER:
486 submitTask(deviceId, TaskType.ROLE_MASTER);
487 break;
488 case ROLE_STANDBY:
489 submitTask(deviceId, TaskType.ROLE_STANDBY);
490 break;
491 case ROLE_NONE:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700492 // FIXME: in case of device disconnection, agents will
493 // signal role NONE, preventing the DeviceManager to mark
494 // the device as offline, as only the master can do that. We
495 // should change the DeviceManager. For now, we disable
496 // signaling role NONE.
497 // submitTask(deviceId, TaskType.ROLE_NONE);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800498 break;
499 case NOT_MASTER:
500 submitTask(deviceId, TaskType.NOT_MASTER);
501 break;
502 default:
503 log.warn("Unrecognized device agent event {}", event.type());
504 }
505 }
506 }
507
508 /**
509 * Pipeline event listener.
510 */
511 private class InternalPipeconfWatchdogListener implements PiPipeconfWatchdogListener {
512 @Override
513 public void event(PiPipeconfWatchdogEvent event) {
514 final DeviceId deviceId = event.subject();
515 switch (event.type()) {
516 case PIPELINE_READY:
517 submitTask(deviceId, TaskType.PIPELINE_READY);
518 break;
519 case PIPELINE_UNKNOWN:
520 submitTask(deviceId, TaskType.PIPELINE_NOT_READY);
521 break;
522 default:
523 break;
524 }
525 }
526
527 @Override
528 public boolean isRelevant(PiPipeconfWatchdogEvent event) {
529 return myScheme(event.subject());
530 }
531 }
532
Carmelo Cascone4b616312019-04-17 14:15:45 -0700533 private void startOrReschedulePeriodicCheckupTasks() {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800534 synchronized (this) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700535 if (checkupTask != null) {
536 checkupTask.cancel(false);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800537 }
Carmelo Cascone4b616312019-04-17 14:15:45 -0700538 checkupTask = SharedScheduledExecutors.getPoolThreadExecutor()
539 .scheduleAtFixedRate(
540 this::submitCheckupTasksForAllDevices,
541 1,
542 checkupInterval,
pierventre475290e2021-04-09 14:32:11 +0200543 TimeUnit.SECONDS,
544 true);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800545 }
546 }
547
Carmelo Cascone4b616312019-04-17 14:15:45 -0700548 private void submitCheckupTasksForAllDevices() {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800549 // Async trigger a task for all devices in the cfg.
Carmelo Cascone4b616312019-04-17 14:15:45 -0700550 log.debug("Submitting checkup task for all devices...");
Carmelo Cascone1dfc7862019-04-17 16:37:44 -0700551 final Set<DeviceId> deviceToCheck = Sets.newHashSet();
552 // All devices in the core and in the config that we care about.
553 deviceService.getDevices().forEach(d -> {
554 if (myScheme(d.id())) {
555 deviceToCheck.add(d.id());
556 }
557 });
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800558 cfgService.getSubjects(DeviceId.class).stream()
559 .filter(GeneralDeviceProvider::myScheme)
Carmelo Cascone1dfc7862019-04-17 16:37:44 -0700560 .filter(this::configIsPresent)
561 .forEach(deviceToCheck::add);
562 deviceToCheck.forEach(d -> submitTask(d, TaskType.CHECKUP));
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800563 }
564
565 /**
566 * Type of tasks performed by this provider.
567 */
568 enum TaskType {
569 CONNECTION_SETUP,
570 CONNECTION_UPDATE,
571 CONNECTION_TEARDOWN,
572 PIPELINE_READY,
573 CHANNEL_OPEN,
574 CHANNEL_CLOSED,
575 PIPELINE_NOT_READY,
Carmelo Cascone4b616312019-04-17 14:15:45 -0700576 CHECKUP,
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800577 ROLE_MASTER,
578 ROLE_NONE,
579 ROLE_STANDBY,
580 NOT_MASTER,
581 }
582
583 private void submitTask(DeviceId deviceId, TaskType taskType) {
584 taskExecutor.submit(deviceId, taskType, taskRunnable(deviceId, taskType));
585 }
586
587 private Runnable taskRunnable(DeviceId deviceId, TaskType taskType) {
588 switch (taskType) {
589 case CONNECTION_SETUP:
590 return () -> handleConnectionSetup(deviceId);
591 case CONNECTION_UPDATE:
592 return () -> handleConnectionUpdate(deviceId);
593 case CONNECTION_TEARDOWN:
594 return () -> handleConnectionTeardown(deviceId);
595 case CHANNEL_OPEN:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700596 case CHECKUP:
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800597 case PIPELINE_READY:
Carmelo Cascone4b616312019-04-17 14:15:45 -0700598 return () -> doCheckupAndRepair(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700599 case CHANNEL_CLOSED:
600 case PIPELINE_NOT_READY:
601 return () -> markOfflineIfNeeded(deviceId);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800602 case ROLE_MASTER:
603 return () -> handleMastershipResponse(deviceId, MastershipRole.MASTER);
604 case ROLE_STANDBY:
605 return () -> handleMastershipResponse(deviceId, MastershipRole.STANDBY);
606 case ROLE_NONE:
607 return () -> handleMastershipResponse(deviceId, MastershipRole.NONE);
608 case NOT_MASTER:
609 return () -> handleNotMaster(deviceId);
610 default:
611 throw new IllegalArgumentException("Unrecognized task type " + taskType);
612 }
613 }
614
615 private void handleConnectionSetup(DeviceId deviceId) {
616 assertConfig(deviceId);
617 // Bind pipeconf (if any and if device is capable).
618 bindPipeconfIfRequired(deviceId);
619 // Get handshaker.
620 final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700621 if (handshaker.hasConnection() || handshakersWithListeners.containsKey(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800622 throw new DeviceTaskException("connection already exists");
623 }
624 // Add device agent listener.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800625 handshakersWithListeners.put(deviceId, handshaker);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700626 handshaker.addDeviceAgentListener(id(), deviceAgentListener);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800627 // Start connection via handshaker.
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700628 if (!handshaker.connect()) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800629 // Failed! Remove listeners.
630 handshaker.removeDeviceAgentListener(id());
631 handshakersWithListeners.remove(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700632 // Clean up connection state leftovers.
633 handshaker.disconnect();
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800634 throw new DeviceTaskException("connection failed");
635 }
636 createOrUpdateDevice(deviceId, false);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800637 // From here we expect a CHANNEL_OPEN event to update availability.
638 }
639
640 private void handleConnectionUpdate(DeviceId deviceId) {
641 assertConfig(deviceId);
642 final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700643 if (!handshaker.hasConnection()) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800644 // If driver reports that a connection still exists, perhaps the
645 // part of the netcfg that changed does not affect the connection.
646 // Otherwise, remove any previous connection state from the old
647 // netcfg and create a new one.
648 log.warn("Detected change of connection endpoints for {}, will " +
649 "tear down existing connection and set up a new one...",
650 deviceId);
651 handleConnectionTeardown(deviceId);
652 handleConnectionSetup(deviceId);
653 }
654 }
655
656 private void createOrUpdateDevice(DeviceId deviceId, boolean available) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800657 assertConfig(deviceId);
pierventre475290e2021-04-09 14:32:11 +0200658
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700659 if (available) {
Carmelo Casconed51a5552019-04-13 01:22:25 -0700660 // Push port descriptions. If marking online, make sure to update
661 // ports before other subsystems pick up the device event.
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700662 final List<PortDescription> ports = getPortDetails(deviceId);
663 providerService.updatePorts(deviceId, ports);
664 }
pierventre475290e2021-04-09 14:32:11 +0200665
pierventreb8856852021-10-01 22:01:22 +0200666 DeviceDescription deviceDescription = getDeviceDescription(deviceId, available);
667 DeviceDescription storeDescription = providerService.getDeviceDescription(deviceId);
668 if (deviceService.getDevice(deviceId) != null &&
669 deviceService.isAvailable(deviceId) == available &&
670 storeDescription != null) {
671 /*
672 * FIXME SDFAB-650 rethink the APIs and abstractions around the DeviceStore.
673 * Device registration is a two-step process for the GDP. Initially, the device is
674 * registered with default avail. to false. Later, the checkup task will update the
675 * description with the default avail to true in order to mark it available. Today,
676 * there is only one API to mark online a device from the device provider which is
677 * deviceConnected which assumes an update on the device description. The device provider
678 * is the only one able to update the device description and we have to make sure that
679 * the default avail. is flipped to true as it is used to mark as online the device when
680 * it is created or updated. Otherwise, if an ONOS instance fails and restarts, when re-joining
681 * the cluster, it will get the device marked as offline and will not be able to update
682 * its status until it become the master. This process concurs with the markOnline done
683 * by the background thread in the DeviceManager and its the reason why we cannot just check
684 * the device availability but we need to compare also the desc. Checking here the equality,
685 * as in general we may want to upgrade the device description at run time.
686 */
687 DeviceDescription testDeviceDescription = DefaultDeviceDescription.copyReplacingAnnotation(
688 deviceDescription, storeDescription.annotations());
689 if (testDeviceDescription.equals(storeDescription)) {
690 return;
691 }
pierventre475290e2021-04-09 14:32:11 +0200692 }
pierventreb8856852021-10-01 22:01:22 +0200693
694 providerService.deviceConnected(deviceId, deviceDescription);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800695 }
696
697 private boolean probeAvailability(DeviceHandshaker handshaker) {
Carmelo Cascone61469462019-03-05 23:59:11 -0800698 return Futures.getUnchecked(handshaker.probeAvailability());
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800699 }
700
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800701 private void markOfflineIfNeeded(DeviceId deviceId) {
702 assertDeviceRegistered(deviceId);
703 if (deviceService.isAvailable(deviceId)) {
704 providerService.deviceDisconnected(deviceId);
705 }
706 }
707
Carmelo Cascone4b616312019-04-17 14:15:45 -0700708 private void doCheckupAndRepair(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800709
Carmelo Cascone4b616312019-04-17 14:15:45 -0700710 // This task should be invoked periodically for each device known by
711 // this provider, or as a consequence of events signaling potential
712 // availability changes of the device. We check that everything is in
713 // order, repair what's wrong, and eventually mark the the device as
714 // available (or not) in the core.
715
716 if (!configIsPresent(deviceId)) {
717 // We should have a connection only for devices in the config.
718 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
719 return;
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800720 }
721
Carmelo Cascone4b616312019-04-17 14:15:45 -0700722 final DeviceHandshaker handshaker = handshakersWithListeners.get(deviceId);
723 if (handshaker == null) {
724 // Device in config but we have not initiated a connection.
725 // Perhaps we missed the config event?
726 submitTask(deviceId, TaskType.CONNECTION_SETUP);
727 return;
728 }
729
730 // If here, we have a handshaker meaning we already connected once to
731 // the device...
732 if (!handshaker.hasConnection()) {
733 // ... but now the driver reports there is NOT a connection.
734 // Perhaps the netcfg changed and we didn't pick the event?
735 log.warn("Re-establishing lost connection to {}", deviceId);
736 submitTask(deviceId, TaskType.CONNECTION_TEARDOWN);
737 submitTask(deviceId, TaskType.CONNECTION_SETUP);
738 return;
739 }
740
741 // If here, device should be registered in the core.
742 assertDeviceRegistered(deviceId);
743
744 if (!handshaker.isReachable()) {
745 // Device appears to be offline.
746 markOfflineIfNeeded(deviceId);
747 // While we expect the protocol layer to implement some sort of
748 // connection backoff mechanism and to signal availability via
749 // CHANNEL_OPEN events, we stimulate some channel activity now.
750 // Trigger probe over the network and forget about it (not waiting
751 // for future to complete). If channel is ready, we expect to come
752 // back here via a CHANNEL_OPEN event.
753 handshaker.probeReachability();
754 return;
755 }
756
757 // If here, device is reachable. Now do mastership and availability
758 // checkups. To avoid overload of checkup tasks which might involve
759 // sending messages over the network and triggering mastership
760 // elections. We require a minimum interval of 1/3 of the configured
761 // checkupInterval between consecutive checkup tasks when the device is
762 // known to be available.
763
764 final Long lastCheckup = lastCheckups.get(deviceId);
765 final boolean isAvailable = deviceService.isAvailable(deviceId);
766 if (isAvailable && lastCheckup != null &&
767 (currentTimeMillis() - lastCheckup) < (checkupInterval * 1000 / 3)) {
768 if (log.isDebugEnabled()) {
769 log.debug("Dropping checkup task for {} as it happened recently",
770 deviceId);
771 }
772 return;
773 }
774 lastCheckups.put(deviceId, currentTimeMillis());
775
776 // Make sure device has a valid mastership role.
777 final MastershipRole expectedRole = mastershipService.getLocalRole(deviceId);
778 if (expectedRole == MastershipRole.NONE) {
779 log.debug("Detected invalid role ({}) for {}, waiting for mastership " +
780 "service to fix this...",
781 expectedRole, deviceId);
782 // Gentle nudge to fix things...
783 mastershipService.requestRoleForSync(deviceId);
784 return;
785 }
786
787 final MastershipRole deviceRole = handshaker.getRole();
788 if (expectedRole != deviceRole) {
789 // FIXME: we should be checking the mastership term as well.
790 log.debug("Detected role mismatch for {}, core expects {}, " +
791 "but device reports {}, waiting for mastership " +
792 "service to fix this...",
793 deviceId, expectedRole, deviceRole);
794 // Gentle nudge to fix things...
795 providerService.receivedRoleReply(deviceId, deviceRole);
796 return;
797 }
798
799 // Check and update availability, which differently from reachability
800 // describes the ability of the device to forward packets.
801 if (probeAvailability(handshaker)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800802 // Device ready to do its job.
803 createOrUpdateDevice(deviceId, true);
804 } else {
805 markOfflineIfNeeded(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700806 if (isPipelineProgrammable(deviceId)) {
807 // If reachable, but not available, and pipeline programmable,
808 // there is a high chance it's because the pipeline is not READY
809 // (independently from what the pipeconf watchdog reports, as
810 // the status there might be outdated). Encourage pipeconf
811 // watchdog to perform a pipeline probe ASAP.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800812 pipeconfWatchdogService.triggerProbe(deviceId);
813 }
814 }
815 }
816
817 private void handleMastershipResponse(DeviceId deviceId, MastershipRole response) {
818 assertDeviceRegistered(deviceId);
819 log.debug("Device {} asserted role {}", deviceId, response);
820 providerService.receivedRoleReply(deviceId, response);
821 }
822
823 private void handleNotMaster(DeviceId deviceId) {
824 assertDeviceRegistered(deviceId);
Carmelo Cascone4b616312019-04-17 14:15:45 -0700825 handleMastershipResponse(deviceId, handshakerOrFail(deviceId).getRole());
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800826 }
827
828 private void assertDeviceRegistered(DeviceId deviceId) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700829 if (!deviceIsRegistered(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800830 throw new DeviceTaskException("device not registered in the core");
831 }
832 }
833
Carmelo Cascone4b616312019-04-17 14:15:45 -0700834 private boolean deviceIsRegistered(DeviceId deviceId) {
835 return deviceService.getDevice(deviceId) != null;
836 }
837
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800838 private void handleConnectionTeardown(DeviceId deviceId) {
839 if (deviceService.getDevice(deviceId) != null
840 && deviceService.isAvailable(deviceId)) {
841 providerService.deviceDisconnected(deviceId);
842 }
843 final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
844 handshaker.removeDeviceAgentListener(id());
845 handshakersWithListeners.remove(deviceId);
846 handshaker.disconnect();
Carmelo Cascone4b616312019-04-17 14:15:45 -0700847 lastCheckups.remove(deviceId);
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800848 }
849
850 private void bindPipeconfIfRequired(DeviceId deviceId) {
851 if (pipeconfService.getPipeconf(deviceId).isPresent()
852 || !isPipelineProgrammable(deviceId)) {
853 // Nothing to do.
854 // Device has already a pipeconf or is not programmable.
855 return;
856 }
857 // Get pipeconf from netcfg or driver (default one).
858 final PiPipelineProgrammable pipelineProg = getBehaviour(
859 deviceId, PiPipelineProgrammable.class);
860 final PiPipeconfId pipeconfId = getPipeconfId(deviceId, pipelineProg);
861 if (pipeconfId == null) {
862 throw new DeviceTaskException("unable to find pipeconf");
863 }
Carmelo Cascone4b616312019-04-17 14:15:45 -0700864 if (!pipeconfService.getPipeconf(pipeconfId).isPresent()) {
865 throw new DeviceTaskException(format(
866 "pipeconf %s not registered", pipeconfId));
867 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800868 // Store binding in pipeconf service.
869 pipeconfService.bindToDevice(pipeconfId, deviceId);
870 }
871
872 private PiPipeconfId getPipeconfId(DeviceId deviceId, PiPipelineProgrammable pipelineProg) {
873 // Places to look for a pipeconf ID (in priority order)):
874 // 1) netcfg
875 // 2) device driver (default one)
876 final PiPipeconfId pipeconfId = getPipeconfFromCfg(deviceId);
877 if (pipeconfId != null && !pipeconfId.id().isEmpty()) {
878 return pipeconfId;
879 }
880 if (pipelineProg != null
881 && pipelineProg.getDefaultPipeconf().isPresent()) {
882 final PiPipeconf defaultPipeconf = pipelineProg.getDefaultPipeconf().get();
883 log.info("Using default pipeconf {} for {}", defaultPipeconf.id(), deviceId);
884 return defaultPipeconf.id();
885 }
886 return null;
887 }
888
889 private PiPipeconfId getPipeconfFromCfg(DeviceId deviceId) {
890 BasicDeviceConfig config = cfgService.getConfig(
891 deviceId, BasicDeviceConfig.class);
892 if (config == null) {
893 return null;
894 }
895 return config.pipeconf() != null
896 ? new PiPipeconfId(config.pipeconf()) : null;
897 }
898
899 private DeviceHandshaker handshakerOrFail(DeviceId deviceId) {
900 final DeviceHandshaker handshaker = getBehaviour(
901 deviceId, DeviceHandshaker.class);
902 if (handshaker == null) {
903 throw new DeviceTaskException("missing handshaker behavior");
904 }
905 return handshaker;
906 }
907
Carmelo Cascone4b616312019-04-17 14:15:45 -0700908 private boolean configIsPresent(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800909 final BasicDeviceConfig basicDeviceCfg = cfgService.getConfig(
910 deviceId, BasicDeviceConfig.class);
911 return basicDeviceCfg != null && !isNullOrEmpty(basicDeviceCfg.driver());
912 }
913
914 private void assertConfig(DeviceId deviceId) {
Carmelo Cascone4b616312019-04-17 14:15:45 -0700915 if (!configIsPresent(deviceId)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800916 throw new DeviceTaskException("configuration is not complete");
917 }
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700918 }
919
Andrea Campanella241896c2017-05-10 13:11:04 -0700920 private Driver getDriver(DeviceId deviceId) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700921 try {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200922 // DriverManager checks first using basic device config.
923 return driverService.getDriver(deviceId);
Andrea Campanella241896c2017-05-10 13:11:04 -0700924 } catch (ItemNotFoundException e) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200925 log.error("Driver not found for {}", deviceId);
926 return null;
Andrea Campanella241896c2017-05-10 13:11:04 -0700927 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700928 }
929
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700930 private <T extends Behaviour> T getBehaviour(DeviceId deviceId, Class<T> type) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700931 Driver driver = getDriver(deviceId);
932 if (driver == null) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700933 return null;
934 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700935 if (!driver.hasBehaviour(type)) {
936 return null;
937 }
938 final DriverData data = new DefaultDriverData(driver, deviceId);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700939 final DefaultDriverHandler handler = new DefaultDriverHandler(data);
940 return driver.createBehaviour(handler, type);
Andrea Campanella241896c2017-05-10 13:11:04 -0700941 }
942
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800943 private boolean hasBehaviour(DeviceId deviceId, Class<? extends Behaviour> type) {
944 Driver driver = getDriver(deviceId);
945 if (driver == null) {
946 return false;
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200947 }
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800948 return driver.hasBehaviour(type);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700949 }
950
951 private DeviceDescription getDeviceDescription(
952 DeviceId deviceId, boolean defaultAvailable) {
953 // Get one from driver or forge.
954 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
955 deviceId, DeviceDescriptionDiscovery.class);
Yi Tsengd7716482018-10-31 15:34:30 -0700956 if (deviceDiscovery == null) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700957 return forgeDeviceDescription(deviceId, defaultAvailable);
958 }
Yi Tsengd7716482018-10-31 15:34:30 -0700959
960 final DeviceDescription d = deviceDiscovery.discoverDeviceDetails();
961 if (d == null) {
962 return forgeDeviceDescription(deviceId, defaultAvailable);
963 }
964 // Enforce defaultAvailable flag over the one obtained from driver.
965 return new DefaultDeviceDescription(d, defaultAvailable, d.annotations());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700966 }
967
968 private List<PortDescription> getPortDetails(DeviceId deviceId) {
969 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
970 deviceId, DeviceDescriptionDiscovery.class);
971 if (deviceDiscovery != null) {
972 return deviceDiscovery.discoverPortDetails();
973 } else {
974 return Collections.emptyList();
975 }
976 }
977
978 private DeviceDescription forgeDeviceDescription(
979 DeviceId deviceId, boolean defaultAvailable) {
980 // Uses handshaker and provider config to get driver data.
981 final DeviceHandshaker handshaker = getBehaviour(
982 deviceId, DeviceHandshaker.class);
983 final Driver driver = handshaker != null
984 ? handshaker.handler().driver() : null;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700985 return new DefaultDeviceDescription(
986 deviceId.uri(),
987 Device.Type.SWITCH,
988 driver != null ? driver.manufacturer() : UNKNOWN,
989 driver != null ? driver.hwVersion() : UNKNOWN,
990 driver != null ? driver.swVersion() : UNKNOWN,
991 UNKNOWN,
992 new ChassisId(),
993 defaultAvailable,
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800994 DefaultAnnotations.EMPTY);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700995 }
996
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800997 static boolean myScheme(DeviceId deviceId) {
998 return deviceId.uri().getScheme().equals(URI_SCHEME);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200999 }
1000
Carmelo Cascone9e4972c2018-08-30 00:29:16 -07001001 private boolean isPipelineProgrammable(DeviceId deviceId) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -08001002 return hasBehaviour(deviceId, PiPipelineProgrammable.class);
Carmelo Casconede3b6842018-09-05 17:45:10 -07001003 }
Thomas Vachuska1b3cf362019-08-29 17:11:18 -07001004
1005 private class InternalDeviceListener implements DeviceListener {
1006 @Override
1007 public void event(DeviceEvent event) {
1008 log.info("Triggering disconnect for device {}", event.subject().id());
1009 triggerDisconnect(event.subject().id());
1010 }
1011
1012 @Override
1013 public boolean isRelevant(DeviceEvent event) {
Thomas Vachuska24c0ca42019-08-29 18:19:16 -07001014 return DeviceEvent.Type.DEVICE_REMOVED == event.type() && myScheme(event.subject().id());
Thomas Vachuska1b3cf362019-08-29 17:11:18 -07001015 }
1016 }
Andrea Campanella241896c2017-05-10 13:11:04 -07001017}