blob: c623bf2a9cabc194566c442f57328b76e6b92899 [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
Saurav Das9aa28bd2017-12-05 15:00:23 -080018import com.google.common.collect.Lists;
alshabib77b88482015-04-07 15:47:50 -070019import com.google.common.collect.Maps;
Thomas Vachuskad27097c2016-06-14 19:10:41 -070020import com.google.common.collect.Sets;
alshabib77b88482015-04-07 15:47:50 -070021import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Deactivate;
Yi Tseng374c5f32017-03-05 22:51:35 -080024import org.apache.felix.scr.annotations.Modified;
25import org.apache.felix.scr.annotations.Property;
alshabib77b88482015-04-07 15:47:50 -070026import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.Service;
29import org.onlab.osgi.DefaultServiceDirectory;
30import org.onlab.osgi.ServiceDirectory;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070031import org.onlab.util.ItemNotFoundException;
Yi Tseng374c5f32017-03-05 22:51:35 -080032import org.onlab.util.Tools;
33import org.onosproject.cfg.ComponentConfigService;
alshabib77b88482015-04-07 15:47:50 -070034import org.onosproject.cluster.ClusterService;
Thomas Vachuskad24ba732017-08-23 15:29:34 -070035import org.onosproject.net.Device;
alshabib77b88482015-04-07 15:47:50 -070036import org.onosproject.net.DeviceId;
Saurav Das24431192016-03-07 19:13:00 -080037import org.onosproject.net.behaviour.NextGroup;
alshabib77b88482015-04-07 15:47:50 -070038import org.onosproject.net.behaviour.Pipeliner;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070039import org.onosproject.net.behaviour.PipelinerContext;
alshabibaebe7752015-04-07 17:45:42 -070040import org.onosproject.net.device.DeviceEvent;
41import org.onosproject.net.device.DeviceListener;
alshabib77b88482015-04-07 15:47:50 -070042import org.onosproject.net.device.DeviceService;
Thomas Vachuskad24ba732017-08-23 15:29:34 -070043import org.onosproject.net.driver.DriverEvent;
alshabib77b88482015-04-07 15:47:50 -070044import org.onosproject.net.driver.DriverHandler;
Thomas Vachuskad24ba732017-08-23 15:29:34 -070045import org.onosproject.net.driver.DriverListener;
alshabib77b88482015-04-07 15:47:50 -070046import org.onosproject.net.driver.DriverService;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070047import org.onosproject.net.flow.FlowRuleService;
alshabib77b88482015-04-07 15:47:50 -070048import org.onosproject.net.flowobjective.FilteringObjective;
49import org.onosproject.net.flowobjective.FlowObjectiveService;
alshabib2a441c62015-04-13 18:39:38 -070050import org.onosproject.net.flowobjective.FlowObjectiveStore;
51import org.onosproject.net.flowobjective.FlowObjectiveStoreDelegate;
alshabib77b88482015-04-07 15:47:50 -070052import org.onosproject.net.flowobjective.ForwardingObjective;
53import org.onosproject.net.flowobjective.NextObjective;
alshabib910aff12015-04-09 16:55:57 -070054import org.onosproject.net.flowobjective.Objective;
Saurav Das1547b3f2017-05-05 17:01:08 -070055import org.onosproject.net.flowobjective.Objective.Operation;
Jonathan Hart17d00452015-04-21 17:10:00 -070056import org.onosproject.net.flowobjective.ObjectiveError;
alshabib2a441c62015-04-13 18:39:38 -070057import org.onosproject.net.flowobjective.ObjectiveEvent;
Saurav Das423fe2b2015-12-04 10:52:59 -080058import org.onosproject.net.flowobjective.ObjectiveEvent.Type;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070059import org.onosproject.net.group.GroupService;
Yi Tseng374c5f32017-03-05 22:51:35 -080060import org.osgi.service.component.ComponentContext;
alshabib77b88482015-04-07 15:47:50 -070061import org.slf4j.Logger;
62import org.slf4j.LoggerFactory;
63
Saurav Das24431192016-03-07 19:13:00 -080064import java.util.ArrayList;
Saurav Das24431192016-03-07 19:13:00 -080065import java.util.List;
alshabib77b88482015-04-07 15:47:50 -070066import java.util.Map;
Saurav Das8a0732e2015-11-20 15:27:53 -080067import java.util.Objects;
alshabib2a441c62015-04-13 18:39:38 -070068import java.util.Set;
Jonathan Hart17d00452015-04-21 17:10:00 -070069import java.util.concurrent.ExecutorService;
alshabib77b88482015-04-07 15:47:50 -070070
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -070071import static com.google.common.base.Preconditions.checkNotNull;
Yi Tseng374c5f32017-03-05 22:51:35 -080072import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuska866b46a2015-04-30 00:26:55 -070073import static java.util.concurrent.Executors.newFixedThreadPool;
Jonathan Hart17d00452015-04-21 17:10:00 -070074import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskad24ba732017-08-23 15:29:34 -070075import static org.onosproject.net.AnnotationKeys.DRIVER;
Changhoon Yoon541ef712015-05-23 17:18:34 +090076import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskad27097c2016-06-14 19:10:41 -070077import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
alshabib77b88482015-04-07 15:47:50 -070078
79/**
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070080 * Provides implementation of the flow objective programming service.
alshabib77b88482015-04-07 15:47:50 -070081 */
alshabib2a441c62015-04-13 18:39:38 -070082@Component(immediate = true)
alshabib77b88482015-04-07 15:47:50 -070083@Service
84public class FlowObjectiveManager implements FlowObjectiveService {
85
Saurav Dasbd7f7422015-04-23 16:31:47 -070086 public static final int INSTALL_RETRY_ATTEMPTS = 5;
Jonathan Hart17d00452015-04-21 17:10:00 -070087 public static final long INSTALL_RETRY_INTERVAL = 1000; // ms
alshabib77b88482015-04-07 15:47:50 -070088
Yi Tseng374c5f32017-03-05 22:51:35 -080089 private static final String WORKER_PATTERN = "objective-installer-%d";
90 private static final String GROUP_THREAD_NAME = "onos/objective-installer";
91 private static final String NUM_THREAD = "numThreads";
92
Jonathan Hart17d00452015-04-21 17:10:00 -070093 private final Logger log = LoggerFactory.getLogger(getClass());
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070094
Yi Tseng9753fc12017-03-10 18:42:46 -080095 private static final int DEFAULT_NUM_THREADS = 4;
Yi Tseng374c5f32017-03-05 22:51:35 -080096 @Property(name = NUM_THREAD,
97 intValue = DEFAULT_NUM_THREADS,
98 label = "Number of worker threads")
99 private int numThreads = DEFAULT_NUM_THREADS;
100
alshabib77b88482015-04-07 15:47:50 -0700101 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
102 protected DriverService driverService;
103
104 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
105 protected DeviceService deviceService;
106
107 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
alshabib77b88482015-04-07 15:47:50 -0700108 protected ClusterService clusterService;
109
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700110 // Note: The following dependencies are added on behalf of the pipeline
111 // driver behaviours to assure these services are available for their
112 // initialization.
113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
114 protected FlowRuleService flowRuleService;
115
116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
117 protected GroupService groupService;
118
alshabib2a441c62015-04-13 18:39:38 -0700119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
120 protected FlowObjectiveStore flowObjectiveStore;
121
Yi Tseng374c5f32017-03-05 22:51:35 -0800122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
123 protected ComponentConfigService cfgService;
124
alshabib2a441c62015-04-13 18:39:38 -0700125 private final FlowObjectiveStoreDelegate delegate = new InternalStoreDelegate();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700126
127 private final Map<DeviceId, DriverHandler> driverHandlers = Maps.newConcurrentMap();
alshabib910aff12015-04-09 16:55:57 -0700128 private final Map<DeviceId, Pipeliner> pipeliners = Maps.newConcurrentMap();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700129
130 private final PipelinerContext context = new InnerPipelineContext();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700131 private final DeviceListener deviceListener = new InnerDeviceListener();
Thomas Vachuskad24ba732017-08-23 15:29:34 -0700132 private final DriverListener driverListener = new InnerDriverListener();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700133
alshabib77b88482015-04-07 15:47:50 -0700134 protected ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
alshabib910aff12015-04-09 16:55:57 -0700135
Saurav Das1547b3f2017-05-05 17:01:08 -0700136 // local stores for queuing fwd and next objectives that are waiting for an
137 // associated next objective execution to complete. The signal for completed
138 // execution comes from a pipeline driver, in this or another controller
139 // instance, via the DistributedFlowObjectiveStore.
140 private final Map<Integer, Set<PendingFlowObjective>> pendingForwards =
141 Maps.newConcurrentMap();
Saurav Das9aa28bd2017-12-05 15:00:23 -0800142 private final Map<Integer, List<PendingFlowObjective>> pendingNexts =
Saurav Das1547b3f2017-05-05 17:01:08 -0700143 Maps.newConcurrentMap();
alshabib2a441c62015-04-13 18:39:38 -0700144
Saurav Das24431192016-03-07 19:13:00 -0800145 // local store to track which nextObjectives were sent to which device
146 // for debugging purposes
147 private Map<Integer, DeviceId> nextToDevice = Maps.newConcurrentMap();
148
Jonathan Hart17d00452015-04-21 17:10:00 -0700149 private ExecutorService executorService;
alshabib2a441c62015-04-13 18:39:38 -0700150
alshabib77b88482015-04-07 15:47:50 -0700151 @Activate
152 protected void activate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800153 cfgService.registerProperties(getClass());
154 executorService = newFixedThreadPool(numThreads,
155 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
alshabib2a441c62015-04-13 18:39:38 -0700156 flowObjectiveStore.setDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700157 deviceService.addListener(deviceListener);
Thomas Vachuskad24ba732017-08-23 15:29:34 -0700158 driverService.addListener(driverListener);
alshabib77b88482015-04-07 15:47:50 -0700159 log.info("Started");
160 }
161
162 @Deactivate
163 protected void deactivate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800164 cfgService.unregisterProperties(getClass(), false);
alshabib2a441c62015-04-13 18:39:38 -0700165 flowObjectiveStore.unsetDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700166 deviceService.removeListener(deviceListener);
Thomas Vachuskad24ba732017-08-23 15:29:34 -0700167 driverService.removeListener(driverListener);
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700168 executorService.shutdown();
169 pipeliners.clear();
170 driverHandlers.clear();
Saurav Das24431192016-03-07 19:13:00 -0800171 nextToDevice.clear();
alshabib77b88482015-04-07 15:47:50 -0700172 log.info("Stopped");
173 }
174
Yi Tseng374c5f32017-03-05 22:51:35 -0800175 @Modified
176 protected void modified(ComponentContext context) {
177 String propertyValue =
178 Tools.get(context.getProperties(), NUM_THREAD);
179 int newNumThreads = isNullOrEmpty(propertyValue) ? numThreads : Integer.parseInt(propertyValue);
180
181 if (newNumThreads != numThreads && newNumThreads > 0) {
182 numThreads = newNumThreads;
183 ExecutorService oldWorkerExecutor = executorService;
184 executorService = newFixedThreadPool(numThreads,
185 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
186 if (oldWorkerExecutor != null) {
187 oldWorkerExecutor.shutdown();
188 }
189 log.info("Reconfigured number of worker threads to {}", numThreads);
190 }
191 }
192
Jonathan Hart17d00452015-04-21 17:10:00 -0700193 /**
194 * Task that passes the flow objective down to the driver. The task will
195 * make a few attempts to find the appropriate driver, then eventually give
196 * up and report an error if no suitable driver could be found.
197 */
198 private class ObjectiveInstaller implements Runnable {
199 private final DeviceId deviceId;
200 private final Objective objective;
201
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700202 private final int numAttempts;
Jonathan Hart17d00452015-04-21 17:10:00 -0700203
204 public ObjectiveInstaller(DeviceId deviceId, Objective objective) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700205 this(deviceId, objective, 1);
206 }
207
208 public ObjectiveInstaller(DeviceId deviceId, Objective objective, int attemps) {
209 this.deviceId = checkNotNull(deviceId);
210 this.objective = checkNotNull(objective);
Yuta HIGUCHI1edc36b2018-01-24 23:39:06 -0800211 this.numAttempts = attemps;
alshabib910aff12015-04-09 16:55:57 -0700212 }
alshabib77b88482015-04-07 15:47:50 -0700213
Jonathan Hart17d00452015-04-21 17:10:00 -0700214 @Override
215 public void run() {
216 try {
Jonathan Hart17d00452015-04-21 17:10:00 -0700217 Pipeliner pipeliner = getDevicePipeliner(deviceId);
218
219 if (pipeliner != null) {
220 if (objective instanceof NextObjective) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700221 nextToDevice.put(objective.id(), deviceId);
Jonathan Hart17d00452015-04-21 17:10:00 -0700222 pipeliner.next((NextObjective) objective);
223 } else if (objective instanceof ForwardingObjective) {
224 pipeliner.forward((ForwardingObjective) objective);
225 } else {
226 pipeliner.filter((FilteringObjective) objective);
227 }
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800228 //Attempts to check if pipeliner is null for retry attempts
Jonathan Hart17d00452015-04-21 17:10:00 -0700229 } else if (numAttempts < INSTALL_RETRY_ATTEMPTS) {
Saurav Das3d038262015-04-23 12:36:58 -0700230 Thread.sleep(INSTALL_RETRY_INTERVAL);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700231 executorService.execute(new ObjectiveInstaller(deviceId, objective, numAttempts + 1));
Jonathan Hart17d00452015-04-21 17:10:00 -0700232 } else {
233 // Otherwise we've tried a few times and failed, report an
234 // error back to the user.
235 objective.context().ifPresent(
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800236 c -> c.onError(objective, ObjectiveError.NOPIPELINER));
Jonathan Hart17d00452015-04-21 17:10:00 -0700237 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700238 //Exception thrown
Jonathan Hart17d00452015-04-21 17:10:00 -0700239 } catch (Exception e) {
240 log.warn("Exception while installing flow objective", e);
241 }
242 }
243 }
244
245 @Override
246 public void filter(DeviceId deviceId, FilteringObjective filteringObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900247 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700248 executorService.execute(new ObjectiveInstaller(deviceId, filteringObjective));
alshabib77b88482015-04-07 15:47:50 -0700249 }
250
251 @Override
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700252 public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900253 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700254 if (forwardingObjective.nextId() == null ||
255 forwardingObjective.op() == Objective.Operation.REMOVE ||
256 flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null ||
257 !queueFwdObjective(deviceId, forwardingObjective)) {
258 // fast path
259 executorService.execute(new ObjectiveInstaller(deviceId, forwardingObjective));
alshabib910aff12015-04-09 16:55:57 -0700260 }
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700261 }
262
alshabib2a441c62015-04-13 18:39:38 -0700263 @Override
Jonathan Hart17d00452015-04-21 17:10:00 -0700264 public void next(DeviceId deviceId, NextObjective nextObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900265 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700266 if (nextObjective.op() == Operation.ADD ||
267 flowObjectiveStore.getNextGroup(nextObjective.id()) != null ||
268 !queueNextObjective(deviceId, nextObjective)) {
269 // either group exists or we are trying to create it - let it through
270 executorService.execute(new ObjectiveInstaller(deviceId, nextObjective));
Saurav Das1547b3f2017-05-05 17:01:08 -0700271 }
alshabib2a441c62015-04-13 18:39:38 -0700272 }
273
alshabibf6ea9e62015-04-21 17:08:26 -0700274 @Override
275 public int allocateNextId() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900276 checkPermission(FLOWRULE_WRITE);
alshabibf6ea9e62015-04-21 17:08:26 -0700277 return flowObjectiveStore.allocateNextId();
278 }
279
Xin Jin313708b2015-07-09 13:43:04 -0700280 @Override
Thomas Vachuskad24ba732017-08-23 15:29:34 -0700281 public void initPolicy(String policy) {
282 }
Xin Jin313708b2015-07-09 13:43:04 -0700283
Saurav Das1547b3f2017-05-05 17:01:08 -0700284 private boolean queueFwdObjective(DeviceId deviceId, ForwardingObjective fwd) {
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700285 boolean queued = false;
286 synchronized (pendingForwards) {
287 // double check the flow objective store, because this block could run
288 // after a notification arrives
289 if (flowObjectiveStore.getNextGroup(fwd.nextId()) == null) {
290 pendingForwards.compute(fwd.nextId(), (id, pending) -> {
Saurav Das1547b3f2017-05-05 17:01:08 -0700291 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, fwd);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700292 if (pending == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700293 return Sets.newHashSet(pendfo);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700294 } else {
Saurav Das1547b3f2017-05-05 17:01:08 -0700295 pending.add(pendfo);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700296 return pending;
297 }
298 });
299 queued = true;
300 }
301 }
302 if (queued) {
Sivachidambaram Subramaniana0efdcc2017-06-22 05:26:46 +0530303 log.info("Queued forwarding objective {} for nextId {} meant for device {}",
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700304 fwd.id(), fwd.nextId(), deviceId);
305 }
306 return queued;
alshabib2a441c62015-04-13 18:39:38 -0700307 }
308
Saurav Das1547b3f2017-05-05 17:01:08 -0700309 private boolean queueNextObjective(DeviceId deviceId, NextObjective next) {
Yi Tseng1666b502017-05-17 11:05:18 -0700310
Saurav Das1547b3f2017-05-05 17:01:08 -0700311 // we need to hold off on other operations till we get notified that the
312 // initial group creation has succeeded
313 boolean queued = false;
314 synchronized (pendingNexts) {
315 // double check the flow objective store, because this block could run
316 // after a notification arrives
317 if (flowObjectiveStore.getNextGroup(next.id()) == null) {
318 pendingNexts.compute(next.id(), (id, pending) -> {
319 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, next);
320 if (pending == null) {
Saurav Das9aa28bd2017-12-05 15:00:23 -0800321 return Lists.newArrayList(pendfo);
Saurav Das1547b3f2017-05-05 17:01:08 -0700322 } else {
323 pending.add(pendfo);
324 return pending;
325 }
326 });
327 queued = true;
328 }
329 }
330 if (queued) {
Sivachidambaram Subramaniana0efdcc2017-06-22 05:26:46 +0530331 log.info("Queued next objective {} with operation {} meant for device {}",
Saurav Das1547b3f2017-05-05 17:01:08 -0700332 next.id(), next.op(), deviceId);
333 }
334 return queued;
335 }
336
Pier Ventre57a61cd2016-09-07 10:55:41 -0700337 /**
338 * Retrieves (if it exists) the device pipeline behaviour from the cache.
339 * Otherwise it warms the caches and triggers the init method of the Pipeline.
340 *
341 * @param deviceId the id of the device associated to the pipeline
342 * @return the implementation of the Pipeliner behaviour
343 */
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700344 private Pipeliner getDevicePipeliner(DeviceId deviceId) {
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700345 return pipeliners.computeIfAbsent(deviceId, this::initPipelineHandler);
alshabib77b88482015-04-07 15:47:50 -0700346 }
347
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700348 /**
Pier Ventre57a61cd2016-09-07 10:55:41 -0700349 * Retrieves (if it exists) the device pipeline behaviour from the cache and
350 * and triggers the init method of the pipeline. Otherwise (DEVICE_ADDED) it warms
351 * the caches and triggers the init method of the Pipeline. The rationale of this
352 * method is for managing the scenario of a switch that goes down for a failure
353 * and goes up after a while.
354 *
355 * @param deviceId the id of the device associated to the pipeline
356 * @return the implementation of the Pipeliner behaviour
357 */
358 private Pipeliner getAndInitDevicePipeliner(DeviceId deviceId) {
359 return pipeliners.compute(deviceId, (deviceIdValue, pipelinerValue) -> {
360 if (pipelinerValue != null) {
361 pipelinerValue.init(deviceId, context);
362 return pipelinerValue;
363 }
364 return this.initPipelineHandler(deviceId);
365 });
366 }
367
368 /**
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700369 * Creates and initialize {@link Pipeliner}.
370 * <p>
371 * Note: Expected to be called under per-Device lock.
372 * e.g., {@code pipeliners}' Map#compute family methods
373 *
374 * @param deviceId Device to initialize pipeliner
375 * @return {@link Pipeliner} instance or null
376 */
377 private Pipeliner initPipelineHandler(DeviceId deviceId) {
378 start = now();
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700379
Jonathan Hart17d00452015-04-21 17:10:00 -0700380 // Attempt to lookup the handler in the cache
381 DriverHandler handler = driverHandlers.get(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700382 cTime = now();
383
Jonathan Hart17d00452015-04-21 17:10:00 -0700384 if (handler == null) {
385 try {
386 // Otherwise create it and if it has pipeline behaviour, cache it
387 handler = driverService.createHandler(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700388 dTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700389 if (!handler.driver().hasBehaviour(Pipeliner.class)) {
Yuta HIGUCHIa2a4f342017-03-17 11:38:57 -0700390 log.debug("Pipeline behaviour not supported for device {}",
Jonathan Hart17d00452015-04-21 17:10:00 -0700391 deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700392 return null;
alshabib2a441c62015-04-13 18:39:38 -0700393 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700394 } catch (ItemNotFoundException e) {
395 log.warn("No applicable driver for device {}", deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700396 return null;
alshabib2a441c62015-04-13 18:39:38 -0700397 }
398
Jonathan Hart17d00452015-04-21 17:10:00 -0700399 driverHandlers.put(deviceId, handler);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700400 eTime = now();
alshabib2a441c62015-04-13 18:39:38 -0700401 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700402
403 // Always (re)initialize the pipeline behaviour
404 log.info("Driver {} bound to device {} ... initializing driver",
405 handler.driver().name(), deviceId);
Thomas Vachuska0121a612015-07-21 11:18:09 -0700406 hTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700407 Pipeliner pipeliner = handler.behaviour(Pipeliner.class);
Thomas Vachuska94c3cf42015-07-20 13:01:12 -0700408 hbTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700409 pipeliner.init(deviceId, context);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700410 stopWatch();
411 return pipeliner;
alshabibaebe7752015-04-07 17:45:42 -0700412 }
alshabib77b88482015-04-07 15:47:50 -0700413
Thomas Vachuskad24ba732017-08-23 15:29:34 -0700414 private void invalidatePipelinerIfNecessary(Device device) {
415 DriverHandler handler = driverHandlers.get(device.id());
416 if (handler != null &&
417 !Objects.equals(handler.driver().name(),
418 device.annotations().value(DRIVER))) {
419 invalidatePipeliner(device.id());
420 }
421 }
422
423 private void invalidatePipeliner(DeviceId id) {
424 log.info("Invalidating cached pipeline behaviour for {}", id);
425 driverHandlers.remove(id);
426 pipeliners.remove(id);
427 if (deviceService.isAvailable(id)) {
428 getAndInitDevicePipeliner(id);
429 }
430 }
431
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700432 // Triggers driver setup when a device is (re)detected.
alshabibaebe7752015-04-07 17:45:42 -0700433 private class InnerDeviceListener implements DeviceListener {
434 @Override
435 public void event(DeviceEvent event) {
436 switch (event.type()) {
437 case DEVICE_ADDED:
438 case DEVICE_AVAILABILITY_CHANGED:
Madan Jampani0174f452015-05-29 11:52:05 -0700439 log.debug("Device either added or availability changed {}",
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700440 event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700441 if (deviceService.isAvailable(event.subject().id())) {
Madan Jampani0174f452015-05-29 11:52:05 -0700442 log.debug("Device is now available {}", event.subject().id());
Pier Ventre57a61cd2016-09-07 10:55:41 -0700443 getAndInitDevicePipeliner(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700444 } else {
445 log.debug("Device is no longer available {}", event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700446 }
447 break;
448 case DEVICE_UPDATED:
Thomas Vachuskad24ba732017-08-23 15:29:34 -0700449 // Invalidate pipeliner and handler caches if the driver name
450 // device annotation changed.
451 invalidatePipelinerIfNecessary(event.subject());
alshabib4313d102015-04-08 18:55:08 -0700452 break;
453 case DEVICE_REMOVED:
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700454 // evict Pipeliner and Handler cache, when
455 // the Device was administratively removed.
456 //
457 // System expect the user to clear all existing flows,
458 // before removing device, especially if they intend to
459 // replace driver/pipeliner assigned to the device.
460 driverHandlers.remove(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700461 pipeliners.remove(event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700462 break;
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700463 case DEVICE_SUSPENDED:
464 break;
alshabib4313d102015-04-08 18:55:08 -0700465 case PORT_ADDED:
466 break;
467 case PORT_UPDATED:
468 break;
469 case PORT_REMOVED:
alshabibaebe7752015-04-07 17:45:42 -0700470 break;
471 default:
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700472 break;
alshabibaebe7752015-04-07 17:45:42 -0700473 }
alshabib77b88482015-04-07 15:47:50 -0700474 }
475 }
alshabibaebe7752015-04-07 17:45:42 -0700476
Thomas Vachuskad24ba732017-08-23 15:29:34 -0700477 // Monitors driver configuration changes and invalidates the pipeliner cache entries.
478 // Note that this may leave stale entries on the device if the driver changes
479 // in manner where the new driver does not produce backward compatible flow objectives.
480 // In such cases, it is the operator's responsibility to force device re-connect.
481 private class InnerDriverListener implements DriverListener {
482 @Override
483 public void event(DriverEvent event) {
484 String driverName = event.subject().name();
485 driverHandlers.entrySet().stream()
486 .filter(e -> driverName.equals(e.getValue().driver().name()))
487 .map(Map.Entry::getKey)
488 .distinct()
489 .forEach(FlowObjectiveManager.this::invalidatePipeliner);
490 }
491 }
492
Thomas Vachuska174bb912015-07-16 21:27:14 -0700493 // Temporary mechanism to monitor pipeliner setup time-cost; there are
494 // intermittent time where this takes in excess of 2 seconds. Why?
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700495 private long start = 0, totals = 0, count = 0;
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700496 private long cTime, dTime, eTime, hTime, hbTime;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700497 private static final long LIMIT = 500;
Thomas Vachuska174bb912015-07-16 21:27:14 -0700498
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700499 private long now() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700500 return System.currentTimeMillis();
501 }
502
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700503 private void stopWatch() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700504 long duration = System.currentTimeMillis() - start;
505 totals += duration;
506 count += 1;
507 if (duration > LIMIT) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700508 log.info("Pipeline setup took {} ms; avg {} ms; cTime={}, dTime={}, eTime={}, hTime={}, hbTime={}",
509 duration, totals / count, diff(cTime), diff(dTime), diff(eTime), diff(hTime), diff(hbTime));
Thomas Vachuska174bb912015-07-16 21:27:14 -0700510 }
511 }
512
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700513 private long diff(long bTime) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700514 long diff = bTime - start;
515 return diff < 0 ? 0 : diff;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700516 }
517
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700518 // Processing context for initializing pipeline driver behaviours.
519 private class InnerPipelineContext implements PipelinerContext {
520 @Override
521 public ServiceDirectory directory() {
522 return serviceDirectory;
alshabibaebe7752015-04-07 17:45:42 -0700523 }
alshabib2a441c62015-04-13 18:39:38 -0700524
525 @Override
526 public FlowObjectiveStore store() {
527 return flowObjectiveStore;
528 }
alshabib2a441c62015-04-13 18:39:38 -0700529 }
530
531 private class InternalStoreDelegate implements FlowObjectiveStoreDelegate {
532 @Override
533 public void notify(ObjectiveEvent event) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800534 if (event.type() == Type.ADD) {
535 log.debug("Received notification of obj event {}", event);
Saurav Das1547b3f2017-05-05 17:01:08 -0700536 Set<PendingFlowObjective> pending;
537
538 // first send all pending flows
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700539 synchronized (pendingForwards) {
540 // needs to be synchronized for queueObjective lookup
541 pending = pendingForwards.remove(event.subject());
542 }
Saurav Das423fe2b2015-12-04 10:52:59 -0800543 if (pending == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700544 log.debug("No forwarding objectives pending for this "
545 + "obj event {}", event);
546 } else {
547 log.debug("Processing {} pending forwarding objectives for nextId {}",
548 pending.size(), event.subject());
549 pending.forEach(p -> getDevicePipeliner(p.deviceId())
550 .forward((ForwardingObjective) p.flowObjective()));
Saurav Das423fe2b2015-12-04 10:52:59 -0800551 }
552
Saurav Das1547b3f2017-05-05 17:01:08 -0700553 // now check for pending next-objectives
Saurav Das9aa28bd2017-12-05 15:00:23 -0800554 List<PendingFlowObjective> pendNexts;
Saurav Das1547b3f2017-05-05 17:01:08 -0700555 synchronized (pendingNexts) {
556 // needs to be synchronized for queueObjective lookup
Saurav Das9aa28bd2017-12-05 15:00:23 -0800557 pendNexts = pendingNexts.remove(event.subject());
Saurav Das1547b3f2017-05-05 17:01:08 -0700558 }
Saurav Das9aa28bd2017-12-05 15:00:23 -0800559 if (pendNexts == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700560 log.debug("No next objectives pending for this "
561 + "obj event {}", event);
562 } else {
563 log.debug("Processing {} pending next objectives for nextId {}",
Saurav Das9aa28bd2017-12-05 15:00:23 -0800564 pendNexts.size(), event.subject());
565 pendNexts.forEach(p -> getDevicePipeliner(p.deviceId())
Saurav Das1547b3f2017-05-05 17:01:08 -0700566 .next((NextObjective) p.flowObjective()));
567 }
alshabib2a441c62015-04-13 18:39:38 -0700568 }
alshabib2a441c62015-04-13 18:39:38 -0700569 }
570 }
571
572 /**
Saurav Das1547b3f2017-05-05 17:01:08 -0700573 * Data class used to hold a pending flow objective that could not
alshabib2a441c62015-04-13 18:39:38 -0700574 * be processed because the associated next object was not present.
Saurav Das1547b3f2017-05-05 17:01:08 -0700575 * Note that this pending flow objective could be a forwarding objective
576 * waiting for a next objective to complete execution. Or it could a
577 * next objective (with a different operation - remove, addToExisting, or
578 * removeFromExisting) waiting for a next objective with the same id to
579 * complete execution.
alshabib2a441c62015-04-13 18:39:38 -0700580 */
Saurav Das1547b3f2017-05-05 17:01:08 -0700581 private class PendingFlowObjective {
alshabib2a441c62015-04-13 18:39:38 -0700582 private final DeviceId deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700583 private final Objective flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700584
Saurav Das1547b3f2017-05-05 17:01:08 -0700585 public PendingFlowObjective(DeviceId deviceId, Objective flowObj) {
alshabib2a441c62015-04-13 18:39:38 -0700586 this.deviceId = deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700587 this.flowObj = flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700588 }
589
590 public DeviceId deviceId() {
591 return deviceId;
592 }
593
Saurav Das1547b3f2017-05-05 17:01:08 -0700594 public Objective flowObjective() {
595 return flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700596 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800597
598 @Override
599 public int hashCode() {
Saurav Das1547b3f2017-05-05 17:01:08 -0700600 return Objects.hash(deviceId, flowObj);
Saurav Das8a0732e2015-11-20 15:27:53 -0800601 }
602
603 @Override
604 public boolean equals(final Object obj) {
605 if (this == obj) {
606 return true;
607 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700608 if (!(obj instanceof PendingFlowObjective)) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800609 return false;
610 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700611 final PendingFlowObjective other = (PendingFlowObjective) obj;
Saurav Das8a0732e2015-11-20 15:27:53 -0800612 if (this.deviceId.equals(other.deviceId) &&
Saurav Das1547b3f2017-05-05 17:01:08 -0700613 this.flowObj.equals(other.flowObj)) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800614 return true;
615 }
616 return false;
617 }
alshabibaebe7752015-04-07 17:45:42 -0700618 }
Saurav Das24431192016-03-07 19:13:00 -0800619
620 @Override
621 public List<String> getNextMappings() {
622 List<String> mappings = new ArrayList<>();
623 Map<Integer, NextGroup> allnexts = flowObjectiveStore.getAllGroups();
Saurav Das25190812016-05-27 13:54:07 -0700624 // XXX if the NextGroup after de-serialization actually stored info of the deviceId
Saurav Das24431192016-03-07 19:13:00 -0800625 // then info on any nextObj could be retrieved from one controller instance.
626 // Right now the drivers on one instance can only fetch for next-ids that came
627 // to them.
628 // Also, we still need to send the right next-id to the right driver as potentially
629 // there can be different drivers for different devices. But on that account,
630 // no instance should be decoding for another instance's nextIds.
631
632 for (Map.Entry<Integer, NextGroup> e : allnexts.entrySet()) {
633 // get the device this next Objective was sent to
634 DeviceId deviceId = nextToDevice.get(e.getKey());
635 mappings.add("NextId " + e.getKey() + ": " +
636 ((deviceId != null) ? deviceId : "nextId not in this onos instance"));
637 if (deviceId != null) {
638 // this instance of the controller sent the nextObj to a driver
639 Pipeliner pipeliner = getDevicePipeliner(deviceId);
640 List<String> nextMappings = pipeliner.getNextMappings(e.getValue());
641 if (nextMappings != null) {
642 mappings.addAll(nextMappings);
643 }
644 }
645 }
646 return mappings;
647 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700648
649 @Override
Saurav Das1547b3f2017-05-05 17:01:08 -0700650 public List<String> getPendingFlowObjectives() {
651 List<String> pendingFlowObjectives = new ArrayList<>();
Charles Chan54734712017-03-29 11:07:55 -0700652
Saurav Das1547b3f2017-05-05 17:01:08 -0700653 for (Integer nextId : pendingForwards.keySet()) {
654 Set<PendingFlowObjective> pfwd = pendingForwards.get(nextId);
Sho SHIMIZU81470a52016-08-12 17:24:55 -0700655 StringBuilder pend = new StringBuilder();
Charles Chan54734712017-03-29 11:07:55 -0700656 pend.append("NextId: ")
657 .append(nextId);
Saurav Das1547b3f2017-05-05 17:01:08 -0700658 for (PendingFlowObjective pf : pfwd) {
Charles Chan54734712017-03-29 11:07:55 -0700659 pend.append("\n FwdId: ")
Saurav Das1547b3f2017-05-05 17:01:08 -0700660 .append(String.format("%11s", pf.flowObjective().id()))
661 .append(", DeviceId: ")
662 .append(pf.deviceId())
663 .append(", Selector: ")
664 .append(((ForwardingObjective) pf.flowObjective())
665 .selector().criteria());
666 }
667 pendingFlowObjectives.add(pend.toString());
668 }
669
670 for (Integer nextId : pendingNexts.keySet()) {
Saurav Das9aa28bd2017-12-05 15:00:23 -0800671 List<PendingFlowObjective> pnext = pendingNexts.get(nextId);
Saurav Das1547b3f2017-05-05 17:01:08 -0700672 StringBuilder pend = new StringBuilder();
673 pend.append("NextId: ")
674 .append(nextId);
675 for (PendingFlowObjective pn : pnext) {
676 pend.append("\n NextOp: ")
677 .append(pn.flowObjective().op())
Charles Chan54734712017-03-29 11:07:55 -0700678 .append(", DeviceId: ")
679 .append(pn.deviceId())
Saurav Das1547b3f2017-05-05 17:01:08 -0700680 .append(", Treatments: ")
681 .append(((NextObjective) pn.flowObjective())
682 .next());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700683 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700684 pendingFlowObjectives.add(pend.toString());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700685 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700686
687 return pendingFlowObjectives;
688 }
689
690 @Override
691 public List<String> getPendingNexts() {
692 return getPendingFlowObjectives();
Saurav Dasb5c236e2016-06-07 10:08:06 -0700693 }
alshabib77b88482015-04-07 15:47:50 -0700694}