blob: 6dea30ee5f120d7d50d09c8337d66d93433225be [file] [log] [blame]
Carmelo Cascone9e4972c2018-08-30 00:29:16 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
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.net.pi.impl;
18
19import com.google.common.collect.Maps;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080020import com.google.common.util.concurrent.Futures;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070021import com.google.common.util.concurrent.Striped;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070022import org.onlab.util.KryoNamespace;
23import org.onlab.util.Tools;
24import org.onosproject.cfg.ComponentConfigService;
25import org.onosproject.event.AbstractListenerManager;
26import org.onosproject.mastership.MastershipInfo;
27import org.onosproject.mastership.MastershipService;
28import org.onosproject.net.Device;
29import org.onosproject.net.DeviceId;
30import org.onosproject.net.MastershipRole;
31import org.onosproject.net.behaviour.PiPipelineProgrammable;
32import org.onosproject.net.device.DeviceEvent;
33import org.onosproject.net.device.DeviceHandshaker;
34import org.onosproject.net.device.DeviceListener;
35import org.onosproject.net.device.DeviceService;
36import org.onosproject.net.pi.model.PiPipeconf;
37import org.onosproject.net.pi.model.PiPipeconfId;
Carmelo Cascone75a9a892019-04-22 12:12:23 -070038import org.onosproject.net.pi.service.PiPipeconfEvent;
39import org.onosproject.net.pi.service.PiPipeconfListener;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070040import org.onosproject.net.pi.service.PiPipeconfMappingStore;
41import org.onosproject.net.pi.service.PiPipeconfService;
42import org.onosproject.net.pi.service.PiPipeconfWatchdogEvent;
43import org.onosproject.net.pi.service.PiPipeconfWatchdogListener;
44import org.onosproject.net.pi.service.PiPipeconfWatchdogService;
pierventrec44ccc72021-03-22 22:17:21 +010045import org.onosproject.store.primitives.DefaultDistributedSet;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070046import org.onosproject.store.serializers.KryoNamespaces;
pierventrec44ccc72021-03-22 22:17:21 +010047import org.onosproject.store.service.DistributedPrimitive;
48import org.onosproject.store.service.DistributedSet;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070049import org.onosproject.store.service.EventuallyConsistentMap;
50import org.onosproject.store.service.EventuallyConsistentMapEvent;
51import org.onosproject.store.service.EventuallyConsistentMapListener;
pierventrec44ccc72021-03-22 22:17:21 +010052import org.onosproject.store.service.Serializer;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070053import org.onosproject.store.service.StorageService;
54import org.onosproject.store.service.WallClockTimestamp;
55import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070056import org.osgi.service.component.annotations.Activate;
57import org.osgi.service.component.annotations.Component;
58import org.osgi.service.component.annotations.Deactivate;
59import org.osgi.service.component.annotations.Modified;
60import org.osgi.service.component.annotations.Reference;
61import org.osgi.service.component.annotations.ReferenceCardinality;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070062import org.slf4j.Logger;
63
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070064import java.util.Dictionary;
65import java.util.Map;
Carmelo Cascone75a9a892019-04-22 12:12:23 -070066import java.util.Objects;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070067import java.util.Timer;
68import java.util.TimerTask;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070069import java.util.concurrent.ExecutorService;
70import java.util.concurrent.Executors;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070071import java.util.concurrent.locks.Lock;
72
Carmelo Cascone95308282019-03-18 17:18:04 -070073import static java.util.Collections.singleton;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070074import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070075import static org.onosproject.net.OsgiPropertyConstants.PWM_PROBE_INTERVAL;
76import static org.onosproject.net.OsgiPropertyConstants.PWM_PROBE_INTERVAL_DEFAULT;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070077import static org.slf4j.LoggerFactory.getLogger;
78
79/**
80 * Implementation of PiPipeconfWatchdogService that implements a periodic
81 * pipeline probe task and listens for device events to update the status of the
82 * pipeline.
83 */
Ray Milkeyd04e2272018-10-16 18:20:18 -070084@Component(
Carmelo Cascone75a9a892019-04-22 12:12:23 -070085 immediate = true,
86 service = PiPipeconfWatchdogService.class,
87 property = {
88 PWM_PROBE_INTERVAL + ":Integer=" + PWM_PROBE_INTERVAL_DEFAULT
89 }
Ray Milkeyd04e2272018-10-16 18:20:18 -070090)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070091public class PiPipeconfWatchdogManager
92 extends AbstractListenerManager<PiPipeconfWatchdogEvent, PiPipeconfWatchdogListener>
93 implements PiPipeconfWatchdogService {
94
95 private final Logger log = getLogger(getClass());
96
97 private static final long SECONDS = 1000L;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -070098
Ray Milkeyd84f89b2018-08-17 14:54:17 -070099 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700100 private PiPipeconfMappingStore pipeconfMappingStore;
101
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700102 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700103 private DeviceService deviceService;
104
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700105 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700106 private MastershipService mastershipService;
107
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700108 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700109 protected PiPipeconfService pipeconfService;
110
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700111 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700112 protected StorageService storageService;
113
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700114 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700115 private ComponentConfigService componentConfigService;
116
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700117 /**
118 * Configure interval in seconds for device pipeconf probing.
119 */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700120 private int probeInterval = PWM_PROBE_INTERVAL_DEFAULT;
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700121
122 protected ExecutorService executor = Executors.newFixedThreadPool(
123 30, groupedThreads("onos/pipeconf-watchdog", "%d", log));
124
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700125 private final DeviceListener deviceListener = new InternalDeviceListener();
126 private final PiPipeconfListener pipeconfListener = new InternalPipeconfListener();
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700127
128 private Timer timer;
129 private TimerTask task;
130
131 private final Striped<Lock> locks = Striped.lock(30);
132
133 private EventuallyConsistentMap<DeviceId, PipelineStatus> statusMap;
134 private Map<DeviceId, PipelineStatus> localStatusMap;
135
pierventrec44ccc72021-03-22 22:17:21 +0100136 // Configured devices by this cluster. We use a set to keep track of all devices for which
137 // we have pushed the forwarding pipeline config at least once. This guarantees that device
138 // pipelines are wiped out/reset at least once when starting the cluster, minimizing the risk
139 // of any stale state from previous runs affecting control operations. Another effect of this
140 // approach is that the default entries mirror will get populated even though the pipeline results
141 // to be the same across different ONOS installations.
142 private static final String CONFIGURED_DEVICES = "onos-pipeconf-configured-set";
143 private DistributedSet<DeviceId> configuredDevices;
144
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700145 @Activate
146 public void activate() {
147 eventDispatcher.addSink(PiPipeconfWatchdogEvent.class, listenerRegistry);
148 localStatusMap = Maps.newConcurrentMap();
pierventrec44ccc72021-03-22 22:17:21 +0100149 // Init distributed status map and configured devices set
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700150 KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
151 .register(KryoNamespaces.API)
152 .register(PipelineStatus.class);
153 statusMap = storageService.<DeviceId, PipelineStatus>eventuallyConsistentMapBuilder()
154 .withName("onos-pipeconf-status-table")
155 .withSerializer(serializer)
156 .withTimestampProvider((k, v) -> new WallClockTimestamp()).build();
157 statusMap.addListener(new StatusMapListener());
pierventrec44ccc72021-03-22 22:17:21 +0100158 // Init the set of the configured devices
159 configuredDevices = new DefaultDistributedSet<>(storageService.<DeviceId>setBuilder()
160 .withName(CONFIGURED_DEVICES)
161 .withSerializer(Serializer.using(KryoNamespaces.API))
162 .build(),
163 DistributedPrimitive.DEFAULT_OPERATION_TIMEOUT_MILLIS);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700164 // Register component configurable properties.
165 componentConfigService.registerProperties(getClass());
166 // Start periodic watchdog task.
167 timer = new Timer();
168 startProbeTask();
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700169 // Add listeners.
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700170 deviceService.addListener(deviceListener);
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700171 pipeconfService.addListener(pipeconfListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700172 log.info("Started");
173 }
174
175 @Modified
176 public void modified(ComponentContext context) {
177 if (context == null) {
178 return;
179 }
180
181 Dictionary<?, ?> properties = context.getProperties();
182 final int oldProbeInterval = probeInterval;
183 probeInterval = Tools.getIntegerProperty(
Ray Milkeyd04e2272018-10-16 18:20:18 -0700184 properties, PWM_PROBE_INTERVAL, PWM_PROBE_INTERVAL_DEFAULT);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700185 log.info("Configured. {} is configured to {} seconds",
Ray Milkeyd04e2272018-10-16 18:20:18 -0700186 PWM_PROBE_INTERVAL_DEFAULT, probeInterval);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700187
188 if (oldProbeInterval != probeInterval) {
189 rescheduleProbeTask();
190 }
191 }
192
193 @Deactivate
194 public void deactivate() {
195 eventDispatcher.removeSink(PiPipeconfWatchdogEvent.class);
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700196 pipeconfService.removeListener(pipeconfListener);
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700197 deviceService.removeListener(deviceListener);
198 stopProbeTask();
199 timer = null;
200 statusMap = null;
201 localStatusMap = null;
202 log.info("Stopped");
203 }
204
205 @Override
206 public void triggerProbe(DeviceId deviceId) {
207 final Device device = deviceService.getDevice(deviceId);
208 if (device != null) {
Carmelo Cascone95308282019-03-18 17:18:04 -0700209 filterAndTriggerTasks(singleton(device));
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700210 }
211 }
212
213 @Override
214 public PipelineStatus getStatus(DeviceId deviceId) {
215 final PipelineStatus status = statusMap.get(deviceId);
216 return status == null ? PipelineStatus.UNKNOWN : status;
217 }
218
219 private void triggerCheckAllDevices() {
220 filterAndTriggerTasks(deviceService.getDevices());
221 }
222
223 private void filterAndTriggerTasks(Iterable<Device> devices) {
224 devices.forEach(device -> {
225 if (!isLocalMaster(device)) {
226 return;
227 }
228
229 final PiPipeconfId pipeconfId = pipeconfMappingStore.getPipeconfId(device.id());
Carmelo Cascone95308282019-03-18 17:18:04 -0700230 if (pipeconfId == null || !device.is(PiPipelineProgrammable.class)) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700231 return;
232 }
233
234 if (!pipeconfService.getPipeconf(pipeconfId).isPresent()) {
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700235 log.warn("Pipeconf {} is not registered, skipping probe for {}",
236 pipeconfId, device.id());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700237 return;
238 }
239
240 final PiPipeconf pipeconf = pipeconfService.getPipeconf(pipeconfId).get();
241
242 if (!device.is(DeviceHandshaker.class)) {
243 log.error("Missing DeviceHandshaker behavior for {}", device.id());
244 return;
245 }
246
247 // Trigger task with per-device lock.
248 executor.execute(withLock(() -> {
249 final boolean success = doSetPipeconfIfRequired(device, pipeconf);
250 if (success) {
251 signalStatusReady(device.id());
pierventrec44ccc72021-03-22 22:17:21 +0100252 signalStatusConfigured(device.id());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700253 } else {
254 signalStatusUnknown(device.id());
255 }
256 }, device.id()));
257 });
258 }
259
260 /**
261 * Returns true if the given device is known to be configured with the given
262 * pipeline, false otherwise. If necessary, this method enforces setting the
263 * given pipeconf using drivers.
264 *
265 * @param device device
266 * @param pipeconf pipeconf
267 * @return boolean
268 */
269 private boolean doSetPipeconfIfRequired(Device device, PiPipeconf pipeconf) {
270 log.debug("Starting watchdog task for {} ({})", device.id(), pipeconf.id());
271 final PiPipelineProgrammable pipelineProg = device.as(PiPipelineProgrammable.class);
272 final DeviceHandshaker handshaker = device.as(DeviceHandshaker.class);
Carmelo Casconec2be50a2019-04-10 00:15:39 -0700273 if (!handshaker.hasConnection()) {
pierventref92de512021-05-18 18:06:40 +0200274 log.warn("There is no connectivity with {}", device.id());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700275 return false;
276 }
pierventrec44ccc72021-03-22 22:17:21 +0100277 if (Futures.getUnchecked(pipelineProg.isPipeconfSet(pipeconf)) &&
278 configuredDevices.contains(device.id())) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700279 log.debug("Pipeconf {} already configured on {}",
280 pipeconf.id(), device.id());
281 return true;
282 }
Carmelo Cascone95308282019-03-18 17:18:04 -0700283 return Futures.getUnchecked(pipelineProg.setPipeconf(pipeconf));
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700284 }
285
286 private Runnable withLock(Runnable task, Object object) {
287 return () -> {
288 final Lock lock = locks.get(object);
289 lock.lock();
290 try {
291 task.run();
292 } finally {
293 lock.unlock();
294 }
295 };
296 }
297
298 private void signalStatusUnknown(DeviceId deviceId) {
299 statusMap.remove(deviceId);
300 }
301
302 private void signalStatusReady(DeviceId deviceId) {
303 statusMap.put(deviceId, PipelineStatus.READY);
304 }
305
pierventrec44ccc72021-03-22 22:17:21 +0100306 private void signalStatusUnconfigured(DeviceId deviceId) {
307 configuredDevices.remove(deviceId);
308 }
309
310 private void signalStatusConfigured(DeviceId deviceId) {
311 configuredDevices.add(deviceId);
312 }
313
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700314 private boolean isLocalMaster(Device device) {
315 if (mastershipService.isLocalMaster(device.id())) {
316 return true;
317 }
318 // The device might have no master (e.g. after it has been disconnected
319 // from core), hence we use device mastership state.
320 final MastershipInfo info = mastershipService.getMastershipFor(device.id());
321 return !info.master().isPresent() &&
322 device.is(DeviceHandshaker.class) &&
323 device.as(DeviceHandshaker.class).getRole()
324 .equals(MastershipRole.MASTER);
325 }
326
327 private void startProbeTask() {
Carmelo Cascone95308282019-03-18 17:18:04 -0700328 synchronized (this) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700329 log.info("Starting pipeline probe thread with {} seconds interval...", probeInterval);
330 task = new InternalTimerTask();
331 timer.scheduleAtFixedRate(task, probeInterval * SECONDS,
332 probeInterval * SECONDS);
333 }
334 }
335
336
337 private void stopProbeTask() {
Carmelo Cascone95308282019-03-18 17:18:04 -0700338 synchronized (this) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700339 log.info("Stopping pipeline probe thread...");
340 task.cancel();
341 task = null;
342 }
343 }
344
345
346 private synchronized void rescheduleProbeTask() {
Carmelo Cascone95308282019-03-18 17:18:04 -0700347 synchronized (this) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700348 stopProbeTask();
349 startProbeTask();
350 }
351 }
352
353 private class InternalTimerTask extends TimerTask {
354 @Override
355 public void run() {
356 triggerCheckAllDevices();
357 }
358 }
359
360 /**
361 * Listener of device events used to update the pipeline status.
362 */
363 private class InternalDeviceListener implements DeviceListener {
364
365 @Override
366 public void event(DeviceEvent event) {
367 final Device device = event.subject();
368 switch (event.type()) {
369 case DEVICE_ADDED:
370 case DEVICE_UPDATED:
371 case DEVICE_AVAILABILITY_CHANGED:
372 if (!deviceService.isAvailable(device.id())) {
373 signalStatusUnknown(device.id());
Carmelo Cascone95308282019-03-18 17:18:04 -0700374 } else {
375 // The GeneralDeviceProvider marks online devices that
376 // have ANY pipeline config set. Here we make sure the
377 // one configured in the pipeconf service is the
378 // expected one. Clearly, it would be better to let the
379 // GDP do this check and avoid sending twice the same
380 // message to the switch.
381 filterAndTriggerTasks(singleton(device));
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700382 }
383 break;
384 case DEVICE_REMOVED:
385 case DEVICE_SUSPENDED:
386 signalStatusUnknown(device.id());
pierventrec44ccc72021-03-22 22:17:21 +0100387 signalStatusUnconfigured(device.id());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700388 break;
389 case PORT_ADDED:
390 case PORT_UPDATED:
391 case PORT_REMOVED:
392 case PORT_STATS_UPDATED:
393 default:
394 break;
395 }
396 }
397 }
398
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700399 private class InternalPipeconfListener implements PiPipeconfListener {
400 @Override
401 public void event(PiPipeconfEvent event) {
402 pipeconfMappingStore.getDevices(event.subject())
403 .forEach(PiPipeconfWatchdogManager.this::triggerProbe);
404 }
405
406 @Override
407 public boolean isRelevant(PiPipeconfEvent event) {
408 return Objects.equals(event.type(), PiPipeconfEvent.Type.REGISTERED);
409 }
410 }
411
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700412 private class StatusMapListener
413 implements EventuallyConsistentMapListener<DeviceId, PipelineStatus> {
414
415 @Override
416 public void event(EventuallyConsistentMapEvent<DeviceId, PipelineStatus> event) {
417 final DeviceId deviceId = event.key();
418 final PipelineStatus status = event.value();
419 switch (event.type()) {
420 case PUT:
421 postStatusEvent(deviceId, status);
422 break;
423 case REMOVE:
424 postStatusEvent(deviceId, PipelineStatus.UNKNOWN);
425 break;
426 default:
427 log.error("Unknown map event type {}", event.type());
428 }
429 }
430
431 private void postStatusEvent(DeviceId deviceId, PipelineStatus newStatus) {
432 PipelineStatus oldStatus = localStatusMap.put(deviceId, newStatus);
433 oldStatus = oldStatus == null ? PipelineStatus.UNKNOWN : oldStatus;
434 final PiPipeconfWatchdogEvent.Type eventType =
435 newStatus == PipelineStatus.READY
436 ? PiPipeconfWatchdogEvent.Type.PIPELINE_READY
437 : PiPipeconfWatchdogEvent.Type.PIPELINE_UNKNOWN;
438 if (newStatus != oldStatus) {
439 log.info("Pipeline status of {} is {}", deviceId, newStatus);
440 post(new PiPipeconfWatchdogEvent(eventType, deviceId));
441 }
442 }
443 }
444}