blob: 2368f254a432f1d1053cf37c8f2967b9a399b124 [file] [log] [blame]
alshabib77b88482015-04-07 15:47:50 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
alshabib77b88482015-04-07 15:47:50 -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 */
16package org.onosproject.net.flowobjective.impl;
17
Pier Luigi97893112018-03-05 11:09:42 +010018import com.google.common.collect.ImmutableSet;
Saurav Dasf14d9ef2017-12-05 15:00:23 -080019import com.google.common.collect.Lists;
alshabib77b88482015-04-07 15:47:50 -070020import com.google.common.collect.Maps;
Thomas Vachuskad27097c2016-06-14 19:10:41 -070021import com.google.common.collect.Sets;
alshabib77b88482015-04-07 15:47:50 -070022import org.onlab.osgi.DefaultServiceDirectory;
23import org.onlab.osgi.ServiceDirectory;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070024import org.onlab.util.ItemNotFoundException;
Yi Tseng374c5f32017-03-05 22:51:35 -080025import org.onlab.util.Tools;
26import org.onosproject.cfg.ComponentConfigService;
alshabib77b88482015-04-07 15:47:50 -070027import org.onosproject.cluster.ClusterService;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070028import org.onosproject.net.Device;
alshabib77b88482015-04-07 15:47:50 -070029import org.onosproject.net.DeviceId;
Saurav Das24431192016-03-07 19:13:00 -080030import org.onosproject.net.behaviour.NextGroup;
alshabib77b88482015-04-07 15:47:50 -070031import org.onosproject.net.behaviour.Pipeliner;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070032import org.onosproject.net.behaviour.PipelinerContext;
alshabibaebe7752015-04-07 17:45:42 -070033import org.onosproject.net.device.DeviceEvent;
34import org.onosproject.net.device.DeviceListener;
alshabib77b88482015-04-07 15:47:50 -070035import org.onosproject.net.device.DeviceService;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070036import org.onosproject.net.driver.DriverEvent;
alshabib77b88482015-04-07 15:47:50 -070037import org.onosproject.net.driver.DriverHandler;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070038import org.onosproject.net.driver.DriverListener;
alshabib77b88482015-04-07 15:47:50 -070039import org.onosproject.net.driver.DriverService;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070040import org.onosproject.net.flow.FlowRuleService;
alshabib77b88482015-04-07 15:47:50 -070041import org.onosproject.net.flowobjective.FilteringObjective;
42import org.onosproject.net.flowobjective.FlowObjectiveService;
alshabib2a441c62015-04-13 18:39:38 -070043import org.onosproject.net.flowobjective.FlowObjectiveStore;
44import org.onosproject.net.flowobjective.FlowObjectiveStoreDelegate;
alshabib77b88482015-04-07 15:47:50 -070045import org.onosproject.net.flowobjective.ForwardingObjective;
46import org.onosproject.net.flowobjective.NextObjective;
alshabib910aff12015-04-09 16:55:57 -070047import org.onosproject.net.flowobjective.Objective;
Saurav Das1547b3f2017-05-05 17:01:08 -070048import org.onosproject.net.flowobjective.Objective.Operation;
Jonathan Hart17d00452015-04-21 17:10:00 -070049import org.onosproject.net.flowobjective.ObjectiveError;
alshabib2a441c62015-04-13 18:39:38 -070050import org.onosproject.net.flowobjective.ObjectiveEvent;
Saurav Das423fe2b2015-12-04 10:52:59 -080051import org.onosproject.net.flowobjective.ObjectiveEvent.Type;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070052import org.onosproject.net.group.GroupService;
Yi Tseng374c5f32017-03-05 22:51:35 -080053import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070054import org.osgi.service.component.annotations.Activate;
55import org.osgi.service.component.annotations.Component;
56import org.osgi.service.component.annotations.Deactivate;
57import org.osgi.service.component.annotations.Modified;
58import org.osgi.service.component.annotations.Reference;
59import org.osgi.service.component.annotations.ReferenceCardinality;
alshabib77b88482015-04-07 15:47:50 -070060import org.slf4j.Logger;
61import org.slf4j.LoggerFactory;
62
Saurav Das24431192016-03-07 19:13:00 -080063import java.util.ArrayList;
Saurav Das24431192016-03-07 19:13:00 -080064import java.util.List;
alshabib77b88482015-04-07 15:47:50 -070065import java.util.Map;
Saurav Das8a0732e2015-11-20 15:27:53 -080066import java.util.Objects;
alshabib2a441c62015-04-13 18:39:38 -070067import java.util.Set;
Jonathan Hart17d00452015-04-21 17:10:00 -070068import java.util.concurrent.ExecutorService;
alshabib77b88482015-04-07 15:47:50 -070069
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -070070import static com.google.common.base.Preconditions.checkNotNull;
Yi Tseng374c5f32017-03-05 22:51:35 -080071import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuska866b46a2015-04-30 00:26:55 -070072import static java.util.concurrent.Executors.newFixedThreadPool;
Ruchi Sahotae4934e12019-03-01 16:56:07 +000073import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Jonathan Hart17d00452015-04-21 17:10:00 -070074import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070075import static org.onosproject.net.AnnotationKeys.DRIVER;
Ray Milkeyd04e2272018-10-16 18:20:18 -070076import static org.onosproject.net.OsgiPropertyConstants.FOM_NUM_THREADS;
77import static org.onosproject.net.OsgiPropertyConstants.FOM_NUM_THREADS_DEFAULT;
Changhoon Yoon541ef712015-05-23 17:18:34 +090078import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskad27097c2016-06-14 19:10:41 -070079import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
alshabib77b88482015-04-07 15:47:50 -070080
81/**
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070082 * Provides implementation of the flow objective programming service.
alshabib77b88482015-04-07 15:47:50 -070083 */
Ray Milkeyd04e2272018-10-16 18:20:18 -070084@Component(
85 enabled = false,
86 service = FlowObjectiveService.class,
87 property = {
Ray Milkey2d7bca12018-10-17 14:51:52 -070088 FOM_NUM_THREADS + ":Integer=" + FOM_NUM_THREADS_DEFAULT
Ray Milkeyd04e2272018-10-16 18:20:18 -070089 }
90)
alshabib77b88482015-04-07 15:47:50 -070091public class FlowObjectiveManager implements FlowObjectiveService {
92
Charles Chana7903c82018-03-15 20:14:16 -070093 private static final int INSTALL_RETRY_ATTEMPTS = 5;
94 private static final long INSTALL_RETRY_INTERVAL = 1000; // ms
alshabib77b88482015-04-07 15:47:50 -070095
Yi Tseng374c5f32017-03-05 22:51:35 -080096 private static final String WORKER_PATTERN = "objective-installer-%d";
97 private static final String GROUP_THREAD_NAME = "onos/objective-installer";
Yi Tseng374c5f32017-03-05 22:51:35 -080098
Jonathan Hart17d00452015-04-21 17:10:00 -070099 private final Logger log = LoggerFactory.getLogger(getClass());
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700100
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700101 /** Number of worker threads. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700102 private int numThreads = FOM_NUM_THREADS_DEFAULT;
Yi Tseng374c5f32017-03-05 22:51:35 -0800103
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700104 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib77b88482015-04-07 15:47:50 -0700105 protected DriverService driverService;
106
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700107 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib77b88482015-04-07 15:47:50 -0700108 protected DeviceService deviceService;
109
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700110 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib77b88482015-04-07 15:47:50 -0700111 protected ClusterService clusterService;
112
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700113 // Note: The following dependencies are added on behalf of the pipeline
114 // driver behaviours to assure these services are available for their
115 // initialization.
Charles Chana7903c82018-03-15 20:14:16 -0700116 @SuppressWarnings("unused")
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700117 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700118 protected FlowRuleService flowRuleService;
119
Charles Chana7903c82018-03-15 20:14:16 -0700120 @SuppressWarnings("unused")
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700121 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700122 protected GroupService groupService;
123
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700124 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib2a441c62015-04-13 18:39:38 -0700125 protected FlowObjectiveStore flowObjectiveStore;
126
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700127 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng374c5f32017-03-05 22:51:35 -0800128 protected ComponentConfigService cfgService;
129
Charles Chana7903c82018-03-15 20:14:16 -0700130 final FlowObjectiveStoreDelegate delegate = new InternalStoreDelegate();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700131
132 private final Map<DeviceId, DriverHandler> driverHandlers = Maps.newConcurrentMap();
Charles Chana7903c82018-03-15 20:14:16 -0700133 protected final Map<DeviceId, Pipeliner> pipeliners = Maps.newConcurrentMap();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700134
135 private final PipelinerContext context = new InnerPipelineContext();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700136 private final DeviceListener deviceListener = new InnerDeviceListener();
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700137 private final DriverListener driverListener = new InnerDriverListener();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700138
Charles Chana7903c82018-03-15 20:14:16 -0700139 private ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
alshabib910aff12015-04-09 16:55:57 -0700140
Saurav Das1547b3f2017-05-05 17:01:08 -0700141 // local stores for queuing fwd and next objectives that are waiting for an
142 // associated next objective execution to complete. The signal for completed
143 // execution comes from a pipeline driver, in this or another controller
144 // instance, via the DistributedFlowObjectiveStore.
Charles Chana7903c82018-03-15 20:14:16 -0700145 // TODO Making these cache and timeout the entries
146 final Map<Integer, Set<PendingFlowObjective>> pendingForwards = Maps.newConcurrentMap();
147 final Map<Integer, List<PendingFlowObjective>> pendingNexts = Maps.newConcurrentMap();
alshabib2a441c62015-04-13 18:39:38 -0700148
Saurav Das24431192016-03-07 19:13:00 -0800149 // local store to track which nextObjectives were sent to which device
150 // for debugging purposes
151 private Map<Integer, DeviceId> nextToDevice = Maps.newConcurrentMap();
152
Charles Chana7903c82018-03-15 20:14:16 -0700153 ExecutorService executorService;
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000154 protected ExecutorService devEventExecutor;
alshabib2a441c62015-04-13 18:39:38 -0700155
alshabib77b88482015-04-07 15:47:50 -0700156 @Activate
157 protected void activate() {
Ray Milkey1f0764a2019-03-01 08:40:37 -0800158 cfgService.registerProperties(FlowObjectiveManager.class);
Yi Tseng374c5f32017-03-05 22:51:35 -0800159 executorService = newFixedThreadPool(numThreads,
160 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000161 devEventExecutor = newSingleThreadScheduledExecutor(
162 groupedThreads("onos/flowobj-dev-events", "events-%d", log));
alshabib2a441c62015-04-13 18:39:38 -0700163 flowObjectiveStore.setDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700164 deviceService.addListener(deviceListener);
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700165 driverService.addListener(driverListener);
alshabib77b88482015-04-07 15:47:50 -0700166 log.info("Started");
167 }
168
169 @Deactivate
170 protected void deactivate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800171 cfgService.unregisterProperties(getClass(), false);
alshabib2a441c62015-04-13 18:39:38 -0700172 flowObjectiveStore.unsetDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700173 deviceService.removeListener(deviceListener);
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700174 driverService.removeListener(driverListener);
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700175 executorService.shutdown();
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000176 devEventExecutor.shutdownNow();
177 devEventExecutor = null;
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700178 pipeliners.clear();
179 driverHandlers.clear();
Saurav Das24431192016-03-07 19:13:00 -0800180 nextToDevice.clear();
alshabib77b88482015-04-07 15:47:50 -0700181 log.info("Stopped");
182 }
183
Yi Tseng374c5f32017-03-05 22:51:35 -0800184 @Modified
185 protected void modified(ComponentContext context) {
186 String propertyValue =
Ray Milkey1f0764a2019-03-01 08:40:37 -0800187 Tools.get(context.getProperties(), FOM_NUM_THREADS);
Yi Tseng374c5f32017-03-05 22:51:35 -0800188 int newNumThreads = isNullOrEmpty(propertyValue) ? numThreads : Integer.parseInt(propertyValue);
189
190 if (newNumThreads != numThreads && newNumThreads > 0) {
191 numThreads = newNumThreads;
192 ExecutorService oldWorkerExecutor = executorService;
193 executorService = newFixedThreadPool(numThreads,
194 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
195 if (oldWorkerExecutor != null) {
196 oldWorkerExecutor.shutdown();
197 }
198 log.info("Reconfigured number of worker threads to {}", numThreads);
199 }
200 }
201
Jonathan Hart17d00452015-04-21 17:10:00 -0700202 /**
203 * Task that passes the flow objective down to the driver. The task will
204 * make a few attempts to find the appropriate driver, then eventually give
205 * up and report an error if no suitable driver could be found.
206 */
Charles Chana7903c82018-03-15 20:14:16 -0700207 class ObjectiveInstaller implements Runnable {
208 final DeviceId deviceId;
209 final Objective objective;
Jonathan Hart17d00452015-04-21 17:10:00 -0700210
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700211 private final int numAttempts;
Jonathan Hart17d00452015-04-21 17:10:00 -0700212
Charles Chana7903c82018-03-15 20:14:16 -0700213 ObjectiveInstaller(DeviceId deviceId, Objective objective) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700214 this(deviceId, objective, 1);
215 }
216
Charles Chana7903c82018-03-15 20:14:16 -0700217 ObjectiveInstaller(DeviceId deviceId, Objective objective, int attemps) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700218 this.deviceId = checkNotNull(deviceId);
219 this.objective = checkNotNull(objective);
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800220 this.numAttempts = attemps;
alshabib910aff12015-04-09 16:55:57 -0700221 }
alshabib77b88482015-04-07 15:47:50 -0700222
Jonathan Hart17d00452015-04-21 17:10:00 -0700223 @Override
224 public void run() {
225 try {
Jonathan Hart17d00452015-04-21 17:10:00 -0700226 Pipeliner pipeliner = getDevicePipeliner(deviceId);
227
228 if (pipeliner != null) {
229 if (objective instanceof NextObjective) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700230 nextToDevice.put(objective.id(), deviceId);
Jonathan Hart17d00452015-04-21 17:10:00 -0700231 pipeliner.next((NextObjective) objective);
232 } else if (objective instanceof ForwardingObjective) {
233 pipeliner.forward((ForwardingObjective) objective);
234 } else {
235 pipeliner.filter((FilteringObjective) objective);
236 }
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800237 //Attempts to check if pipeliner is null for retry attempts
Jonathan Hart17d00452015-04-21 17:10:00 -0700238 } else if (numAttempts < INSTALL_RETRY_ATTEMPTS) {
Saurav Das3d038262015-04-23 12:36:58 -0700239 Thread.sleep(INSTALL_RETRY_INTERVAL);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700240 executorService.execute(new ObjectiveInstaller(deviceId, objective, numAttempts + 1));
Jonathan Hart17d00452015-04-21 17:10:00 -0700241 } else {
242 // Otherwise we've tried a few times and failed, report an
243 // error back to the user.
244 objective.context().ifPresent(
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800245 c -> c.onError(objective, ObjectiveError.NOPIPELINER));
Jonathan Hart17d00452015-04-21 17:10:00 -0700246 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700247 //Exception thrown
Jonathan Hart17d00452015-04-21 17:10:00 -0700248 } catch (Exception e) {
249 log.warn("Exception while installing flow objective", e);
250 }
251 }
252 }
253
254 @Override
255 public void filter(DeviceId deviceId, FilteringObjective filteringObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900256 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700257 executorService.execute(new ObjectiveInstaller(deviceId, filteringObjective));
alshabib77b88482015-04-07 15:47:50 -0700258 }
259
260 @Override
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700261 public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900262 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700263 if (forwardingObjective.nextId() == null ||
Yi Tseng1666b502017-05-17 11:05:18 -0700264 flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null ||
265 !queueFwdObjective(deviceId, forwardingObjective)) {
266 // fast path
267 executorService.execute(new ObjectiveInstaller(deviceId, forwardingObjective));
alshabib910aff12015-04-09 16:55:57 -0700268 }
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700269 }
270
alshabib2a441c62015-04-13 18:39:38 -0700271 @Override
Jonathan Hart17d00452015-04-21 17:10:00 -0700272 public void next(DeviceId deviceId, NextObjective nextObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900273 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700274 if (nextObjective.op() == Operation.ADD ||
Charles Chanb71e1ba2018-08-16 21:02:34 -0700275 nextObjective.op() == Operation.VERIFY ||
Yi Tseng1666b502017-05-17 11:05:18 -0700276 flowObjectiveStore.getNextGroup(nextObjective.id()) != null ||
277 !queueNextObjective(deviceId, nextObjective)) {
278 // either group exists or we are trying to create it - let it through
279 executorService.execute(new ObjectiveInstaller(deviceId, nextObjective));
Saurav Das1547b3f2017-05-05 17:01:08 -0700280 }
alshabib2a441c62015-04-13 18:39:38 -0700281 }
282
alshabibf6ea9e62015-04-21 17:08:26 -0700283 @Override
284 public int allocateNextId() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900285 checkPermission(FLOWRULE_WRITE);
alshabibf6ea9e62015-04-21 17:08:26 -0700286 return flowObjectiveStore.allocateNextId();
287 }
288
Xin Jin313708b2015-07-09 13:43:04 -0700289 @Override
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700290 public void initPolicy(String policy) {
291 }
Xin Jin313708b2015-07-09 13:43:04 -0700292
Charles Chana7903c82018-03-15 20:14:16 -0700293 boolean queueFwdObjective(DeviceId deviceId, ForwardingObjective fwd) {
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700294 boolean queued = false;
295 synchronized (pendingForwards) {
296 // double check the flow objective store, because this block could run
297 // after a notification arrives
298 if (flowObjectiveStore.getNextGroup(fwd.nextId()) == null) {
299 pendingForwards.compute(fwd.nextId(), (id, pending) -> {
Saurav Das1547b3f2017-05-05 17:01:08 -0700300 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, fwd);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700301 if (pending == null) {
Pier Luigi97893112018-03-05 11:09:42 +0100302 return Sets.newLinkedHashSet(ImmutableSet.of(pendfo));
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700303 } else {
Saurav Das1547b3f2017-05-05 17:01:08 -0700304 pending.add(pendfo);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700305 return pending;
306 }
307 });
308 queued = true;
309 }
310 }
311 if (queued) {
Saurav Dasc568c342018-01-25 09:49:01 -0800312 log.debug("Queued forwarding objective {} for nextId {} meant for device {}",
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700313 fwd.id(), fwd.nextId(), deviceId);
314 }
315 return queued;
alshabib2a441c62015-04-13 18:39:38 -0700316 }
317
Charles Chana7903c82018-03-15 20:14:16 -0700318 boolean queueNextObjective(DeviceId deviceId, NextObjective next) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700319 // we need to hold off on other operations till we get notified that the
320 // initial group creation has succeeded
321 boolean queued = false;
322 synchronized (pendingNexts) {
323 // double check the flow objective store, because this block could run
324 // after a notification arrives
325 if (flowObjectiveStore.getNextGroup(next.id()) == null) {
326 pendingNexts.compute(next.id(), (id, pending) -> {
327 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, next);
328 if (pending == null) {
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800329 return Lists.newArrayList(pendfo);
Saurav Das1547b3f2017-05-05 17:01:08 -0700330 } else {
331 pending.add(pendfo);
332 return pending;
333 }
334 });
335 queued = true;
336 }
337 }
338 if (queued) {
Saurav Dasc568c342018-01-25 09:49:01 -0800339 log.debug("Queued next objective {} with operation {} meant for device {}",
Saurav Das1547b3f2017-05-05 17:01:08 -0700340 next.id(), next.op(), deviceId);
341 }
342 return queued;
343 }
344
Pier Ventre57a61cd2016-09-07 10:55:41 -0700345 /**
346 * Retrieves (if it exists) the device pipeline behaviour from the cache.
347 * Otherwise it warms the caches and triggers the init method of the Pipeline.
348 *
349 * @param deviceId the id of the device associated to the pipeline
350 * @return the implementation of the Pipeliner behaviour
351 */
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700352 private Pipeliner getDevicePipeliner(DeviceId deviceId) {
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700353 return pipeliners.computeIfAbsent(deviceId, this::initPipelineHandler);
alshabib77b88482015-04-07 15:47:50 -0700354 }
355
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700356 /**
Pier Ventre57a61cd2016-09-07 10:55:41 -0700357 * Retrieves (if it exists) the device pipeline behaviour from the cache and
358 * and triggers the init method of the pipeline. Otherwise (DEVICE_ADDED) it warms
359 * the caches and triggers the init method of the Pipeline. The rationale of this
360 * method is for managing the scenario of a switch that goes down for a failure
361 * and goes up after a while.
362 *
363 * @param deviceId the id of the device associated to the pipeline
364 * @return the implementation of the Pipeliner behaviour
365 */
366 private Pipeliner getAndInitDevicePipeliner(DeviceId deviceId) {
367 return pipeliners.compute(deviceId, (deviceIdValue, pipelinerValue) -> {
368 if (pipelinerValue != null) {
369 pipelinerValue.init(deviceId, context);
370 return pipelinerValue;
371 }
372 return this.initPipelineHandler(deviceId);
373 });
374 }
375
376 /**
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700377 * Creates and initialize {@link Pipeliner}.
378 * <p>
379 * Note: Expected to be called under per-Device lock.
380 * e.g., {@code pipeliners}' Map#compute family methods
381 *
382 * @param deviceId Device to initialize pipeliner
383 * @return {@link Pipeliner} instance or null
384 */
385 private Pipeliner initPipelineHandler(DeviceId deviceId) {
386 start = now();
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700387
Jonathan Hart17d00452015-04-21 17:10:00 -0700388 // Attempt to lookup the handler in the cache
389 DriverHandler handler = driverHandlers.get(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700390 cTime = now();
391
Jonathan Hart17d00452015-04-21 17:10:00 -0700392 if (handler == null) {
393 try {
394 // Otherwise create it and if it has pipeline behaviour, cache it
395 handler = driverService.createHandler(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700396 dTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700397 if (!handler.driver().hasBehaviour(Pipeliner.class)) {
Yuta HIGUCHIa2a4f342017-03-17 11:38:57 -0700398 log.debug("Pipeline behaviour not supported for device {}",
Jonathan Hart17d00452015-04-21 17:10:00 -0700399 deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700400 return null;
alshabib2a441c62015-04-13 18:39:38 -0700401 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700402 } catch (ItemNotFoundException e) {
403 log.warn("No applicable driver for device {}", deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700404 return null;
alshabib2a441c62015-04-13 18:39:38 -0700405 }
406
Jonathan Hart17d00452015-04-21 17:10:00 -0700407 driverHandlers.put(deviceId, handler);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700408 eTime = now();
alshabib2a441c62015-04-13 18:39:38 -0700409 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700410
411 // Always (re)initialize the pipeline behaviour
412 log.info("Driver {} bound to device {} ... initializing driver",
413 handler.driver().name(), deviceId);
Thomas Vachuska0121a612015-07-21 11:18:09 -0700414 hTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700415 Pipeliner pipeliner = handler.behaviour(Pipeliner.class);
Thomas Vachuska94c3cf42015-07-20 13:01:12 -0700416 hbTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700417 pipeliner.init(deviceId, context);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700418 stopWatch();
419 return pipeliner;
alshabibaebe7752015-04-07 17:45:42 -0700420 }
alshabib77b88482015-04-07 15:47:50 -0700421
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700422 private void invalidatePipelinerIfNecessary(Device device) {
423 DriverHandler handler = driverHandlers.get(device.id());
424 if (handler != null &&
425 !Objects.equals(handler.driver().name(),
426 device.annotations().value(DRIVER))) {
427 invalidatePipeliner(device.id());
428 }
429 }
430
431 private void invalidatePipeliner(DeviceId id) {
432 log.info("Invalidating cached pipeline behaviour for {}", id);
433 driverHandlers.remove(id);
434 pipeliners.remove(id);
435 if (deviceService.isAvailable(id)) {
436 getAndInitDevicePipeliner(id);
437 }
438 }
439
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700440 // Triggers driver setup when a device is (re)detected.
alshabibaebe7752015-04-07 17:45:42 -0700441 private class InnerDeviceListener implements DeviceListener {
442 @Override
443 public void event(DeviceEvent event) {
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000444 if (devEventExecutor != null) {
alshabibaebe7752015-04-07 17:45:42 -0700445 switch (event.type()) {
446 case DEVICE_ADDED:
447 case DEVICE_AVAILABILITY_CHANGED:
Madan Jampani0174f452015-05-29 11:52:05 -0700448 log.debug("Device either added or availability changed {}",
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700449 event.subject().id());
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000450 devEventExecutor.execute(() -> {
451 if (deviceService.isAvailable(event.subject().id())) {
Madan Jampani0174f452015-05-29 11:52:05 -0700452 log.debug("Device is now available {}", event.subject().id());
Pier Ventre57a61cd2016-09-07 10:55:41 -0700453 getAndInitDevicePipeliner(event.subject().id());
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000454 } else {
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700455 log.debug("Device is no longer available {}", event.subject().id());
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000456 }
457 });
alshabib4313d102015-04-08 18:55:08 -0700458 break;
459 case DEVICE_UPDATED:
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700460 // Invalidate pipeliner and handler caches if the driver name
461 // device annotation changed.
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000462 devEventExecutor.execute(() -> invalidatePipelinerIfNecessary(event.subject()));
alshabib4313d102015-04-08 18:55:08 -0700463 break;
464 case DEVICE_REMOVED:
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700465 // evict Pipeliner and Handler cache, when
466 // the Device was administratively removed.
467 //
468 // System expect the user to clear all existing flows,
469 // before removing device, especially if they intend to
470 // replace driver/pipeliner assigned to the device.
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000471 devEventExecutor.execute(() -> {
472 driverHandlers.remove(event.subject().id());
473 pipeliners.remove(event.subject().id());
474 });
alshabib4313d102015-04-08 18:55:08 -0700475 break;
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700476 case DEVICE_SUSPENDED:
477 break;
alshabib4313d102015-04-08 18:55:08 -0700478 case PORT_ADDED:
479 break;
480 case PORT_UPDATED:
481 break;
482 case PORT_REMOVED:
alshabibaebe7752015-04-07 17:45:42 -0700483 break;
484 default:
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700485 break;
alshabibaebe7752015-04-07 17:45:42 -0700486 }
Ruchi Sahotae4934e12019-03-01 16:56:07 +0000487 }
alshabib77b88482015-04-07 15:47:50 -0700488 }
489 }
alshabibaebe7752015-04-07 17:45:42 -0700490
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700491 // Monitors driver configuration changes and invalidates the pipeliner cache entries.
492 // Note that this may leave stale entries on the device if the driver changes
493 // in manner where the new driver does not produce backward compatible flow objectives.
494 // In such cases, it is the operator's responsibility to force device re-connect.
495 private class InnerDriverListener implements DriverListener {
496 @Override
497 public void event(DriverEvent event) {
498 String driverName = event.subject().name();
499 driverHandlers.entrySet().stream()
500 .filter(e -> driverName.equals(e.getValue().driver().name()))
501 .map(Map.Entry::getKey)
502 .distinct()
503 .forEach(FlowObjectiveManager.this::invalidatePipeliner);
504 }
505 }
506
Thomas Vachuska174bb912015-07-16 21:27:14 -0700507 // Temporary mechanism to monitor pipeliner setup time-cost; there are
508 // intermittent time where this takes in excess of 2 seconds. Why?
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700509 private long start = 0, totals = 0, count = 0;
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700510 private long cTime, dTime, eTime, hTime, hbTime;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700511 private static final long LIMIT = 500;
Thomas Vachuska174bb912015-07-16 21:27:14 -0700512
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700513 private long now() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700514 return System.currentTimeMillis();
515 }
516
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700517 private void stopWatch() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700518 long duration = System.currentTimeMillis() - start;
519 totals += duration;
520 count += 1;
521 if (duration > LIMIT) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700522 log.info("Pipeline setup took {} ms; avg {} ms; cTime={}, dTime={}, eTime={}, hTime={}, hbTime={}",
523 duration, totals / count, diff(cTime), diff(dTime), diff(eTime), diff(hTime), diff(hbTime));
Thomas Vachuska174bb912015-07-16 21:27:14 -0700524 }
525 }
526
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700527 private long diff(long bTime) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700528 long diff = bTime - start;
529 return diff < 0 ? 0 : diff;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700530 }
531
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700532 // Processing context for initializing pipeline driver behaviours.
533 private class InnerPipelineContext implements PipelinerContext {
534 @Override
535 public ServiceDirectory directory() {
536 return serviceDirectory;
alshabibaebe7752015-04-07 17:45:42 -0700537 }
alshabib2a441c62015-04-13 18:39:38 -0700538
539 @Override
540 public FlowObjectiveStore store() {
541 return flowObjectiveStore;
542 }
alshabib2a441c62015-04-13 18:39:38 -0700543 }
544
545 private class InternalStoreDelegate implements FlowObjectiveStoreDelegate {
546 @Override
547 public void notify(ObjectiveEvent event) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800548 if (event.type() == Type.ADD) {
549 log.debug("Received notification of obj event {}", event);
Saurav Das1547b3f2017-05-05 17:01:08 -0700550 Set<PendingFlowObjective> pending;
551
552 // first send all pending flows
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700553 synchronized (pendingForwards) {
554 // needs to be synchronized for queueObjective lookup
555 pending = pendingForwards.remove(event.subject());
556 }
Saurav Das423fe2b2015-12-04 10:52:59 -0800557 if (pending == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700558 log.debug("No forwarding objectives pending for this "
559 + "obj event {}", event);
560 } else {
561 log.debug("Processing {} pending forwarding objectives for nextId {}",
562 pending.size(), event.subject());
563 pending.forEach(p -> getDevicePipeliner(p.deviceId())
564 .forward((ForwardingObjective) p.flowObjective()));
Saurav Das423fe2b2015-12-04 10:52:59 -0800565 }
566
Saurav Das1547b3f2017-05-05 17:01:08 -0700567 // now check for pending next-objectives
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800568 List<PendingFlowObjective> pendNexts;
Saurav Das1547b3f2017-05-05 17:01:08 -0700569 synchronized (pendingNexts) {
570 // needs to be synchronized for queueObjective lookup
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800571 pendNexts = pendingNexts.remove(event.subject());
Saurav Das1547b3f2017-05-05 17:01:08 -0700572 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800573 if (pendNexts == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700574 log.debug("No next objectives pending for this "
575 + "obj event {}", event);
576 } else {
577 log.debug("Processing {} pending next objectives for nextId {}",
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800578 pendNexts.size(), event.subject());
579 pendNexts.forEach(p -> getDevicePipeliner(p.deviceId())
Saurav Das1547b3f2017-05-05 17:01:08 -0700580 .next((NextObjective) p.flowObjective()));
581 }
alshabib2a441c62015-04-13 18:39:38 -0700582 }
alshabib2a441c62015-04-13 18:39:38 -0700583 }
584 }
585
586 /**
Saurav Das1547b3f2017-05-05 17:01:08 -0700587 * Data class used to hold a pending flow objective that could not
alshabib2a441c62015-04-13 18:39:38 -0700588 * be processed because the associated next object was not present.
Saurav Das1547b3f2017-05-05 17:01:08 -0700589 * Note that this pending flow objective could be a forwarding objective
590 * waiting for a next objective to complete execution. Or it could a
591 * next objective (with a different operation - remove, addToExisting, or
592 * removeFromExisting) waiting for a next objective with the same id to
593 * complete execution.
alshabib2a441c62015-04-13 18:39:38 -0700594 */
Charles Chana7903c82018-03-15 20:14:16 -0700595 protected class PendingFlowObjective {
alshabib2a441c62015-04-13 18:39:38 -0700596 private final DeviceId deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700597 private final Objective flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700598
Charles Chana7903c82018-03-15 20:14:16 -0700599 PendingFlowObjective(DeviceId deviceId, Objective flowObj) {
alshabib2a441c62015-04-13 18:39:38 -0700600 this.deviceId = deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700601 this.flowObj = flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700602 }
603
604 public DeviceId deviceId() {
605 return deviceId;
606 }
607
Saurav Das1547b3f2017-05-05 17:01:08 -0700608 public Objective flowObjective() {
609 return flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700610 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800611
612 @Override
613 public int hashCode() {
Saurav Das1547b3f2017-05-05 17:01:08 -0700614 return Objects.hash(deviceId, flowObj);
Saurav Das8a0732e2015-11-20 15:27:53 -0800615 }
616
617 @Override
618 public boolean equals(final Object obj) {
619 if (this == obj) {
620 return true;
621 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700622 if (!(obj instanceof PendingFlowObjective)) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800623 return false;
624 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700625 final PendingFlowObjective other = (PendingFlowObjective) obj;
Charles Chana7903c82018-03-15 20:14:16 -0700626
627 return this.deviceId.equals(other.deviceId) &&
628 this.flowObj.equals(other.flowObj);
Saurav Das8a0732e2015-11-20 15:27:53 -0800629 }
alshabibaebe7752015-04-07 17:45:42 -0700630 }
Saurav Das24431192016-03-07 19:13:00 -0800631
632 @Override
633 public List<String> getNextMappings() {
634 List<String> mappings = new ArrayList<>();
635 Map<Integer, NextGroup> allnexts = flowObjectiveStore.getAllGroups();
Saurav Das25190812016-05-27 13:54:07 -0700636 // XXX if the NextGroup after de-serialization actually stored info of the deviceId
Saurav Das24431192016-03-07 19:13:00 -0800637 // then info on any nextObj could be retrieved from one controller instance.
638 // Right now the drivers on one instance can only fetch for next-ids that came
639 // to them.
640 // Also, we still need to send the right next-id to the right driver as potentially
641 // there can be different drivers for different devices. But on that account,
642 // no instance should be decoding for another instance's nextIds.
643
644 for (Map.Entry<Integer, NextGroup> e : allnexts.entrySet()) {
645 // get the device this next Objective was sent to
646 DeviceId deviceId = nextToDevice.get(e.getKey());
647 mappings.add("NextId " + e.getKey() + ": " +
648 ((deviceId != null) ? deviceId : "nextId not in this onos instance"));
649 if (deviceId != null) {
650 // this instance of the controller sent the nextObj to a driver
651 Pipeliner pipeliner = getDevicePipeliner(deviceId);
652 List<String> nextMappings = pipeliner.getNextMappings(e.getValue());
653 if (nextMappings != null) {
654 mappings.addAll(nextMappings);
655 }
656 }
657 }
658 return mappings;
659 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700660
661 @Override
Saurav Das1547b3f2017-05-05 17:01:08 -0700662 public List<String> getPendingFlowObjectives() {
663 List<String> pendingFlowObjectives = new ArrayList<>();
Charles Chan54734712017-03-29 11:07:55 -0700664
Saurav Das1547b3f2017-05-05 17:01:08 -0700665 for (Integer nextId : pendingForwards.keySet()) {
666 Set<PendingFlowObjective> pfwd = pendingForwards.get(nextId);
Sho SHIMIZU81470a52016-08-12 17:24:55 -0700667 StringBuilder pend = new StringBuilder();
Charles Chan54734712017-03-29 11:07:55 -0700668 pend.append("NextId: ")
669 .append(nextId);
Saurav Das1547b3f2017-05-05 17:01:08 -0700670 for (PendingFlowObjective pf : pfwd) {
Charles Chan54734712017-03-29 11:07:55 -0700671 pend.append("\n FwdId: ")
Saurav Das1547b3f2017-05-05 17:01:08 -0700672 .append(String.format("%11s", pf.flowObjective().id()))
673 .append(", DeviceId: ")
674 .append(pf.deviceId())
675 .append(", Selector: ")
676 .append(((ForwardingObjective) pf.flowObjective())
677 .selector().criteria());
678 }
679 pendingFlowObjectives.add(pend.toString());
680 }
681
682 for (Integer nextId : pendingNexts.keySet()) {
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800683 List<PendingFlowObjective> pnext = pendingNexts.get(nextId);
Saurav Das1547b3f2017-05-05 17:01:08 -0700684 StringBuilder pend = new StringBuilder();
685 pend.append("NextId: ")
686 .append(nextId);
687 for (PendingFlowObjective pn : pnext) {
688 pend.append("\n NextOp: ")
689 .append(pn.flowObjective().op())
Charles Chan54734712017-03-29 11:07:55 -0700690 .append(", DeviceId: ")
691 .append(pn.deviceId())
Saurav Das1547b3f2017-05-05 17:01:08 -0700692 .append(", Treatments: ")
693 .append(((NextObjective) pn.flowObjective())
694 .next());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700695 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700696 pendingFlowObjectives.add(pend.toString());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700697 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700698
699 return pendingFlowObjectives;
700 }
alshabib77b88482015-04-07 15:47:50 -0700701}