blob: 103d6cf9c92f7e8907983aeb515407910a509e69 [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()) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700274 return false;
275 }
pierventrec44ccc72021-03-22 22:17:21 +0100276 if (Futures.getUnchecked(pipelineProg.isPipeconfSet(pipeconf)) &&
277 configuredDevices.contains(device.id())) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700278 log.debug("Pipeconf {} already configured on {}",
279 pipeconf.id(), device.id());
280 return true;
281 }
Carmelo Cascone95308282019-03-18 17:18:04 -0700282 return Futures.getUnchecked(pipelineProg.setPipeconf(pipeconf));
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700283 }
284
285 private Runnable withLock(Runnable task, Object object) {
286 return () -> {
287 final Lock lock = locks.get(object);
288 lock.lock();
289 try {
290 task.run();
291 } finally {
292 lock.unlock();
293 }
294 };
295 }
296
297 private void signalStatusUnknown(DeviceId deviceId) {
298 statusMap.remove(deviceId);
299 }
300
301 private void signalStatusReady(DeviceId deviceId) {
302 statusMap.put(deviceId, PipelineStatus.READY);
303 }
304
pierventrec44ccc72021-03-22 22:17:21 +0100305 private void signalStatusUnconfigured(DeviceId deviceId) {
306 configuredDevices.remove(deviceId);
307 }
308
309 private void signalStatusConfigured(DeviceId deviceId) {
310 configuredDevices.add(deviceId);
311 }
312
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700313 private boolean isLocalMaster(Device device) {
314 if (mastershipService.isLocalMaster(device.id())) {
315 return true;
316 }
317 // The device might have no master (e.g. after it has been disconnected
318 // from core), hence we use device mastership state.
319 final MastershipInfo info = mastershipService.getMastershipFor(device.id());
320 return !info.master().isPresent() &&
321 device.is(DeviceHandshaker.class) &&
322 device.as(DeviceHandshaker.class).getRole()
323 .equals(MastershipRole.MASTER);
324 }
325
326 private void startProbeTask() {
Carmelo Cascone95308282019-03-18 17:18:04 -0700327 synchronized (this) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700328 log.info("Starting pipeline probe thread with {} seconds interval...", probeInterval);
329 task = new InternalTimerTask();
330 timer.scheduleAtFixedRate(task, probeInterval * SECONDS,
331 probeInterval * SECONDS);
332 }
333 }
334
335
336 private void stopProbeTask() {
Carmelo Cascone95308282019-03-18 17:18:04 -0700337 synchronized (this) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700338 log.info("Stopping pipeline probe thread...");
339 task.cancel();
340 task = null;
341 }
342 }
343
344
345 private synchronized void rescheduleProbeTask() {
Carmelo Cascone95308282019-03-18 17:18:04 -0700346 synchronized (this) {
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700347 stopProbeTask();
348 startProbeTask();
349 }
350 }
351
352 private class InternalTimerTask extends TimerTask {
353 @Override
354 public void run() {
355 triggerCheckAllDevices();
356 }
357 }
358
359 /**
360 * Listener of device events used to update the pipeline status.
361 */
362 private class InternalDeviceListener implements DeviceListener {
363
364 @Override
365 public void event(DeviceEvent event) {
366 final Device device = event.subject();
367 switch (event.type()) {
368 case DEVICE_ADDED:
369 case DEVICE_UPDATED:
370 case DEVICE_AVAILABILITY_CHANGED:
371 if (!deviceService.isAvailable(device.id())) {
372 signalStatusUnknown(device.id());
Carmelo Cascone95308282019-03-18 17:18:04 -0700373 } else {
374 // The GeneralDeviceProvider marks online devices that
375 // have ANY pipeline config set. Here we make sure the
376 // one configured in the pipeconf service is the
377 // expected one. Clearly, it would be better to let the
378 // GDP do this check and avoid sending twice the same
379 // message to the switch.
380 filterAndTriggerTasks(singleton(device));
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700381 }
382 break;
383 case DEVICE_REMOVED:
384 case DEVICE_SUSPENDED:
385 signalStatusUnknown(device.id());
pierventrec44ccc72021-03-22 22:17:21 +0100386 signalStatusUnconfigured(device.id());
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700387 break;
388 case PORT_ADDED:
389 case PORT_UPDATED:
390 case PORT_REMOVED:
391 case PORT_STATS_UPDATED:
392 default:
393 break;
394 }
395 }
396 }
397
Carmelo Cascone75a9a892019-04-22 12:12:23 -0700398 private class InternalPipeconfListener implements PiPipeconfListener {
399 @Override
400 public void event(PiPipeconfEvent event) {
401 pipeconfMappingStore.getDevices(event.subject())
402 .forEach(PiPipeconfWatchdogManager.this::triggerProbe);
403 }
404
405 @Override
406 public boolean isRelevant(PiPipeconfEvent event) {
407 return Objects.equals(event.type(), PiPipeconfEvent.Type.REGISTERED);
408 }
409 }
410
Carmelo Cascone9e4972c2018-08-30 00:29:16 -0700411 private class StatusMapListener
412 implements EventuallyConsistentMapListener<DeviceId, PipelineStatus> {
413
414 @Override
415 public void event(EventuallyConsistentMapEvent<DeviceId, PipelineStatus> event) {
416 final DeviceId deviceId = event.key();
417 final PipelineStatus status = event.value();
418 switch (event.type()) {
419 case PUT:
420 postStatusEvent(deviceId, status);
421 break;
422 case REMOVE:
423 postStatusEvent(deviceId, PipelineStatus.UNKNOWN);
424 break;
425 default:
426 log.error("Unknown map event type {}", event.type());
427 }
428 }
429
430 private void postStatusEvent(DeviceId deviceId, PipelineStatus newStatus) {
431 PipelineStatus oldStatus = localStatusMap.put(deviceId, newStatus);
432 oldStatus = oldStatus == null ? PipelineStatus.UNKNOWN : oldStatus;
433 final PiPipeconfWatchdogEvent.Type eventType =
434 newStatus == PipelineStatus.READY
435 ? PiPipeconfWatchdogEvent.Type.PIPELINE_READY
436 : PiPipeconfWatchdogEvent.Type.PIPELINE_UNKNOWN;
437 if (newStatus != oldStatus) {
438 log.info("Pipeline status of {} is {}", deviceId, newStatus);
439 post(new PiPipeconfWatchdogEvent(eventType, deviceId));
440 }
441 }
442 }
443}