blob: 4567415cef8ffefcfa15e3746e1c86a14d8bc41b [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.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
Yi Tseng374c5f32017-03-05 22:51:35 -080025import org.apache.felix.scr.annotations.Modified;
26import org.apache.felix.scr.annotations.Property;
alshabib77b88482015-04-07 15:47:50 -070027import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
29import org.apache.felix.scr.annotations.Service;
30import org.onlab.osgi.DefaultServiceDirectory;
31import org.onlab.osgi.ServiceDirectory;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070032import org.onlab.util.ItemNotFoundException;
Yi Tseng374c5f32017-03-05 22:51:35 -080033import org.onlab.util.Tools;
34import org.onosproject.cfg.ComponentConfigService;
alshabib77b88482015-04-07 15:47:50 -070035import org.onosproject.cluster.ClusterService;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070036import org.onosproject.net.Device;
alshabib77b88482015-04-07 15:47:50 -070037import org.onosproject.net.DeviceId;
Saurav Das24431192016-03-07 19:13:00 -080038import org.onosproject.net.behaviour.NextGroup;
alshabib77b88482015-04-07 15:47:50 -070039import org.onosproject.net.behaviour.Pipeliner;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070040import org.onosproject.net.behaviour.PipelinerContext;
alshabibaebe7752015-04-07 17:45:42 -070041import org.onosproject.net.device.DeviceEvent;
42import org.onosproject.net.device.DeviceListener;
alshabib77b88482015-04-07 15:47:50 -070043import org.onosproject.net.device.DeviceService;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070044import org.onosproject.net.driver.DriverEvent;
alshabib77b88482015-04-07 15:47:50 -070045import org.onosproject.net.driver.DriverHandler;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070046import org.onosproject.net.driver.DriverListener;
alshabib77b88482015-04-07 15:47:50 -070047import org.onosproject.net.driver.DriverService;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070048import org.onosproject.net.flow.FlowRuleService;
alshabib77b88482015-04-07 15:47:50 -070049import org.onosproject.net.flowobjective.FilteringObjective;
50import org.onosproject.net.flowobjective.FlowObjectiveService;
alshabib2a441c62015-04-13 18:39:38 -070051import org.onosproject.net.flowobjective.FlowObjectiveStore;
52import org.onosproject.net.flowobjective.FlowObjectiveStoreDelegate;
alshabib77b88482015-04-07 15:47:50 -070053import org.onosproject.net.flowobjective.ForwardingObjective;
54import org.onosproject.net.flowobjective.NextObjective;
alshabib910aff12015-04-09 16:55:57 -070055import org.onosproject.net.flowobjective.Objective;
Saurav Das1547b3f2017-05-05 17:01:08 -070056import org.onosproject.net.flowobjective.Objective.Operation;
Jonathan Hart17d00452015-04-21 17:10:00 -070057import org.onosproject.net.flowobjective.ObjectiveError;
alshabib2a441c62015-04-13 18:39:38 -070058import org.onosproject.net.flowobjective.ObjectiveEvent;
Saurav Das423fe2b2015-12-04 10:52:59 -080059import org.onosproject.net.flowobjective.ObjectiveEvent.Type;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070060import org.onosproject.net.group.GroupService;
Yi Tseng374c5f32017-03-05 22:51:35 -080061import org.osgi.service.component.ComponentContext;
alshabib77b88482015-04-07 15:47:50 -070062import org.slf4j.Logger;
63import org.slf4j.LoggerFactory;
64
Saurav Das24431192016-03-07 19:13:00 -080065import java.util.ArrayList;
Saurav Das24431192016-03-07 19:13:00 -080066import java.util.List;
alshabib77b88482015-04-07 15:47:50 -070067import java.util.Map;
Saurav Das8a0732e2015-11-20 15:27:53 -080068import java.util.Objects;
alshabib2a441c62015-04-13 18:39:38 -070069import java.util.Set;
Jonathan Hart17d00452015-04-21 17:10:00 -070070import java.util.concurrent.ExecutorService;
alshabib77b88482015-04-07 15:47:50 -070071
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -070072import static com.google.common.base.Preconditions.checkNotNull;
Yi Tseng374c5f32017-03-05 22:51:35 -080073import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuska866b46a2015-04-30 00:26:55 -070074import static java.util.concurrent.Executors.newFixedThreadPool;
Jonathan Hart17d00452015-04-21 17:10:00 -070075import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070076import static org.onosproject.net.AnnotationKeys.DRIVER;
Changhoon Yoon541ef712015-05-23 17:18:34 +090077import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskad27097c2016-06-14 19:10:41 -070078import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
alshabib77b88482015-04-07 15:47:50 -070079
80/**
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070081 * Provides implementation of the flow objective programming service.
alshabib77b88482015-04-07 15:47:50 -070082 */
Charles Chana7903c82018-03-15 20:14:16 -070083@Component(enabled = false)
alshabib77b88482015-04-07 15:47:50 -070084@Service
85public class FlowObjectiveManager implements FlowObjectiveService {
86
Charles Chana7903c82018-03-15 20:14:16 -070087 private static final int INSTALL_RETRY_ATTEMPTS = 5;
88 private static final long INSTALL_RETRY_INTERVAL = 1000; // ms
alshabib77b88482015-04-07 15:47:50 -070089
Yi Tseng374c5f32017-03-05 22:51:35 -080090 private static final String WORKER_PATTERN = "objective-installer-%d";
91 private static final String GROUP_THREAD_NAME = "onos/objective-installer";
92 private static final String NUM_THREAD = "numThreads";
93
Jonathan Hart17d00452015-04-21 17:10:00 -070094 private final Logger log = LoggerFactory.getLogger(getClass());
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070095
Yi Tseng9753fc12017-03-10 18:42:46 -080096 private static final int DEFAULT_NUM_THREADS = 4;
Yi Tseng374c5f32017-03-05 22:51:35 -080097 @Property(name = NUM_THREAD,
98 intValue = DEFAULT_NUM_THREADS,
99 label = "Number of worker threads")
100 private int numThreads = DEFAULT_NUM_THREADS;
101
alshabib77b88482015-04-07 15:47:50 -0700102 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
103 protected DriverService driverService;
104
105 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
106 protected DeviceService deviceService;
107
108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
alshabib77b88482015-04-07 15:47:50 -0700109 protected ClusterService clusterService;
110
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700111 // Note: The following dependencies are added on behalf of the pipeline
112 // driver behaviours to assure these services are available for their
113 // initialization.
Charles Chana7903c82018-03-15 20:14:16 -0700114 @SuppressWarnings("unused")
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700115 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
116 protected FlowRuleService flowRuleService;
117
Charles Chana7903c82018-03-15 20:14:16 -0700118 @SuppressWarnings("unused")
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
120 protected GroupService groupService;
121
alshabib2a441c62015-04-13 18:39:38 -0700122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
123 protected FlowObjectiveStore flowObjectiveStore;
124
Yi Tseng374c5f32017-03-05 22:51:35 -0800125 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
126 protected ComponentConfigService cfgService;
127
Charles Chana7903c82018-03-15 20:14:16 -0700128 final FlowObjectiveStoreDelegate delegate = new InternalStoreDelegate();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700129
130 private final Map<DeviceId, DriverHandler> driverHandlers = Maps.newConcurrentMap();
Charles Chana7903c82018-03-15 20:14:16 -0700131 protected final Map<DeviceId, Pipeliner> pipeliners = Maps.newConcurrentMap();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700132
133 private final PipelinerContext context = new InnerPipelineContext();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700134 private final DeviceListener deviceListener = new InnerDeviceListener();
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700135 private final DriverListener driverListener = new InnerDriverListener();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700136
Charles Chana7903c82018-03-15 20:14:16 -0700137 private ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
alshabib910aff12015-04-09 16:55:57 -0700138
Saurav Das1547b3f2017-05-05 17:01:08 -0700139 // local stores for queuing fwd and next objectives that are waiting for an
140 // associated next objective execution to complete. The signal for completed
141 // execution comes from a pipeline driver, in this or another controller
142 // instance, via the DistributedFlowObjectiveStore.
Charles Chana7903c82018-03-15 20:14:16 -0700143 // TODO Making these cache and timeout the entries
144 final Map<Integer, Set<PendingFlowObjective>> pendingForwards = Maps.newConcurrentMap();
145 final Map<Integer, List<PendingFlowObjective>> pendingNexts = Maps.newConcurrentMap();
alshabib2a441c62015-04-13 18:39:38 -0700146
Saurav Das24431192016-03-07 19:13:00 -0800147 // local store to track which nextObjectives were sent to which device
148 // for debugging purposes
149 private Map<Integer, DeviceId> nextToDevice = Maps.newConcurrentMap();
150
Charles Chana7903c82018-03-15 20:14:16 -0700151 ExecutorService executorService;
alshabib2a441c62015-04-13 18:39:38 -0700152
alshabib77b88482015-04-07 15:47:50 -0700153 @Activate
154 protected void activate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800155 cfgService.registerProperties(getClass());
156 executorService = newFixedThreadPool(numThreads,
157 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
alshabib2a441c62015-04-13 18:39:38 -0700158 flowObjectiveStore.setDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700159 deviceService.addListener(deviceListener);
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700160 driverService.addListener(driverListener);
alshabib77b88482015-04-07 15:47:50 -0700161 log.info("Started");
162 }
163
164 @Deactivate
165 protected void deactivate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800166 cfgService.unregisterProperties(getClass(), false);
alshabib2a441c62015-04-13 18:39:38 -0700167 flowObjectiveStore.unsetDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700168 deviceService.removeListener(deviceListener);
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700169 driverService.removeListener(driverListener);
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700170 executorService.shutdown();
171 pipeliners.clear();
172 driverHandlers.clear();
Saurav Das24431192016-03-07 19:13:00 -0800173 nextToDevice.clear();
alshabib77b88482015-04-07 15:47:50 -0700174 log.info("Stopped");
175 }
176
Yi Tseng374c5f32017-03-05 22:51:35 -0800177 @Modified
178 protected void modified(ComponentContext context) {
179 String propertyValue =
180 Tools.get(context.getProperties(), NUM_THREAD);
181 int newNumThreads = isNullOrEmpty(propertyValue) ? numThreads : Integer.parseInt(propertyValue);
182
183 if (newNumThreads != numThreads && newNumThreads > 0) {
184 numThreads = newNumThreads;
185 ExecutorService oldWorkerExecutor = executorService;
186 executorService = newFixedThreadPool(numThreads,
187 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
188 if (oldWorkerExecutor != null) {
189 oldWorkerExecutor.shutdown();
190 }
191 log.info("Reconfigured number of worker threads to {}", numThreads);
192 }
193 }
194
Jonathan Hart17d00452015-04-21 17:10:00 -0700195 /**
196 * Task that passes the flow objective down to the driver. The task will
197 * make a few attempts to find the appropriate driver, then eventually give
198 * up and report an error if no suitable driver could be found.
199 */
Charles Chana7903c82018-03-15 20:14:16 -0700200 class ObjectiveInstaller implements Runnable {
201 final DeviceId deviceId;
202 final Objective objective;
Jonathan Hart17d00452015-04-21 17:10:00 -0700203
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700204 private final int numAttempts;
Jonathan Hart17d00452015-04-21 17:10:00 -0700205
Charles Chana7903c82018-03-15 20:14:16 -0700206 ObjectiveInstaller(DeviceId deviceId, Objective objective) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700207 this(deviceId, objective, 1);
208 }
209
Charles Chana7903c82018-03-15 20:14:16 -0700210 ObjectiveInstaller(DeviceId deviceId, Objective objective, int attemps) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700211 this.deviceId = checkNotNull(deviceId);
212 this.objective = checkNotNull(objective);
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800213 this.numAttempts = attemps;
alshabib910aff12015-04-09 16:55:57 -0700214 }
alshabib77b88482015-04-07 15:47:50 -0700215
Jonathan Hart17d00452015-04-21 17:10:00 -0700216 @Override
217 public void run() {
218 try {
Jonathan Hart17d00452015-04-21 17:10:00 -0700219 Pipeliner pipeliner = getDevicePipeliner(deviceId);
220
221 if (pipeliner != null) {
222 if (objective instanceof NextObjective) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700223 nextToDevice.put(objective.id(), deviceId);
Jonathan Hart17d00452015-04-21 17:10:00 -0700224 pipeliner.next((NextObjective) objective);
225 } else if (objective instanceof ForwardingObjective) {
226 pipeliner.forward((ForwardingObjective) objective);
227 } else {
228 pipeliner.filter((FilteringObjective) objective);
229 }
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800230 //Attempts to check if pipeliner is null for retry attempts
Jonathan Hart17d00452015-04-21 17:10:00 -0700231 } else if (numAttempts < INSTALL_RETRY_ATTEMPTS) {
Saurav Das3d038262015-04-23 12:36:58 -0700232 Thread.sleep(INSTALL_RETRY_INTERVAL);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700233 executorService.execute(new ObjectiveInstaller(deviceId, objective, numAttempts + 1));
Jonathan Hart17d00452015-04-21 17:10:00 -0700234 } else {
235 // Otherwise we've tried a few times and failed, report an
236 // error back to the user.
237 objective.context().ifPresent(
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800238 c -> c.onError(objective, ObjectiveError.NOPIPELINER));
Jonathan Hart17d00452015-04-21 17:10:00 -0700239 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700240 //Exception thrown
Jonathan Hart17d00452015-04-21 17:10:00 -0700241 } catch (Exception e) {
242 log.warn("Exception while installing flow objective", e);
243 }
244 }
245 }
246
247 @Override
248 public void filter(DeviceId deviceId, FilteringObjective filteringObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900249 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700250 executorService.execute(new ObjectiveInstaller(deviceId, filteringObjective));
alshabib77b88482015-04-07 15:47:50 -0700251 }
252
253 @Override
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700254 public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900255 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700256 if (forwardingObjective.nextId() == null ||
Yi Tseng1666b502017-05-17 11:05:18 -0700257 flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null ||
258 !queueFwdObjective(deviceId, forwardingObjective)) {
259 // fast path
260 executorService.execute(new ObjectiveInstaller(deviceId, forwardingObjective));
alshabib910aff12015-04-09 16:55:57 -0700261 }
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700262 }
263
alshabib2a441c62015-04-13 18:39:38 -0700264 @Override
Jonathan Hart17d00452015-04-21 17:10:00 -0700265 public void next(DeviceId deviceId, NextObjective nextObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900266 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700267 if (nextObjective.op() == Operation.ADD ||
Charles Chanb71e1ba2018-08-16 21:02:34 -0700268 nextObjective.op() == Operation.VERIFY ||
Yi Tseng1666b502017-05-17 11:05:18 -0700269 flowObjectiveStore.getNextGroup(nextObjective.id()) != null ||
270 !queueNextObjective(deviceId, nextObjective)) {
271 // either group exists or we are trying to create it - let it through
272 executorService.execute(new ObjectiveInstaller(deviceId, nextObjective));
Saurav Das1547b3f2017-05-05 17:01:08 -0700273 }
alshabib2a441c62015-04-13 18:39:38 -0700274 }
275
alshabibf6ea9e62015-04-21 17:08:26 -0700276 @Override
277 public int allocateNextId() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900278 checkPermission(FLOWRULE_WRITE);
alshabibf6ea9e62015-04-21 17:08:26 -0700279 return flowObjectiveStore.allocateNextId();
280 }
281
Xin Jin313708b2015-07-09 13:43:04 -0700282 @Override
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700283 public void initPolicy(String policy) {
284 }
Xin Jin313708b2015-07-09 13:43:04 -0700285
Charles Chana7903c82018-03-15 20:14:16 -0700286 boolean queueFwdObjective(DeviceId deviceId, ForwardingObjective fwd) {
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700287 boolean queued = false;
288 synchronized (pendingForwards) {
289 // double check the flow objective store, because this block could run
290 // after a notification arrives
291 if (flowObjectiveStore.getNextGroup(fwd.nextId()) == null) {
292 pendingForwards.compute(fwd.nextId(), (id, pending) -> {
Saurav Das1547b3f2017-05-05 17:01:08 -0700293 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, fwd);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700294 if (pending == null) {
Pier Luigi97893112018-03-05 11:09:42 +0100295 return Sets.newLinkedHashSet(ImmutableSet.of(pendfo));
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700296 } else {
Saurav Das1547b3f2017-05-05 17:01:08 -0700297 pending.add(pendfo);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700298 return pending;
299 }
300 });
301 queued = true;
302 }
303 }
304 if (queued) {
Saurav Dasc568c342018-01-25 09:49:01 -0800305 log.debug("Queued forwarding objective {} for nextId {} meant for device {}",
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700306 fwd.id(), fwd.nextId(), deviceId);
307 }
308 return queued;
alshabib2a441c62015-04-13 18:39:38 -0700309 }
310
Charles Chana7903c82018-03-15 20:14:16 -0700311 boolean queueNextObjective(DeviceId deviceId, NextObjective next) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700312 // we need to hold off on other operations till we get notified that the
313 // initial group creation has succeeded
314 boolean queued = false;
315 synchronized (pendingNexts) {
316 // double check the flow objective store, because this block could run
317 // after a notification arrives
318 if (flowObjectiveStore.getNextGroup(next.id()) == null) {
319 pendingNexts.compute(next.id(), (id, pending) -> {
320 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, next);
321 if (pending == null) {
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800322 return Lists.newArrayList(pendfo);
Saurav Das1547b3f2017-05-05 17:01:08 -0700323 } else {
324 pending.add(pendfo);
325 return pending;
326 }
327 });
328 queued = true;
329 }
330 }
331 if (queued) {
Saurav Dasc568c342018-01-25 09:49:01 -0800332 log.debug("Queued next objective {} with operation {} meant for device {}",
Saurav Das1547b3f2017-05-05 17:01:08 -0700333 next.id(), next.op(), deviceId);
334 }
335 return queued;
336 }
337
Pier Ventre57a61cd2016-09-07 10:55:41 -0700338 /**
339 * Retrieves (if it exists) the device pipeline behaviour from the cache.
340 * Otherwise it warms the caches and triggers the init method of the Pipeline.
341 *
342 * @param deviceId the id of the device associated to the pipeline
343 * @return the implementation of the Pipeliner behaviour
344 */
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700345 private Pipeliner getDevicePipeliner(DeviceId deviceId) {
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700346 return pipeliners.computeIfAbsent(deviceId, this::initPipelineHandler);
alshabib77b88482015-04-07 15:47:50 -0700347 }
348
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700349 /**
Pier Ventre57a61cd2016-09-07 10:55:41 -0700350 * Retrieves (if it exists) the device pipeline behaviour from the cache and
351 * and triggers the init method of the pipeline. Otherwise (DEVICE_ADDED) it warms
352 * the caches and triggers the init method of the Pipeline. The rationale of this
353 * method is for managing the scenario of a switch that goes down for a failure
354 * and goes up after a while.
355 *
356 * @param deviceId the id of the device associated to the pipeline
357 * @return the implementation of the Pipeliner behaviour
358 */
359 private Pipeliner getAndInitDevicePipeliner(DeviceId deviceId) {
360 return pipeliners.compute(deviceId, (deviceIdValue, pipelinerValue) -> {
361 if (pipelinerValue != null) {
362 pipelinerValue.init(deviceId, context);
363 return pipelinerValue;
364 }
365 return this.initPipelineHandler(deviceId);
366 });
367 }
368
369 /**
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700370 * Creates and initialize {@link Pipeliner}.
371 * <p>
372 * Note: Expected to be called under per-Device lock.
373 * e.g., {@code pipeliners}' Map#compute family methods
374 *
375 * @param deviceId Device to initialize pipeliner
376 * @return {@link Pipeliner} instance or null
377 */
378 private Pipeliner initPipelineHandler(DeviceId deviceId) {
379 start = now();
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700380
Jonathan Hart17d00452015-04-21 17:10:00 -0700381 // Attempt to lookup the handler in the cache
382 DriverHandler handler = driverHandlers.get(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700383 cTime = now();
384
Jonathan Hart17d00452015-04-21 17:10:00 -0700385 if (handler == null) {
386 try {
387 // Otherwise create it and if it has pipeline behaviour, cache it
388 handler = driverService.createHandler(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700389 dTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700390 if (!handler.driver().hasBehaviour(Pipeliner.class)) {
Yuta HIGUCHIa2a4f342017-03-17 11:38:57 -0700391 log.debug("Pipeline behaviour not supported for device {}",
Jonathan Hart17d00452015-04-21 17:10:00 -0700392 deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700393 return null;
alshabib2a441c62015-04-13 18:39:38 -0700394 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700395 } catch (ItemNotFoundException e) {
396 log.warn("No applicable driver for device {}", deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700397 return null;
alshabib2a441c62015-04-13 18:39:38 -0700398 }
399
Jonathan Hart17d00452015-04-21 17:10:00 -0700400 driverHandlers.put(deviceId, handler);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700401 eTime = now();
alshabib2a441c62015-04-13 18:39:38 -0700402 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700403
404 // Always (re)initialize the pipeline behaviour
405 log.info("Driver {} bound to device {} ... initializing driver",
406 handler.driver().name(), deviceId);
Thomas Vachuska0121a612015-07-21 11:18:09 -0700407 hTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700408 Pipeliner pipeliner = handler.behaviour(Pipeliner.class);
Thomas Vachuska94c3cf42015-07-20 13:01:12 -0700409 hbTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700410 pipeliner.init(deviceId, context);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700411 stopWatch();
412 return pipeliner;
alshabibaebe7752015-04-07 17:45:42 -0700413 }
alshabib77b88482015-04-07 15:47:50 -0700414
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700415 private void invalidatePipelinerIfNecessary(Device device) {
416 DriverHandler handler = driverHandlers.get(device.id());
417 if (handler != null &&
418 !Objects.equals(handler.driver().name(),
419 device.annotations().value(DRIVER))) {
420 invalidatePipeliner(device.id());
421 }
422 }
423
424 private void invalidatePipeliner(DeviceId id) {
425 log.info("Invalidating cached pipeline behaviour for {}", id);
426 driverHandlers.remove(id);
427 pipeliners.remove(id);
428 if (deviceService.isAvailable(id)) {
429 getAndInitDevicePipeliner(id);
430 }
431 }
432
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700433 // Triggers driver setup when a device is (re)detected.
alshabibaebe7752015-04-07 17:45:42 -0700434 private class InnerDeviceListener implements DeviceListener {
435 @Override
436 public void event(DeviceEvent event) {
437 switch (event.type()) {
438 case DEVICE_ADDED:
439 case DEVICE_AVAILABILITY_CHANGED:
Madan Jampani0174f452015-05-29 11:52:05 -0700440 log.debug("Device either added or availability changed {}",
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700441 event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700442 if (deviceService.isAvailable(event.subject().id())) {
Madan Jampani0174f452015-05-29 11:52:05 -0700443 log.debug("Device is now available {}", event.subject().id());
Pier Ventre57a61cd2016-09-07 10:55:41 -0700444 getAndInitDevicePipeliner(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700445 } else {
446 log.debug("Device is no longer available {}", event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700447 }
448 break;
449 case DEVICE_UPDATED:
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700450 // Invalidate pipeliner and handler caches if the driver name
451 // device annotation changed.
452 invalidatePipelinerIfNecessary(event.subject());
alshabib4313d102015-04-08 18:55:08 -0700453 break;
454 case DEVICE_REMOVED:
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700455 // evict Pipeliner and Handler cache, when
456 // the Device was administratively removed.
457 //
458 // System expect the user to clear all existing flows,
459 // before removing device, especially if they intend to
460 // replace driver/pipeliner assigned to the device.
461 driverHandlers.remove(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700462 pipeliners.remove(event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700463 break;
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700464 case DEVICE_SUSPENDED:
465 break;
alshabib4313d102015-04-08 18:55:08 -0700466 case PORT_ADDED:
467 break;
468 case PORT_UPDATED:
469 break;
470 case PORT_REMOVED:
alshabibaebe7752015-04-07 17:45:42 -0700471 break;
472 default:
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700473 break;
alshabibaebe7752015-04-07 17:45:42 -0700474 }
alshabib77b88482015-04-07 15:47:50 -0700475 }
476 }
alshabibaebe7752015-04-07 17:45:42 -0700477
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700478 // Monitors driver configuration changes and invalidates the pipeliner cache entries.
479 // Note that this may leave stale entries on the device if the driver changes
480 // in manner where the new driver does not produce backward compatible flow objectives.
481 // In such cases, it is the operator's responsibility to force device re-connect.
482 private class InnerDriverListener implements DriverListener {
483 @Override
484 public void event(DriverEvent event) {
485 String driverName = event.subject().name();
486 driverHandlers.entrySet().stream()
487 .filter(e -> driverName.equals(e.getValue().driver().name()))
488 .map(Map.Entry::getKey)
489 .distinct()
490 .forEach(FlowObjectiveManager.this::invalidatePipeliner);
491 }
492 }
493
Thomas Vachuska174bb912015-07-16 21:27:14 -0700494 // Temporary mechanism to monitor pipeliner setup time-cost; there are
495 // intermittent time where this takes in excess of 2 seconds. Why?
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700496 private long start = 0, totals = 0, count = 0;
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700497 private long cTime, dTime, eTime, hTime, hbTime;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700498 private static final long LIMIT = 500;
Thomas Vachuska174bb912015-07-16 21:27:14 -0700499
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700500 private long now() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700501 return System.currentTimeMillis();
502 }
503
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700504 private void stopWatch() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700505 long duration = System.currentTimeMillis() - start;
506 totals += duration;
507 count += 1;
508 if (duration > LIMIT) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700509 log.info("Pipeline setup took {} ms; avg {} ms; cTime={}, dTime={}, eTime={}, hTime={}, hbTime={}",
510 duration, totals / count, diff(cTime), diff(dTime), diff(eTime), diff(hTime), diff(hbTime));
Thomas Vachuska174bb912015-07-16 21:27:14 -0700511 }
512 }
513
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700514 private long diff(long bTime) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700515 long diff = bTime - start;
516 return diff < 0 ? 0 : diff;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700517 }
518
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700519 // Processing context for initializing pipeline driver behaviours.
520 private class InnerPipelineContext implements PipelinerContext {
521 @Override
522 public ServiceDirectory directory() {
523 return serviceDirectory;
alshabibaebe7752015-04-07 17:45:42 -0700524 }
alshabib2a441c62015-04-13 18:39:38 -0700525
526 @Override
527 public FlowObjectiveStore store() {
528 return flowObjectiveStore;
529 }
alshabib2a441c62015-04-13 18:39:38 -0700530 }
531
532 private class InternalStoreDelegate implements FlowObjectiveStoreDelegate {
533 @Override
534 public void notify(ObjectiveEvent event) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800535 if (event.type() == Type.ADD) {
536 log.debug("Received notification of obj event {}", event);
Saurav Das1547b3f2017-05-05 17:01:08 -0700537 Set<PendingFlowObjective> pending;
538
539 // first send all pending flows
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700540 synchronized (pendingForwards) {
541 // needs to be synchronized for queueObjective lookup
542 pending = pendingForwards.remove(event.subject());
543 }
Saurav Das423fe2b2015-12-04 10:52:59 -0800544 if (pending == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700545 log.debug("No forwarding objectives pending for this "
546 + "obj event {}", event);
547 } else {
548 log.debug("Processing {} pending forwarding objectives for nextId {}",
549 pending.size(), event.subject());
550 pending.forEach(p -> getDevicePipeliner(p.deviceId())
551 .forward((ForwardingObjective) p.flowObjective()));
Saurav Das423fe2b2015-12-04 10:52:59 -0800552 }
553
Saurav Das1547b3f2017-05-05 17:01:08 -0700554 // now check for pending next-objectives
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800555 List<PendingFlowObjective> pendNexts;
Saurav Das1547b3f2017-05-05 17:01:08 -0700556 synchronized (pendingNexts) {
557 // needs to be synchronized for queueObjective lookup
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800558 pendNexts = pendingNexts.remove(event.subject());
Saurav Das1547b3f2017-05-05 17:01:08 -0700559 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800560 if (pendNexts == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700561 log.debug("No next objectives pending for this "
562 + "obj event {}", event);
563 } else {
564 log.debug("Processing {} pending next objectives for nextId {}",
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800565 pendNexts.size(), event.subject());
566 pendNexts.forEach(p -> getDevicePipeliner(p.deviceId())
Saurav Das1547b3f2017-05-05 17:01:08 -0700567 .next((NextObjective) p.flowObjective()));
568 }
alshabib2a441c62015-04-13 18:39:38 -0700569 }
alshabib2a441c62015-04-13 18:39:38 -0700570 }
571 }
572
573 /**
Saurav Das1547b3f2017-05-05 17:01:08 -0700574 * Data class used to hold a pending flow objective that could not
alshabib2a441c62015-04-13 18:39:38 -0700575 * be processed because the associated next object was not present.
Saurav Das1547b3f2017-05-05 17:01:08 -0700576 * Note that this pending flow objective could be a forwarding objective
577 * waiting for a next objective to complete execution. Or it could a
578 * next objective (with a different operation - remove, addToExisting, or
579 * removeFromExisting) waiting for a next objective with the same id to
580 * complete execution.
alshabib2a441c62015-04-13 18:39:38 -0700581 */
Charles Chana7903c82018-03-15 20:14:16 -0700582 protected class PendingFlowObjective {
alshabib2a441c62015-04-13 18:39:38 -0700583 private final DeviceId deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700584 private final Objective flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700585
Charles Chana7903c82018-03-15 20:14:16 -0700586 PendingFlowObjective(DeviceId deviceId, Objective flowObj) {
alshabib2a441c62015-04-13 18:39:38 -0700587 this.deviceId = deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700588 this.flowObj = flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700589 }
590
591 public DeviceId deviceId() {
592 return deviceId;
593 }
594
Saurav Das1547b3f2017-05-05 17:01:08 -0700595 public Objective flowObjective() {
596 return flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700597 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800598
599 @Override
600 public int hashCode() {
Saurav Das1547b3f2017-05-05 17:01:08 -0700601 return Objects.hash(deviceId, flowObj);
Saurav Das8a0732e2015-11-20 15:27:53 -0800602 }
603
604 @Override
605 public boolean equals(final Object obj) {
606 if (this == obj) {
607 return true;
608 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700609 if (!(obj instanceof PendingFlowObjective)) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800610 return false;
611 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700612 final PendingFlowObjective other = (PendingFlowObjective) obj;
Charles Chana7903c82018-03-15 20:14:16 -0700613
614 return this.deviceId.equals(other.deviceId) &&
615 this.flowObj.equals(other.flowObj);
Saurav Das8a0732e2015-11-20 15:27:53 -0800616 }
alshabibaebe7752015-04-07 17:45:42 -0700617 }
Saurav Das24431192016-03-07 19:13:00 -0800618
619 @Override
620 public List<String> getNextMappings() {
621 List<String> mappings = new ArrayList<>();
622 Map<Integer, NextGroup> allnexts = flowObjectiveStore.getAllGroups();
Saurav Das25190812016-05-27 13:54:07 -0700623 // XXX if the NextGroup after de-serialization actually stored info of the deviceId
Saurav Das24431192016-03-07 19:13:00 -0800624 // then info on any nextObj could be retrieved from one controller instance.
625 // Right now the drivers on one instance can only fetch for next-ids that came
626 // to them.
627 // Also, we still need to send the right next-id to the right driver as potentially
628 // there can be different drivers for different devices. But on that account,
629 // no instance should be decoding for another instance's nextIds.
630
631 for (Map.Entry<Integer, NextGroup> e : allnexts.entrySet()) {
632 // get the device this next Objective was sent to
633 DeviceId deviceId = nextToDevice.get(e.getKey());
634 mappings.add("NextId " + e.getKey() + ": " +
635 ((deviceId != null) ? deviceId : "nextId not in this onos instance"));
636 if (deviceId != null) {
637 // this instance of the controller sent the nextObj to a driver
638 Pipeliner pipeliner = getDevicePipeliner(deviceId);
639 List<String> nextMappings = pipeliner.getNextMappings(e.getValue());
640 if (nextMappings != null) {
641 mappings.addAll(nextMappings);
642 }
643 }
644 }
645 return mappings;
646 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700647
648 @Override
Saurav Das1547b3f2017-05-05 17:01:08 -0700649 public List<String> getPendingFlowObjectives() {
650 List<String> pendingFlowObjectives = new ArrayList<>();
Charles Chan54734712017-03-29 11:07:55 -0700651
Saurav Das1547b3f2017-05-05 17:01:08 -0700652 for (Integer nextId : pendingForwards.keySet()) {
653 Set<PendingFlowObjective> pfwd = pendingForwards.get(nextId);
Sho SHIMIZU81470a52016-08-12 17:24:55 -0700654 StringBuilder pend = new StringBuilder();
Charles Chan54734712017-03-29 11:07:55 -0700655 pend.append("NextId: ")
656 .append(nextId);
Saurav Das1547b3f2017-05-05 17:01:08 -0700657 for (PendingFlowObjective pf : pfwd) {
Charles Chan54734712017-03-29 11:07:55 -0700658 pend.append("\n FwdId: ")
Saurav Das1547b3f2017-05-05 17:01:08 -0700659 .append(String.format("%11s", pf.flowObjective().id()))
660 .append(", DeviceId: ")
661 .append(pf.deviceId())
662 .append(", Selector: ")
663 .append(((ForwardingObjective) pf.flowObjective())
664 .selector().criteria());
665 }
666 pendingFlowObjectives.add(pend.toString());
667 }
668
669 for (Integer nextId : pendingNexts.keySet()) {
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800670 List<PendingFlowObjective> pnext = pendingNexts.get(nextId);
Saurav Das1547b3f2017-05-05 17:01:08 -0700671 StringBuilder pend = new StringBuilder();
672 pend.append("NextId: ")
673 .append(nextId);
674 for (PendingFlowObjective pn : pnext) {
675 pend.append("\n NextOp: ")
676 .append(pn.flowObjective().op())
Charles Chan54734712017-03-29 11:07:55 -0700677 .append(", DeviceId: ")
678 .append(pn.deviceId())
Saurav Das1547b3f2017-05-05 17:01:08 -0700679 .append(", Treatments: ")
680 .append(((NextObjective) pn.flowObjective())
681 .next());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700682 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700683 pendingFlowObjectives.add(pend.toString());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700684 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700685
686 return pendingFlowObjectives;
687 }
alshabib77b88482015-04-07 15:47:50 -0700688}