blob: 3ca56ee664dba2dbaf7a7e4fc568ad70ba79e88b [file] [log] [blame]
Andrea Campanella241896c2017-05-10 13:11:04 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Andrea Campanella241896c2017-05-10 13:11:04 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.provider.general.device.impl;
18
19import com.google.common.annotations.Beta;
Andrea Campanellabc112a92017-06-26 19:06:43 +020020import com.google.common.collect.ImmutableSet;
21import com.google.common.collect.Maps;
Carmelo Cascone158b8c42018-07-04 19:42:37 +020022import com.google.common.util.concurrent.Striped;
Andrea Campanella241896c2017-05-10 13:11:04 -070023import org.onlab.packet.ChassisId;
24import org.onlab.util.ItemNotFoundException;
Andrea Campanella19090322017-08-22 10:31:37 +020025import org.onlab.util.Tools;
Andrea Campanella4929a812017-10-09 18:38:23 +020026import org.onosproject.cfg.ComponentConfigService;
Andrea Campanella241896c2017-05-10 13:11:04 -070027import org.onosproject.core.CoreService;
Andrea Campanella14e196d2017-07-24 18:11:36 +020028import org.onosproject.mastership.MastershipService;
Andrea Campanella241896c2017-05-10 13:11:04 -070029import org.onosproject.net.AnnotationKeys;
30import org.onosproject.net.DefaultAnnotations;
31import org.onosproject.net.Device;
32import org.onosproject.net.DeviceId;
33import org.onosproject.net.MastershipRole;
34import org.onosproject.net.PortNumber;
Carmelo Cascone87892e22017-11-13 16:01:29 -080035import org.onosproject.net.behaviour.PiPipelineProgrammable;
Andrea Campanella241896c2017-05-10 13:11:04 -070036import org.onosproject.net.behaviour.PortAdmin;
37import org.onosproject.net.config.ConfigFactory;
38import org.onosproject.net.config.NetworkConfigEvent;
39import org.onosproject.net.config.NetworkConfigListener;
40import org.onosproject.net.config.NetworkConfigRegistry;
41import org.onosproject.net.config.basics.BasicDeviceConfig;
42import org.onosproject.net.config.basics.SubjectFactories;
43import org.onosproject.net.device.DefaultDeviceDescription;
Carmelo Casconee5b28722018-06-22 17:28:28 +020044import org.onosproject.net.device.DeviceAgentEvent;
45import org.onosproject.net.device.DeviceAgentListener;
Andrea Campanella241896c2017-05-10 13:11:04 -070046import org.onosproject.net.device.DeviceDescription;
47import org.onosproject.net.device.DeviceDescriptionDiscovery;
48import org.onosproject.net.device.DeviceEvent;
49import org.onosproject.net.device.DeviceHandshaker;
50import org.onosproject.net.device.DeviceListener;
51import org.onosproject.net.device.DeviceProvider;
52import org.onosproject.net.device.DeviceProviderRegistry;
53import org.onosproject.net.device.DeviceProviderService;
54import org.onosproject.net.device.DeviceService;
55import org.onosproject.net.device.PortDescription;
56import org.onosproject.net.device.PortStatistics;
57import org.onosproject.net.device.PortStatisticsDiscovery;
58import 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.PiPipeconfConfig;
67import org.onosproject.net.pi.service.PiPipeconfService;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070068import org.onosproject.net.pi.service.PiPipeconfWatchdogEvent;
69import org.onosproject.net.pi.service.PiPipeconfWatchdogListener;
70import org.onosproject.net.pi.service.PiPipeconfWatchdogService;
Andrea Campanella241896c2017-05-10 13:11:04 -070071import org.onosproject.net.provider.AbstractProvider;
72import org.onosproject.net.provider.ProviderId;
73import org.onosproject.provider.general.device.api.GeneralProviderDeviceConfig;
Andrea Campanella19090322017-08-22 10:31:37 +020074import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070075import org.osgi.service.component.annotations.Activate;
76import org.osgi.service.component.annotations.Component;
77import org.osgi.service.component.annotations.Deactivate;
78import org.osgi.service.component.annotations.Modified;
79import org.osgi.service.component.annotations.Reference;
80import org.osgi.service.component.annotations.ReferenceCardinality;
Andrea Campanella241896c2017-05-10 13:11:04 -070081import org.slf4j.Logger;
82
Ray Milkeyb68bbbc2017-12-18 10:05:49 -080083import java.security.SecureRandom;
Andrea Campanella241896c2017-05-10 13:11:04 -070084import java.util.Collection;
Andrea Campanellabc112a92017-06-26 19:06:43 +020085import java.util.Collections;
Andrea Campanella19090322017-08-22 10:31:37 +020086import java.util.Dictionary;
Andrea Campanella241896c2017-05-10 13:11:04 -070087import java.util.List;
Thomas Vachuska5b38dc02018-05-10 15:24:40 -070088import java.util.Map;
Andrea Campanellabc112a92017-06-26 19:06:43 +020089import java.util.Set;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070090import java.util.StringJoiner;
Andrea Campanella241896c2017-05-10 13:11:04 -070091import java.util.concurrent.CompletableFuture;
Andrea Campanella19090322017-08-22 10:31:37 +020092import java.util.concurrent.ConcurrentHashMap;
Andrea Campanellabc112a92017-06-26 19:06:43 +020093import java.util.concurrent.ConcurrentMap;
94import java.util.concurrent.CopyOnWriteArraySet;
Andrea Campanella241896c2017-05-10 13:11:04 -070095import java.util.concurrent.ExecutionException;
Carmelo Casconee5b28722018-06-22 17:28:28 +020096import java.util.concurrent.ExecutorService;
Andrea Campanella241896c2017-05-10 13:11:04 -070097import java.util.concurrent.ScheduledExecutorService;
Andrea Campanella19090322017-08-22 10:31:37 +020098import java.util.concurrent.ScheduledFuture;
Andrea Campanella241896c2017-05-10 13:11:04 -070099import java.util.concurrent.TimeUnit;
100import java.util.concurrent.TimeoutException;
Andrea Campanellabc112a92017-06-26 19:06:43 +0200101import java.util.concurrent.locks.Lock;
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200102import java.util.function.Supplier;
Andrea Campanella241896c2017-05-10 13:11:04 -0700103
Carmelo Casconee5b28722018-06-22 17:28:28 +0200104import static java.util.concurrent.Executors.newFixedThreadPool;
Andrea Campanella241896c2017-05-10 13:11:04 -0700105import static java.util.concurrent.Executors.newScheduledThreadPool;
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200106import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Andrea Campanella241896c2017-05-10 13:11:04 -0700107import static org.onlab.util.Tools.groupedThreads;
108import static org.onosproject.net.device.DeviceEvent.Type;
Yi Tsengd7716482018-10-31 15:34:30 -0700109import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.OP_TIMEOUT_SHORT;
110import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.OP_TIMEOUT_SHORT_DEFAULT;
111import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.PROBE_FREQUENCY;
112import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.PROBE_FREQUENCY_DEFAULT;
113import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.STATS_POLL_FREQUENCY;
114import static org.onosproject.provider.general.device.impl.OsgiPropertyConstants.STATS_POLL_FREQUENCY_DEFAULT;
Andrea Campanella241896c2017-05-10 13:11:04 -0700115import static org.slf4j.LoggerFactory.getLogger;
116
117/**
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200118 * Provider which uses drivers to detect device and do initial handshake and
119 * channel establishment with devices. Any other provider specific operation is
120 * also delegated to the DeviceHandshaker driver.
Andrea Campanella241896c2017-05-10 13:11:04 -0700121 */
122@Beta
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700123@Component(immediate = true,
124 property = {
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -0700125 STATS_POLL_FREQUENCY + ":Integer=" + STATS_POLL_FREQUENCY_DEFAULT,
126 PROBE_FREQUENCY + ":Integer=" + PROBE_FREQUENCY_DEFAULT,
127 OP_TIMEOUT_SHORT + ":Integer=" + OP_TIMEOUT_SHORT_DEFAULT,
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700128 })
Andrea Campanella241896c2017-05-10 13:11:04 -0700129public class GeneralDeviceProvider extends AbstractProvider
130 implements DeviceProvider {
Carmelo Casconee5b28722018-06-22 17:28:28 +0200131
Andrea Campanella241896c2017-05-10 13:11:04 -0700132 private final Logger log = getLogger(getClass());
133
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700134 private static final String APP_NAME = "org.onosproject.gdp";
135 private static final String URI_SCHEME = "device";
136 private static final String CFG_SCHEME = "generalprovider";
137 private static final String DEVICE_PROVIDER_PACKAGE =
138 "org.onosproject.general.provider.device";
139 private static final int CORE_POOL_SIZE = 10;
140 private static final String UNKNOWN = "unknown";
141 private static final String DRIVER = "driver";
142 private static final Set<String> PIPELINE_CONFIGURABLE_PROTOCOLS =
143 ImmutableSet.of("p4runtime");
144
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700145 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200146 private DeviceProviderRegistry providerRegistry;
Andrea Campanella241896c2017-05-10 13:11:04 -0700147
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700148 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200149 private ComponentConfigService componentConfigService;
Andrea Campanella4929a812017-10-09 18:38:23 +0200150
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700151 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200152 private NetworkConfigRegistry cfgService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700153
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700154 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200155 private CoreService coreService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700156
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200158 private DeviceService deviceService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700159
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700160 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200161 private DriverService driverService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700162
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700163 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Casconee5b28722018-06-22 17:28:28 +0200164 private MastershipService mastershipService;
Andrea Campanella14e196d2017-07-24 18:11:36 +0200165
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700166 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700167 private PiPipeconfService pipeconfService;
Andrea Campanella241896c2017-05-10 13:11:04 -0700168
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700169 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700170 private PiPipeconfWatchdogService pipeconfWatchdogService;
Andrea Campanella14e196d2017-07-24 18:11:36 +0200171
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -0700172 /**
173 * Configure poll frequency for port status and statistics; default is 10 sec.
174 */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700175 private int statsPollFrequency = STATS_POLL_FREQUENCY_DEFAULT;
Andrea Campanella19090322017-08-22 10:31:37 +0200176
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -0700177 /**
178 * Configure probe frequency for checking device availability; default is 10 sec.
179 */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700180 private int probeFrequency = PROBE_FREQUENCY_DEFAULT;
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200181
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -0700182 /**
183 * Configure timeout in seconds for device operations that are supposed to take a short time
184 * (e.g. checking device reachability); default is 10 seconds.
185 */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700186 private int opTimeoutShort = OP_TIMEOUT_SHORT_DEFAULT;
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200187
Andrea Campanellabc112a92017-06-26 19:06:43 +0200188 //FIXME to be removed when netcfg will issue device events in a bundle or
189 //ensures all configuration needed is present
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700190 private final Set<DeviceId> deviceConfigured = new CopyOnWriteArraySet<>();
191 private final Set<DeviceId> driverConfigured = new CopyOnWriteArraySet<>();
192 private final Set<DeviceId> pipelineConfigured = new CopyOnWriteArraySet<>();
Andrea Campanella241896c2017-05-10 13:11:04 -0700193
Carmelo Casconee5b28722018-06-22 17:28:28 +0200194 private final Map<DeviceId, MastershipRole> requestedRoles = Maps.newConcurrentMap();
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700195 private final ConcurrentMap<DeviceId, ScheduledFuture<?>> statsPollingTasks = new ConcurrentHashMap<>();
196 private final Map<DeviceId, DeviceHandshaker> handshakersWithListeners = Maps.newConcurrentMap();
197 private final InternalDeviceListener deviceListener = new InternalDeviceListener();
198 private final InternalPipeconfWatchdogListener pipeconfWatchdogListener = new InternalPipeconfWatchdogListener();
Carmelo Casconee5b28722018-06-22 17:28:28 +0200199 private final NetworkConfigListener cfgListener = new InternalNetworkConfigListener();
200 private final DeviceAgentListener deviceAgentListener = new InternalDeviceAgentListener();
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700201 private final ConfigFactory factory = new InternalConfigFactory();
202 private final Striped<Lock> deviceLocks = Striped.lock(30);
Andrea Campanella241896c2017-05-10 13:11:04 -0700203
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700204 private ExecutorService connectionExecutor;
205 private ScheduledExecutorService statsExecutor;
206 private ScheduledExecutorService probeExecutor;
207 private ScheduledFuture<?> probeTask;
208 private DeviceProviderService providerService;
209
210 public GeneralDeviceProvider() {
211 super(new ProviderId(URI_SCHEME, DEVICE_PROVIDER_PACKAGE));
212 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700213
214 @Activate
Andrea Campanella1e573442018-05-17 17:07:13 +0200215 public void activate(ComponentContext context) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700216 connectionExecutor = newFixedThreadPool(CORE_POOL_SIZE, groupedThreads(
217 "onos/gdp-connect", "%d", log));
218 statsExecutor = newScheduledThreadPool(CORE_POOL_SIZE, groupedThreads(
219 "onos/gdp-stats", "%d", log));
220 probeExecutor = newSingleThreadScheduledExecutor(groupedThreads(
221 "onos/gdp-probe", "%d", log));
Andrea Campanella241896c2017-05-10 13:11:04 -0700222 providerService = providerRegistry.register(this);
Andrea Campanella4929a812017-10-09 18:38:23 +0200223 componentConfigService.registerProperties(getClass());
Andrea Campanella241896c2017-05-10 13:11:04 -0700224 coreService.registerApplication(APP_NAME);
225 cfgService.registerConfigFactory(factory);
226 cfgService.addListener(cfgListener);
227 deviceService.addListener(deviceListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700228 pipeconfWatchdogService.addListener(pipeconfWatchdogListener);
229 rescheduleProbeTask(false);
Andrea Campanella1e573442018-05-17 17:07:13 +0200230 modified(context);
Andrea Campanella241896c2017-05-10 13:11:04 -0700231 log.info("Started");
232 }
233
Andrea Campanella19090322017-08-22 10:31:37 +0200234 @Modified
235 public void modified(ComponentContext context) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200236 if (context == null) {
237 return;
Andrea Campanella19090322017-08-22 10:31:37 +0200238 }
239
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200240 Dictionary<?, ?> properties = context.getProperties();
241 final int oldStatsPollFrequency = statsPollFrequency;
242 statsPollFrequency = Tools.getIntegerProperty(
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700243 properties, STATS_POLL_FREQUENCY, STATS_POLL_FREQUENCY_DEFAULT);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200244 log.info("Configured. {} is configured to {} seconds",
245 STATS_POLL_FREQUENCY, statsPollFrequency);
246 final int oldProbeFrequency = probeFrequency;
247 probeFrequency = Tools.getIntegerProperty(
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700248 properties, PROBE_FREQUENCY, PROBE_FREQUENCY_DEFAULT);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200249 log.info("Configured. {} is configured to {} seconds",
250 PROBE_FREQUENCY, probeFrequency);
251 opTimeoutShort = Tools.getIntegerProperty(
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700252 properties, OP_TIMEOUT_SHORT, OP_TIMEOUT_SHORT_DEFAULT);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200253 log.info("Configured. {} is configured to {} seconds",
254 OP_TIMEOUT_SHORT, opTimeoutShort);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200255
256 if (oldStatsPollFrequency != statsPollFrequency) {
257 rescheduleStatsPollingTasks();
Andrea Campanella19090322017-08-22 10:31:37 +0200258 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200259
260 if (oldProbeFrequency != probeFrequency) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700261 rescheduleProbeTask(true);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200262 }
263 }
264
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700265 private void rescheduleProbeTask(boolean deelay) {
266 synchronized (this) {
267 if (probeTask != null) {
268 probeTask.cancel(false);
269 }
270 probeTask = probeExecutor.scheduleAtFixedRate(
271 this::triggerProbeAllDevices,
272 deelay ? probeFrequency : 0,
273 probeFrequency,
274 TimeUnit.SECONDS);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200275 }
Andrea Campanella19090322017-08-22 10:31:37 +0200276 }
277
Andrea Campanella241896c2017-05-10 13:11:04 -0700278 @Deactivate
279 public void deactivate() {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700280 // Shutdown stats polling tasks.
281 statsPollingTasks.keySet().forEach(this::cancelStatsPolling);
282 statsPollingTasks.clear();
283 statsExecutor.shutdownNow();
284 try {
285 statsExecutor.awaitTermination(5, TimeUnit.SECONDS);
286 } catch (InterruptedException e) {
287 log.warn("statsExecutor not terminated properly");
288 }
289 statsExecutor = null;
290 // Shutdown probe executor.
291 probeTask.cancel(true);
292 probeTask = null;
293 probeExecutor.shutdownNow();
294 try {
295 probeExecutor.awaitTermination(5, TimeUnit.SECONDS);
296 } catch (InterruptedException e) {
297 log.warn("probeExecutor not terminated properly");
298 }
299 probeExecutor = null;
300 // Shutdown connection executor.
301 connectionExecutor.shutdownNow();
302 try {
303 connectionExecutor.awaitTermination(5, TimeUnit.SECONDS);
304 } catch (InterruptedException e) {
305 log.warn("connectionExecutor not terminated properly");
306 }
307 connectionExecutor = null;
308 // Remove all device agent listeners
309 handshakersWithListeners.values().forEach(h -> h.removeDeviceAgentListener(id()));
310 handshakersWithListeners.clear();
311 // Other cleanup.
Andrea Campanella4929a812017-10-09 18:38:23 +0200312 componentConfigService.unregisterProperties(getClass(), false);
Andrea Campanella241896c2017-05-10 13:11:04 -0700313 cfgService.removeListener(cfgListener);
Andrea Campanella241896c2017-05-10 13:11:04 -0700314 deviceService.removeListener(deviceListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700315 pipeconfWatchdogService.removeListener(pipeconfWatchdogListener);
Andrea Campanella241896c2017-05-10 13:11:04 -0700316 providerRegistry.unregister(this);
317 providerService = null;
318 cfgService.unregisterConfigFactory(factory);
319 log.info("Stopped");
320 }
321
Andrea Campanella241896c2017-05-10 13:11:04 -0700322
323 @Override
324 public void triggerProbe(DeviceId deviceId) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200325 connectionExecutor.execute(withDeviceLock(
326 () -> doDeviceProbe(deviceId), deviceId));
Andrea Campanella241896c2017-05-10 13:11:04 -0700327 }
328
329 @Override
330 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700331 log.info("Notifying role {} to device {}", newRole, deviceId);
Carmelo Casconee5b28722018-06-22 17:28:28 +0200332 requestedRoles.put(deviceId, newRole);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200333 connectionExecutor.execute(() -> doRoleChanged(deviceId, newRole));
Carmelo Casconee5b28722018-06-22 17:28:28 +0200334 }
335
336 private void doRoleChanged(DeviceId deviceId, MastershipRole newRole) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700337 final DeviceHandshaker handshaker = getBehaviour(
338 deviceId, DeviceHandshaker.class);
Carmelo Casconee5b28722018-06-22 17:28:28 +0200339 if (handshaker == null) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200340 log.error("Null handshaker. Unable to notify new role {} to {}",
341 newRole, deviceId);
Carmelo Casconee5b28722018-06-22 17:28:28 +0200342 return;
343 }
344 handshaker.roleChanged(newRole);
Andrea Campanella241896c2017-05-10 13:11:04 -0700345 }
346
347 @Override
348 public boolean isReachable(DeviceId deviceId) {
Andrea Campanella14e196d2017-07-24 18:11:36 +0200349 log.debug("Testing reachability for device {}", deviceId);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700350 final DeviceHandshaker handshaker = getBehaviour(
351 deviceId, DeviceHandshaker.class);
Andrea Campanellac1ecdd02018-01-12 12:48:24 +0100352 if (handshaker == null) {
353 return false;
354 }
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200355 return getFutureWithDeadline(
356 handshaker.isReachable(), "checking reachability",
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200357 deviceId, false, opTimeoutShort);
Andrea Campanella241896c2017-05-10 13:11:04 -0700358 }
359
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700360 private boolean isConnected(DeviceId deviceId) {
361 log.debug("Testing connection to device {}", deviceId);
362 final DeviceHandshaker handshaker = getBehaviour(
363 deviceId, DeviceHandshaker.class);
364 if (handshaker == null) {
365 return false;
366 }
367 return handshaker.isConnected();
368 }
369
Andrea Campanella241896c2017-05-10 13:11:04 -0700370 @Override
371 public void changePortState(DeviceId deviceId, PortNumber portNumber,
372 boolean enable) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200373 connectionExecutor.execute(
374 () -> doChangePortState(deviceId, portNumber, enable));
375 }
376
377 private void doChangePortState(DeviceId deviceId, PortNumber portNumber,
378 boolean enable) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200379 if (!deviceService.getDevice(deviceId).is(PortAdmin.class)) {
380 log.warn("Missing PortAdmin behaviour on {}, aborting port state change",
381 deviceId);
382 return;
Andrea Campanella241896c2017-05-10 13:11:04 -0700383 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200384 final PortAdmin portAdmin = deviceService.getDevice(deviceId)
385 .as(PortAdmin.class);
386 final CompletableFuture<Boolean> modifyTask = enable
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200387 ? portAdmin.enable(portNumber)
388 : portAdmin.disable(portNumber);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200389 final String descr = (enable ? "enabling" : "disabling") + " port " + portNumber;
390 getFutureWithDeadline(
391 modifyTask, descr, deviceId, null, opTimeoutShort);
Andrea Campanella241896c2017-05-10 13:11:04 -0700392 }
393
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700394 @Override
395 public void triggerDisconnect(DeviceId deviceId) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200396 log.debug("Triggering disconnection of device {}", deviceId);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200397 connectionExecutor.execute(withDeviceLock(
398 () -> doDisconnectDevice(deviceId), deviceId));
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700399 }
400
Andrea Campanella241896c2017-05-10 13:11:04 -0700401 private Driver getDriver(DeviceId deviceId) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700402 try {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200403 // DriverManager checks first using basic device config.
404 return driverService.getDriver(deviceId);
Andrea Campanella241896c2017-05-10 13:11:04 -0700405 } catch (ItemNotFoundException e) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200406 log.error("Driver not found for {}", deviceId);
407 return null;
Andrea Campanella241896c2017-05-10 13:11:04 -0700408 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700409 }
410
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700411 private <T extends Behaviour> T getBehaviour(DeviceId deviceId, Class<T> type) {
412 // Get handshaker.
413
414 Driver driver = getDriver(deviceId);
415 if (driver == null) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700416 return null;
417 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700418 if (!driver.hasBehaviour(type)) {
419 return null;
420 }
421 final DriverData data = new DefaultDriverData(driver, deviceId);
422 // Storing deviceKeyId and all other config values as data in the driver
423 // with protocol_<info> name as the key. e.g protocol_ip.
424 final GeneralProviderDeviceConfig providerConfig = cfgService.getConfig(
425 deviceId, GeneralProviderDeviceConfig.class);
426 if (providerConfig != null) {
427 providerConfig.protocolsInfo().forEach((protocol, info) -> {
428 info.configValues().forEach(
429 (k, v) -> data.set(protocol + "_" + k, v));
430 data.set(protocol + "_key", info.deviceKeyId());
431 });
432 }
433 final DefaultDriverHandler handler = new DefaultDriverHandler(data);
434 return driver.createBehaviour(handler, type);
Andrea Campanella241896c2017-05-10 13:11:04 -0700435 }
436
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200437 private void doConnectDevice(DeviceId deviceId) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700438 log.debug("Initiating connection to device {}...", deviceId);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200439 // Retrieve config
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700440 if (configIsMissing(deviceId)) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200441 return;
442 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700443 // Bind pipeconf (if any and if device is capable).
444 if (!bindPipeconfIfRequired(deviceId)) {
445 // We already logged the error.
446 return;
447 }
448 // Get handshaker.
449 final DeviceHandshaker handshaker = getBehaviour(
450 deviceId, DeviceHandshaker.class);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200451 if (handshaker == null) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700452 log.error("Missing handshaker behavior for {}, aborting connection",
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200453 deviceId);
454 return;
455 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700456 // Add device agent listener.
457 handshaker.addDeviceAgentListener(id(), deviceAgentListener);
458 handshakersWithListeners.put(deviceId, handshaker);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200459 // Start connection via handshaker.
460 final Boolean connectSuccess = getFutureWithDeadline(
461 handshaker.connect(), "initiating connection",
Carmelo Casconede3b6842018-09-05 17:45:10 -0700462 deviceId, false, opTimeoutShort);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700463 if (!connectSuccess) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200464 log.warn("Unable to connect to {}", deviceId);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700465 }
466 }
467
468 private void triggerAdvertiseDevice(DeviceId deviceId) {
469 connectionExecutor.execute(withDeviceLock(
470 () -> doAdvertiseDevice(deviceId), deviceId));
471 }
472
473 private void doAdvertiseDevice(DeviceId deviceId) {
474 // Retrieve config
475 if (configIsMissing(deviceId)) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200476 return;
477 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700478 // Obtain device and port description.
479 final boolean isPipelineReady = isPipelineReady(deviceId);
480 final DeviceDescription description = getDeviceDescription(
481 deviceId, isPipelineReady);
482 final List<PortDescription> ports = getPortDetails(deviceId);
483 // Advertise to core.
484 if (deviceService.getDevice(deviceId) == null ||
485 (description.isDefaultAvailable() &&
486 !deviceService.isAvailable(deviceId))) {
487 if (!isPipelineReady) {
488 log.info("Advertising device to core with available={} as " +
489 "device pipeline is not ready yet",
490 description.isDefaultAvailable());
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400491 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700492 providerService.deviceConnected(deviceId, description);
Carmelo Cascone1fb27d32017-08-25 20:40:20 +0200493 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700494 providerService.updatePorts(deviceId, ports);
495 // If pipeline is not ready, encourage watchdog to perform probe ASAP.
496 if (!isPipelineReady) {
497 pipeconfWatchdogService.triggerProbe(deviceId);
498 }
499 }
500
501 private DeviceDescription getDeviceDescription(
502 DeviceId deviceId, boolean defaultAvailable) {
503 // Get one from driver or forge.
504 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
505 deviceId, DeviceDescriptionDiscovery.class);
Yi Tsengd7716482018-10-31 15:34:30 -0700506 if (deviceDiscovery == null) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700507 return forgeDeviceDescription(deviceId, defaultAvailable);
508 }
Yi Tsengd7716482018-10-31 15:34:30 -0700509
510 final DeviceDescription d = deviceDiscovery.discoverDeviceDetails();
511 if (d == null) {
512 return forgeDeviceDescription(deviceId, defaultAvailable);
513 }
514 // Enforce defaultAvailable flag over the one obtained from driver.
515 return new DefaultDeviceDescription(d, defaultAvailable, d.annotations());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700516 }
517
518 private List<PortDescription> getPortDetails(DeviceId deviceId) {
519 final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour(
520 deviceId, DeviceDescriptionDiscovery.class);
521 if (deviceDiscovery != null) {
522 return deviceDiscovery.discoverPortDetails();
523 } else {
524 return Collections.emptyList();
525 }
526 }
527
528 private DeviceDescription forgeDeviceDescription(
529 DeviceId deviceId, boolean defaultAvailable) {
530 // Uses handshaker and provider config to get driver data.
531 final DeviceHandshaker handshaker = getBehaviour(
532 deviceId, DeviceHandshaker.class);
533 final Driver driver = handshaker != null
534 ? handshaker.handler().driver() : null;
535 final GeneralProviderDeviceConfig cfg = cfgService.getConfig(
536 deviceId, GeneralProviderDeviceConfig.class);
537 final DefaultAnnotations.Builder annBuilder = DefaultAnnotations.builder();
538 // If device is pipeline programmable, let this provider decide when the
539 // device can be marked online.
540 annBuilder.set(AnnotationKeys.PROVIDER_MARK_ONLINE,
541 String.valueOf(isPipelineProgrammable(deviceId)));
542 if (cfg != null) {
543 StringJoiner protoStringBuilder = new StringJoiner(", ");
544 cfg.protocolsInfo().keySet().forEach(protoStringBuilder::add);
545 annBuilder.set(AnnotationKeys.PROTOCOL, protoStringBuilder.toString());
546 }
547 return new DefaultDeviceDescription(
548 deviceId.uri(),
549 Device.Type.SWITCH,
550 driver != null ? driver.manufacturer() : UNKNOWN,
551 driver != null ? driver.hwVersion() : UNKNOWN,
552 driver != null ? driver.swVersion() : UNKNOWN,
553 UNKNOWN,
554 new ChassisId(),
555 defaultAvailable,
556 annBuilder.build());
557 }
558
559 private void triggerMarkAvailable(DeviceId deviceId) {
560 connectionExecutor.execute(withDeviceLock(
561 () -> doMarkAvailable(deviceId), deviceId));
562 }
563
564 private void doMarkAvailable(DeviceId deviceId) {
565 if (deviceService.isAvailable(deviceId)) {
566 return;
567 }
568 final DeviceDescription descr = getDeviceDescription(deviceId, true);
569 // It has been observed that devices that were marked offline (e.g.
570 // after device disconnection) might end up with no master. Here we
571 // trigger a new master election (if device has no master).
572 mastershipService.requestRoleForSync(deviceId);
573 providerService.deviceConnected(deviceId, descr);
574 }
575
576 private boolean bindPipeconfIfRequired(DeviceId deviceId) {
577 if (pipeconfService.ofDevice(deviceId).isPresent()
578 || !isPipelineProgrammable(deviceId)) {
579 // Nothing to do, all good.
580 return true;
581 }
582 // Get pipeconf from netcfg or driver (default one).
583 final PiPipelineProgrammable pipelineProg = getBehaviour(
584 deviceId, PiPipelineProgrammable.class);
585 final PiPipeconfId pipeconfId = getPipeconfId(deviceId, pipelineProg);
586 if (pipeconfId == null) {
587 return false;
588 }
589 // Store binding in pipeconf service.
590 pipeconfService.bindToDevice(pipeconfId, deviceId);
591 return true;
592 }
593
594 private PiPipeconfId getPipeconfId(DeviceId deviceId, PiPipelineProgrammable pipelineProg) {
595 // Places to look for a pipeconf ID (in priority order)):
596 // 1) netcfg
597 // 2) device driver (default one)
598 final PiPipeconfId pipeconfId = getPipeconfFromCfg(deviceId);
599 if (pipeconfId != null && !pipeconfId.id().isEmpty()) {
600 return pipeconfId;
601 }
602 if (pipelineProg != null
603 && pipelineProg.getDefaultPipeconf().isPresent()) {
604 final PiPipeconf defaultPipeconf = pipelineProg.getDefaultPipeconf().get();
605 log.info("Using default pipeconf {} for {}", defaultPipeconf.id(), deviceId);
606 return defaultPipeconf.id();
607 } else {
608 log.warn("Unable to associate a pipeconf to {}", deviceId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200609 return null;
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400610 }
Carmelo Cascone59f57de2017-07-11 19:55:09 -0400611 }
612
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200613 private void doDisconnectDevice(DeviceId deviceId) {
Carmelo Cascone7044efd2018-07-06 13:01:36 +0200614 log.debug("Initiating disconnection from {}...", deviceId);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700615 final DeviceHandshaker handshaker = getBehaviour(
616 deviceId, DeviceHandshaker.class);
Carmelo Cascone7044efd2018-07-06 13:01:36 +0200617 final boolean isAvailable = deviceService.isAvailable(deviceId);
618 // Signal disconnection to core (if master).
619 if (isAvailable && mastershipService.isLocalMaster(deviceId)) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200620 providerService.deviceDisconnected(deviceId);
621 }
Carmelo Cascone7044efd2018-07-06 13:01:36 +0200622 // Cancel tasks.
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200623 cancelStatsPolling(deviceId);
Carmelo Cascone7044efd2018-07-06 13:01:36 +0200624 // Disconnect device.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200625 if (handshaker == null) {
Carmelo Cascone7044efd2018-07-06 13:01:36 +0200626 if (isAvailable) {
627 // If not available don't bother logging. We are probably
628 // invoking this method multiple times for the same device.
629 log.warn("Missing DeviceHandshaker behavior for {}, " +
630 "no guarantees of complete disconnection",
631 deviceId);
632 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200633 return;
Andrea Campanella241896c2017-05-10 13:11:04 -0700634 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700635 handshaker.removeDeviceAgentListener(id());
636 handshakersWithListeners.remove(deviceId);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200637 final boolean disconnectSuccess = getFutureWithDeadline(
638 handshaker.disconnect(), "performing disconnection",
639 deviceId, false, opTimeoutShort);
640 if (!disconnectSuccess) {
641 log.warn("Unable to disconnect from {}", deviceId);
642 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700643 }
644
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200645 // Needed to catch the exception in the executors since are not rethrown otherwise.
Andrea Campanella241896c2017-05-10 13:11:04 -0700646 private Runnable exceptionSafe(Runnable runnable) {
647 return () -> {
648 try {
649 runnable.run();
650 } catch (Exception e) {
651 log.error("Unhandled Exception", e);
652 }
653 };
654 }
655
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200656 private <U> U withDeviceLock(Supplier<U> task, DeviceId deviceId) {
657 final Lock lock = deviceLocks.get(deviceId);
658 lock.lock();
659 try {
660 return task.get();
661 } finally {
662 lock.unlock();
663 }
664 }
665
666 private Runnable withDeviceLock(Runnable task, DeviceId deviceId) {
667 // Wrapper of withDeviceLock(Supplier, ...) for void tasks.
668 return () -> withDeviceLock(() -> {
669 task.run();
670 return null;
671 }, deviceId);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200672 }
673
Andrea Campanella241896c2017-05-10 13:11:04 -0700674 private void updatePortStatistics(DeviceId deviceId) {
Andrea Campanellace111932017-09-18 16:59:56 +0900675 Device device = deviceService.getDevice(deviceId);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200676 if (device != null && deviceService.isAvailable(deviceId) &&
Andrea Campanellace111932017-09-18 16:59:56 +0900677 device.is(PortStatisticsDiscovery.class)) {
678 Collection<PortStatistics> statistics = device.as(PortStatisticsDiscovery.class)
679 .discoverPortStatistics();
680 //updating statistcs only if not empty
681 if (!statistics.isEmpty()) {
682 providerService.updatePortStatistics(deviceId, statistics);
683 }
684 } else {
685 log.debug("Can't update port statistics for device {}", deviceId);
Andrea Campanella19090322017-08-22 10:31:37 +0200686 }
687 }
688
Carmelo Casconee5b28722018-06-22 17:28:28 +0200689 private boolean notMyScheme(DeviceId deviceId) {
690 return !deviceId.uri().getScheme().equals(URI_SCHEME);
Andrea Campanella241896c2017-05-10 13:11:04 -0700691 }
692
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200693 private void triggerConnect(DeviceId deviceId) {
694 connectionExecutor.execute(withDeviceLock(
695 () -> doConnectDevice(deviceId), deviceId));
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200696 }
697
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700698 private boolean isPipelineProgrammable(DeviceId deviceId) {
699 final GeneralProviderDeviceConfig providerConfig = cfgService.getConfig(
700 deviceId, GeneralProviderDeviceConfig.class);
701 if (providerConfig == null) {
702 return false;
703 }
704 return !Collections.disjoint(
705 ImmutableSet.copyOf(providerConfig.node().fieldNames()),
706 PIPELINE_CONFIGURABLE_PROTOCOLS);
707 }
708
Andrea Campanella241896c2017-05-10 13:11:04 -0700709 /**
710 * Listener for configuration events.
711 */
712 private class InternalNetworkConfigListener implements NetworkConfigListener {
713
Andrea Campanella241896c2017-05-10 13:11:04 -0700714 @Override
715 public void event(NetworkConfigEvent event) {
Carmelo Cascone7044efd2018-07-06 13:01:36 +0200716 connectionExecutor.execute(() -> consumeConfigEvent(event));
717 }
718
719 @Override
720 public boolean isRelevant(NetworkConfigEvent event) {
721 return (event.configClass().equals(GeneralProviderDeviceConfig.class) ||
722 event.configClass().equals(BasicDeviceConfig.class) ||
723 event.configClass().equals(PiPipeconfConfig.class)) &&
724 (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
725 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED);
726 }
727
728 private void consumeConfigEvent(NetworkConfigEvent event) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700729 DeviceId deviceId = (DeviceId) event.subject();
730 //Assuming that the deviceId comes with uri 'device:'
Carmelo Casconee5b28722018-06-22 17:28:28 +0200731 if (notMyScheme(deviceId)) {
Andrea Campanella241896c2017-05-10 13:11:04 -0700732 // not under my scheme, skipping
733 log.debug("{} is not my scheme, skipping", deviceId);
734 return;
735 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200736 final boolean configComplete = withDeviceLock(
737 () -> isDeviceConfigComplete(event, deviceId), deviceId);
738 if (!configComplete) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200739 // Still waiting for some configuration.
Andrea Campanellabc112a92017-06-26 19:06:43 +0200740 return;
741 }
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200742 // Good to go.
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200743 triggerConnect(deviceId);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200744 cleanUpConfigInfo(deviceId);
Andrea Campanella14e196d2017-07-24 18:11:36 +0200745 }
746
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200747 private boolean isDeviceConfigComplete(NetworkConfigEvent event, DeviceId deviceId) {
748 // FIXME to be removed when netcfg will issue device events in a bundle or
Andrea Campanellabc112a92017-06-26 19:06:43 +0200749 // ensure all configuration needed is present
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200750 if (event.configClass().equals(GeneralProviderDeviceConfig.class)) {
751 //FIXME we currently assume that p4runtime devices are pipeline configurable.
752 //If we want to connect a p4runtime device with no pipeline
753 if (event.config().isPresent()) {
754 deviceConfigured.add(deviceId);
755 final boolean isNotPipelineConfigurable = Collections.disjoint(
756 ImmutableSet.copyOf(event.config().get().node().fieldNames()),
757 PIPELINE_CONFIGURABLE_PROTOCOLS);
758 if (isNotPipelineConfigurable) {
759 // Skip waiting for a pipeline if we can't support it.
Andrea Campanellabc112a92017-06-26 19:06:43 +0200760 pipelineConfigured.add(deviceId);
761 }
762 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200763 } else if (event.configClass().equals(BasicDeviceConfig.class)) {
764 if (event.config().isPresent() && event.config().get().node().has(DRIVER)) {
765 driverConfigured.add(deviceId);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200766 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200767 } else if (event.configClass().equals(PiPipeconfConfig.class)) {
768 if (event.config().isPresent()
769 && event.config().get().node().has(PiPipeconfConfig.PIPIPECONFID)) {
770 pipelineConfigured.add(deviceId);
771 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700772 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200773
774 if (deviceConfigured.contains(deviceId)
775 && driverConfigured.contains(deviceId)
776 && pipelineConfigured.contains(deviceId)) {
777 return true;
778 } else {
779 if (deviceConfigured.contains(deviceId) && driverConfigured.contains(deviceId)) {
780 log.debug("Waiting for pipeline configuration for device {}", deviceId);
781 } else if (pipelineConfigured.contains(deviceId) && driverConfigured.contains(deviceId)) {
782 log.debug("Waiting for device configuration for device {}", deviceId);
783 } else if (pipelineConfigured.contains(deviceId) && deviceConfigured.contains(deviceId)) {
784 log.debug("Waiting for driver configuration for device {}", deviceId);
785 } else if (driverConfigured.contains(deviceId)) {
786 log.debug("Only driver configuration for device {}", deviceId);
787 } else if (deviceConfigured.contains(deviceId)) {
788 log.debug("Only device configuration for device {}", deviceId);
789 }
790 }
791 return false;
Andrea Campanella241896c2017-05-10 13:11:04 -0700792 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700793 }
794
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700795 private boolean isPipelineReady(DeviceId deviceId) {
796 final boolean isPipelineProg = isPipelineProgrammable(deviceId);
797 final boolean isPipeconfReady = pipeconfWatchdogService
798 .getStatus(deviceId)
799 .equals(PiPipeconfWatchdogService.PipelineStatus.READY);
800 return !isPipelineProg || isPipeconfReady;
Andrea Campanella14e196d2017-07-24 18:11:36 +0200801 }
802
803 private void cleanUpConfigInfo(DeviceId deviceId) {
Andrea Campanellabc112a92017-06-26 19:06:43 +0200804 deviceConfigured.remove(deviceId);
805 driverConfigured.remove(deviceId);
806 pipelineConfigured.remove(deviceId);
Andrea Campanellabc112a92017-06-26 19:06:43 +0200807 }
808
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200809 private void startStatsPolling(DeviceId deviceId, boolean withRandomDelay) {
810 statsPollingTasks.compute(deviceId, (did, oldTask) -> {
811 if (oldTask != null) {
812 oldTask.cancel(false);
813 }
814 final int delay = withRandomDelay
815 ? new SecureRandom().nextInt(10) : 0;
816 return statsExecutor.scheduleAtFixedRate(
817 exceptionSafe(() -> updatePortStatistics(deviceId)),
818 delay, statsPollFrequency, TimeUnit.SECONDS);
819 });
Andrea Campanella19090322017-08-22 10:31:37 +0200820 }
821
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200822 private void cancelStatsPolling(DeviceId deviceId) {
823 statsPollingTasks.computeIfPresent(deviceId, (did, task) -> {
824 task.cancel(false);
825 return null;
826 });
827 }
828
829 private void rescheduleStatsPollingTasks() {
830 statsPollingTasks.keySet().forEach(deviceId -> {
831 // startStatsPolling cancels old one if present.
832 startStatsPolling(deviceId, true);
833 });
834 }
835
836 private void triggerProbeAllDevices() {
837 // Async trigger a task for all devices in the cfg.
838 cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700839 .forEach(this::triggerDeviceProbe);
Andrea Campanella1e573442018-05-17 17:07:13 +0200840 }
841
Carmelo Cascone92044522018-06-29 19:00:59 +0200842 private PiPipeconfId getPipeconfFromCfg(DeviceId deviceId) {
843 PiPipeconfConfig config = cfgService.getConfig(
844 deviceId, PiPipeconfConfig.class);
845 if (config == null) {
846 return null;
847 }
848 return config.piPipeconfId();
849 }
850
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700851 private void triggerDeviceProbe(DeviceId deviceId) {
852 connectionExecutor.execute(withDeviceLock(
853 () -> doDeviceProbe(deviceId), deviceId));
854 }
855
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200856 private void doDeviceProbe(DeviceId deviceId) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700857 log.debug("Probing device {}...", deviceId);
858 if (configIsMissing(deviceId)) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200859 return;
860 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700861 if (!isConnected(deviceId)) {
862 if (deviceService.isAvailable(deviceId)) {
863 providerService.deviceDisconnected(deviceId);
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200864 }
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200865 triggerConnect(deviceId);
Andrea Campanella1e573442018-05-17 17:07:13 +0200866 }
867 }
868
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700869 private boolean configIsMissing(DeviceId deviceId) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200870 final boolean present =
871 cfgService.getConfig(deviceId, GeneralProviderDeviceConfig.class) != null
872 && cfgService.getConfig(deviceId, BasicDeviceConfig.class) != null;
Andrea Campanella1e573442018-05-17 17:07:13 +0200873 if (!present) {
874 log.warn("Configuration for device {} is not complete", deviceId);
875 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700876 return !present;
Carmelo Casconee5b28722018-06-22 17:28:28 +0200877 }
878
879 private void handleMastershipResponse(DeviceId deviceId, MastershipRole response) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700880 // Notify core about mastership response.
881 final MastershipRole request = requestedRoles.get(deviceId);
882 final boolean isAvailable = deviceService.isAvailable(deviceId);
883 if (request == null || !isAvailable) {
Carmelo Casconee5b28722018-06-22 17:28:28 +0200884 return;
885 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700886 log.debug("Device {} asserted role {} (requested was {})",
887 deviceId, response, request);
888 providerService.receivedRoleReply(deviceId, request, response);
889 // FIXME: this should be based on assigned mastership, not what returned by device
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200890 if (response.equals(MastershipRole.MASTER)) {
891 startStatsPolling(deviceId, false);
892 } else {
893 cancelStatsPolling(deviceId);
Carmelo Casconee5b28722018-06-22 17:28:28 +0200894 }
895 }
896
Carmelo Casconede3b6842018-09-05 17:45:10 -0700897 private void handleNotMaster(DeviceId deviceId) {
898 log.warn("Device {} notified that this node is not master, " +
899 "relinquishing mastership...", deviceId);
900 mastershipService.relinquishMastership(deviceId);
901 }
902
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200903 private <U> U getFutureWithDeadline(CompletableFuture<U> future, String opDescription,
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200904 DeviceId deviceId, U defaultValue, int timeout) {
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200905 try {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200906 return future.get(timeout, TimeUnit.SECONDS);
Carmelo Cascone96beb6f2018-06-27 18:07:12 +0200907 } catch (InterruptedException e) {
908 log.error("Thread interrupted while {} on {}", opDescription, deviceId);
909 Thread.currentThread().interrupt();
910 } catch (ExecutionException e) {
911 log.error("Exception while {} on {}", opDescription, deviceId, e.getCause());
912 } catch (TimeoutException e) {
913 log.error("Operation TIMEOUT while {} on {}", opDescription, deviceId);
914 }
915 return defaultValue;
916 }
917
Andrea Campanella241896c2017-05-10 13:11:04 -0700918 /**
919 * Listener for core device events.
920 */
921 private class InternalDeviceListener implements DeviceListener {
922 @Override
923 public void event(DeviceEvent event) {
Andrea Campanellace111932017-09-18 16:59:56 +0900924 DeviceId deviceId = event.subject().id();
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700925 // For now this is scheduled periodically, when streaming API will
926 // be available we check and base it on the streaming API (e.g. gNMI)
927 if (mastershipService.isLocalMaster(deviceId)) {
Carmelo Cascone158b8c42018-07-04 19:42:37 +0200928 startStatsPolling(deviceId, true);
Andrea Campanella241896c2017-05-10 13:11:04 -0700929 }
930 }
931
932 @Override
933 public boolean isRelevant(DeviceEvent event) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700934 return event.type() == Type.DEVICE_ADDED &&
935 event.subject().id().toString().startsWith(URI_SCHEME.toLowerCase());
Andrea Campanella241896c2017-05-10 13:11:04 -0700936 }
937 }
Andrea Campanella1e573442018-05-17 17:07:13 +0200938
939 /**
Carmelo Casconee5b28722018-06-22 17:28:28 +0200940 * Listener for device agent events.
Andrea Campanella1e573442018-05-17 17:07:13 +0200941 */
Carmelo Casconee5b28722018-06-22 17:28:28 +0200942 private class InternalDeviceAgentListener implements DeviceAgentListener {
Andrea Campanella1e573442018-05-17 17:07:13 +0200943
944 @Override
Carmelo Casconee5b28722018-06-22 17:28:28 +0200945 public void event(DeviceAgentEvent event) {
Andrea Campanella1e573442018-05-17 17:07:13 +0200946 DeviceId deviceId = event.subject();
Carmelo Casconee5b28722018-06-22 17:28:28 +0200947 switch (event.type()) {
948 case CHANNEL_OPEN:
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700949 triggerAdvertiseDevice(deviceId);
Carmelo Casconee5b28722018-06-22 17:28:28 +0200950 break;
951 case CHANNEL_CLOSED:
Carmelo Casconee5b28722018-06-22 17:28:28 +0200952 case CHANNEL_ERROR:
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700953 triggerDeviceProbe(deviceId);
Carmelo Casconee5b28722018-06-22 17:28:28 +0200954 break;
955 case ROLE_MASTER:
956 handleMastershipResponse(deviceId, MastershipRole.MASTER);
957 break;
958 case ROLE_STANDBY:
959 handleMastershipResponse(deviceId, MastershipRole.STANDBY);
960 break;
961 case ROLE_NONE:
962 handleMastershipResponse(deviceId, MastershipRole.NONE);
963 break;
Carmelo Casconede3b6842018-09-05 17:45:10 -0700964 case NOT_MASTER:
965 handleNotMaster(deviceId);
966 break;
Carmelo Casconee5b28722018-06-22 17:28:28 +0200967 default:
968 log.warn("Unrecognized device agent event {}", event.type());
Andrea Campanella1e573442018-05-17 17:07:13 +0200969 }
Andrea Campanella1e573442018-05-17 17:07:13 +0200970 }
971
972 }
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700973
974 private class InternalPipeconfWatchdogListener implements PiPipeconfWatchdogListener {
975 @Override
976 public void event(PiPipeconfWatchdogEvent event) {
977 triggerMarkAvailable(event.subject());
978 }
979
980 @Override
981 public boolean isRelevant(PiPipeconfWatchdogEvent event) {
982 return event.type().equals(PiPipeconfWatchdogEvent.Type.PIPELINE_READY);
983 }
984 }
985
986 private class InternalConfigFactory
987 extends ConfigFactory<DeviceId, GeneralProviderDeviceConfig> {
988
989 InternalConfigFactory() {
990 super(SubjectFactories.DEVICE_SUBJECT_FACTORY,
991 GeneralProviderDeviceConfig.class, CFG_SCHEME);
992 }
993
994 @Override
995 public GeneralProviderDeviceConfig createConfig() {
996 return new GeneralProviderDeviceConfig();
997 }
998 }
Andrea Campanella241896c2017-05-10 13:11:04 -0700999}