blob: 45e2e95d973041c625da6286305787f9e00e8385 [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;
Jonathan Hart17d00452015-04-21 17:10:00 -070073import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskacfeff192017-08-23 15:29:34 -070074import static org.onosproject.net.AnnotationKeys.DRIVER;
Ray Milkeyd04e2272018-10-16 18:20:18 -070075import static org.onosproject.net.OsgiPropertyConstants.FOM_NUM_THREADS;
76import static org.onosproject.net.OsgiPropertyConstants.FOM_NUM_THREADS_DEFAULT;
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 */
Ray Milkeyd04e2272018-10-16 18:20:18 -070083@Component(
84 enabled = false,
85 service = FlowObjectiveService.class,
86 property = {
Ray Milkey2d7bca12018-10-17 14:51:52 -070087 FOM_NUM_THREADS + ":Integer=" + FOM_NUM_THREADS_DEFAULT
Ray Milkeyd04e2272018-10-16 18:20:18 -070088 }
89)
alshabib77b88482015-04-07 15:47:50 -070090public class FlowObjectiveManager implements FlowObjectiveService {
91
Charles Chana7903c82018-03-15 20:14:16 -070092 private static final int INSTALL_RETRY_ATTEMPTS = 5;
93 private static final long INSTALL_RETRY_INTERVAL = 1000; // ms
alshabib77b88482015-04-07 15:47:50 -070094
Yi Tseng374c5f32017-03-05 22:51:35 -080095 private static final String WORKER_PATTERN = "objective-installer-%d";
96 private static final String GROUP_THREAD_NAME = "onos/objective-installer";
Yi Tseng374c5f32017-03-05 22:51:35 -080097
Jonathan Hart17d00452015-04-21 17:10:00 -070098 private final Logger log = LoggerFactory.getLogger(getClass());
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070099
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700100 /** Number of worker threads. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700101 private int numThreads = FOM_NUM_THREADS_DEFAULT;
Yi Tseng374c5f32017-03-05 22:51:35 -0800102
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700103 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib77b88482015-04-07 15:47:50 -0700104 protected DriverService driverService;
105
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700106 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib77b88482015-04-07 15:47:50 -0700107 protected DeviceService deviceService;
108
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700109 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib77b88482015-04-07 15:47:50 -0700110 protected ClusterService clusterService;
111
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700112 // Note: The following dependencies are added on behalf of the pipeline
113 // driver behaviours to assure these services are available for their
114 // initialization.
Charles Chana7903c82018-03-15 20:14:16 -0700115 @SuppressWarnings("unused")
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700116 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700117 protected FlowRuleService flowRuleService;
118
Charles Chana7903c82018-03-15 20:14:16 -0700119 @SuppressWarnings("unused")
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700120 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700121 protected GroupService groupService;
122
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700123 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabib2a441c62015-04-13 18:39:38 -0700124 protected FlowObjectiveStore flowObjectiveStore;
125
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700126 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng374c5f32017-03-05 22:51:35 -0800127 protected ComponentConfigService cfgService;
128
Charles Chana7903c82018-03-15 20:14:16 -0700129 final FlowObjectiveStoreDelegate delegate = new InternalStoreDelegate();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700130
131 private final Map<DeviceId, DriverHandler> driverHandlers = Maps.newConcurrentMap();
Charles Chana7903c82018-03-15 20:14:16 -0700132 protected final Map<DeviceId, Pipeliner> pipeliners = Maps.newConcurrentMap();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700133
134 private final PipelinerContext context = new InnerPipelineContext();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700135 private final DeviceListener deviceListener = new InnerDeviceListener();
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700136 private final DriverListener driverListener = new InnerDriverListener();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700137
Charles Chana7903c82018-03-15 20:14:16 -0700138 private ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
alshabib910aff12015-04-09 16:55:57 -0700139
Saurav Das1547b3f2017-05-05 17:01:08 -0700140 // local stores for queuing fwd and next objectives that are waiting for an
141 // associated next objective execution to complete. The signal for completed
142 // execution comes from a pipeline driver, in this or another controller
143 // instance, via the DistributedFlowObjectiveStore.
Charles Chana7903c82018-03-15 20:14:16 -0700144 // TODO Making these cache and timeout the entries
145 final Map<Integer, Set<PendingFlowObjective>> pendingForwards = Maps.newConcurrentMap();
146 final Map<Integer, List<PendingFlowObjective>> pendingNexts = Maps.newConcurrentMap();
alshabib2a441c62015-04-13 18:39:38 -0700147
Saurav Das24431192016-03-07 19:13:00 -0800148 // local store to track which nextObjectives were sent to which device
149 // for debugging purposes
150 private Map<Integer, DeviceId> nextToDevice = Maps.newConcurrentMap();
151
Charles Chana7903c82018-03-15 20:14:16 -0700152 ExecutorService executorService;
alshabib2a441c62015-04-13 18:39:38 -0700153
alshabib77b88482015-04-07 15:47:50 -0700154 @Activate
155 protected void activate() {
Ray Milkey1f0764a2019-03-01 08:40:37 -0800156 cfgService.registerProperties(FlowObjectiveManager.class);
Yi Tseng374c5f32017-03-05 22:51:35 -0800157 executorService = newFixedThreadPool(numThreads,
158 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
alshabib2a441c62015-04-13 18:39:38 -0700159 flowObjectiveStore.setDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700160 deviceService.addListener(deviceListener);
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700161 driverService.addListener(driverListener);
alshabib77b88482015-04-07 15:47:50 -0700162 log.info("Started");
163 }
164
165 @Deactivate
166 protected void deactivate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800167 cfgService.unregisterProperties(getClass(), false);
alshabib2a441c62015-04-13 18:39:38 -0700168 flowObjectiveStore.unsetDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700169 deviceService.removeListener(deviceListener);
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700170 driverService.removeListener(driverListener);
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700171 executorService.shutdown();
172 pipeliners.clear();
173 driverHandlers.clear();
Saurav Das24431192016-03-07 19:13:00 -0800174 nextToDevice.clear();
alshabib77b88482015-04-07 15:47:50 -0700175 log.info("Stopped");
176 }
177
Yi Tseng374c5f32017-03-05 22:51:35 -0800178 @Modified
179 protected void modified(ComponentContext context) {
180 String propertyValue =
Ray Milkey1f0764a2019-03-01 08:40:37 -0800181 Tools.get(context.getProperties(), FOM_NUM_THREADS);
Yi Tseng374c5f32017-03-05 22:51:35 -0800182 int newNumThreads = isNullOrEmpty(propertyValue) ? numThreads : Integer.parseInt(propertyValue);
183
184 if (newNumThreads != numThreads && newNumThreads > 0) {
185 numThreads = newNumThreads;
186 ExecutorService oldWorkerExecutor = executorService;
187 executorService = newFixedThreadPool(numThreads,
188 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
189 if (oldWorkerExecutor != null) {
190 oldWorkerExecutor.shutdown();
191 }
192 log.info("Reconfigured number of worker threads to {}", numThreads);
193 }
194 }
195
Jonathan Hart17d00452015-04-21 17:10:00 -0700196 /**
197 * Task that passes the flow objective down to the driver. The task will
198 * make a few attempts to find the appropriate driver, then eventually give
199 * up and report an error if no suitable driver could be found.
200 */
Charles Chana7903c82018-03-15 20:14:16 -0700201 class ObjectiveInstaller implements Runnable {
202 final DeviceId deviceId;
203 final Objective objective;
Jonathan Hart17d00452015-04-21 17:10:00 -0700204
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700205 private final int numAttempts;
Jonathan Hart17d00452015-04-21 17:10:00 -0700206
Charles Chana7903c82018-03-15 20:14:16 -0700207 ObjectiveInstaller(DeviceId deviceId, Objective objective) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700208 this(deviceId, objective, 1);
209 }
210
Charles Chana7903c82018-03-15 20:14:16 -0700211 ObjectiveInstaller(DeviceId deviceId, Objective objective, int attemps) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700212 this.deviceId = checkNotNull(deviceId);
213 this.objective = checkNotNull(objective);
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800214 this.numAttempts = attemps;
alshabib910aff12015-04-09 16:55:57 -0700215 }
alshabib77b88482015-04-07 15:47:50 -0700216
Jonathan Hart17d00452015-04-21 17:10:00 -0700217 @Override
218 public void run() {
219 try {
Jonathan Hart17d00452015-04-21 17:10:00 -0700220 Pipeliner pipeliner = getDevicePipeliner(deviceId);
221
222 if (pipeliner != null) {
223 if (objective instanceof NextObjective) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700224 nextToDevice.put(objective.id(), deviceId);
Jonathan Hart17d00452015-04-21 17:10:00 -0700225 pipeliner.next((NextObjective) objective);
226 } else if (objective instanceof ForwardingObjective) {
227 pipeliner.forward((ForwardingObjective) objective);
228 } else {
229 pipeliner.filter((FilteringObjective) objective);
230 }
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800231 //Attempts to check if pipeliner is null for retry attempts
Jonathan Hart17d00452015-04-21 17:10:00 -0700232 } else if (numAttempts < INSTALL_RETRY_ATTEMPTS) {
Saurav Das3d038262015-04-23 12:36:58 -0700233 Thread.sleep(INSTALL_RETRY_INTERVAL);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700234 executorService.execute(new ObjectiveInstaller(deviceId, objective, numAttempts + 1));
Jonathan Hart17d00452015-04-21 17:10:00 -0700235 } else {
236 // Otherwise we've tried a few times and failed, report an
237 // error back to the user.
238 objective.context().ifPresent(
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800239 c -> c.onError(objective, ObjectiveError.NOPIPELINER));
Jonathan Hart17d00452015-04-21 17:10:00 -0700240 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700241 //Exception thrown
Jonathan Hart17d00452015-04-21 17:10:00 -0700242 } catch (Exception e) {
243 log.warn("Exception while installing flow objective", e);
244 }
245 }
246 }
247
248 @Override
249 public void filter(DeviceId deviceId, FilteringObjective filteringObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900250 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700251 executorService.execute(new ObjectiveInstaller(deviceId, filteringObjective));
alshabib77b88482015-04-07 15:47:50 -0700252 }
253
254 @Override
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700255 public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900256 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700257 if (forwardingObjective.nextId() == null ||
Yi Tseng1666b502017-05-17 11:05:18 -0700258 flowObjectiveStore.getNextGroup(forwardingObjective.nextId()) != null ||
259 !queueFwdObjective(deviceId, forwardingObjective)) {
260 // fast path
261 executorService.execute(new ObjectiveInstaller(deviceId, forwardingObjective));
alshabib910aff12015-04-09 16:55:57 -0700262 }
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700263 }
264
alshabib2a441c62015-04-13 18:39:38 -0700265 @Override
Jonathan Hart17d00452015-04-21 17:10:00 -0700266 public void next(DeviceId deviceId, NextObjective nextObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900267 checkPermission(FLOWRULE_WRITE);
Yi Tseng1666b502017-05-17 11:05:18 -0700268 if (nextObjective.op() == Operation.ADD ||
Charles Chanb71e1ba2018-08-16 21:02:34 -0700269 nextObjective.op() == Operation.VERIFY ||
Yi Tseng1666b502017-05-17 11:05:18 -0700270 flowObjectiveStore.getNextGroup(nextObjective.id()) != null ||
271 !queueNextObjective(deviceId, nextObjective)) {
272 // either group exists or we are trying to create it - let it through
273 executorService.execute(new ObjectiveInstaller(deviceId, nextObjective));
Saurav Das1547b3f2017-05-05 17:01:08 -0700274 }
alshabib2a441c62015-04-13 18:39:38 -0700275 }
276
alshabibf6ea9e62015-04-21 17:08:26 -0700277 @Override
278 public int allocateNextId() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900279 checkPermission(FLOWRULE_WRITE);
alshabibf6ea9e62015-04-21 17:08:26 -0700280 return flowObjectiveStore.allocateNextId();
281 }
282
Xin Jin313708b2015-07-09 13:43:04 -0700283 @Override
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700284 public void initPolicy(String policy) {
285 }
Xin Jin313708b2015-07-09 13:43:04 -0700286
Charles Chana7903c82018-03-15 20:14:16 -0700287 boolean queueFwdObjective(DeviceId deviceId, ForwardingObjective fwd) {
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700288 boolean queued = false;
289 synchronized (pendingForwards) {
290 // double check the flow objective store, because this block could run
291 // after a notification arrives
292 if (flowObjectiveStore.getNextGroup(fwd.nextId()) == null) {
293 pendingForwards.compute(fwd.nextId(), (id, pending) -> {
Saurav Das1547b3f2017-05-05 17:01:08 -0700294 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, fwd);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700295 if (pending == null) {
Pier Luigi97893112018-03-05 11:09:42 +0100296 return Sets.newLinkedHashSet(ImmutableSet.of(pendfo));
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700297 } else {
Saurav Das1547b3f2017-05-05 17:01:08 -0700298 pending.add(pendfo);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700299 return pending;
300 }
301 });
302 queued = true;
303 }
304 }
305 if (queued) {
Saurav Dasc568c342018-01-25 09:49:01 -0800306 log.debug("Queued forwarding objective {} for nextId {} meant for device {}",
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700307 fwd.id(), fwd.nextId(), deviceId);
308 }
309 return queued;
alshabib2a441c62015-04-13 18:39:38 -0700310 }
311
Charles Chana7903c82018-03-15 20:14:16 -0700312 boolean queueNextObjective(DeviceId deviceId, NextObjective next) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700313 // we need to hold off on other operations till we get notified that the
314 // initial group creation has succeeded
315 boolean queued = false;
316 synchronized (pendingNexts) {
317 // double check the flow objective store, because this block could run
318 // after a notification arrives
319 if (flowObjectiveStore.getNextGroup(next.id()) == null) {
320 pendingNexts.compute(next.id(), (id, pending) -> {
321 PendingFlowObjective pendfo = new PendingFlowObjective(deviceId, next);
322 if (pending == null) {
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800323 return Lists.newArrayList(pendfo);
Saurav Das1547b3f2017-05-05 17:01:08 -0700324 } else {
325 pending.add(pendfo);
326 return pending;
327 }
328 });
329 queued = true;
330 }
331 }
332 if (queued) {
Saurav Dasc568c342018-01-25 09:49:01 -0800333 log.debug("Queued next objective {} with operation {} meant for device {}",
Saurav Das1547b3f2017-05-05 17:01:08 -0700334 next.id(), next.op(), deviceId);
335 }
336 return queued;
337 }
338
Pier Ventre57a61cd2016-09-07 10:55:41 -0700339 /**
340 * Retrieves (if it exists) the device pipeline behaviour from the cache.
341 * Otherwise it warms the caches and triggers the init method of the Pipeline.
342 *
343 * @param deviceId the id of the device associated to the pipeline
344 * @return the implementation of the Pipeliner behaviour
345 */
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700346 private Pipeliner getDevicePipeliner(DeviceId deviceId) {
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700347 return pipeliners.computeIfAbsent(deviceId, this::initPipelineHandler);
alshabib77b88482015-04-07 15:47:50 -0700348 }
349
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700350 /**
Pier Ventre57a61cd2016-09-07 10:55:41 -0700351 * Retrieves (if it exists) the device pipeline behaviour from the cache and
352 * and triggers the init method of the pipeline. Otherwise (DEVICE_ADDED) it warms
353 * the caches and triggers the init method of the Pipeline. The rationale of this
354 * method is for managing the scenario of a switch that goes down for a failure
355 * and goes up after a while.
356 *
357 * @param deviceId the id of the device associated to the pipeline
358 * @return the implementation of the Pipeliner behaviour
359 */
360 private Pipeliner getAndInitDevicePipeliner(DeviceId deviceId) {
361 return pipeliners.compute(deviceId, (deviceIdValue, pipelinerValue) -> {
362 if (pipelinerValue != null) {
363 pipelinerValue.init(deviceId, context);
364 return pipelinerValue;
365 }
366 return this.initPipelineHandler(deviceId);
367 });
368 }
369
370 /**
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700371 * Creates and initialize {@link Pipeliner}.
372 * <p>
373 * Note: Expected to be called under per-Device lock.
374 * e.g., {@code pipeliners}' Map#compute family methods
375 *
376 * @param deviceId Device to initialize pipeliner
377 * @return {@link Pipeliner} instance or null
378 */
379 private Pipeliner initPipelineHandler(DeviceId deviceId) {
380 start = now();
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700381
Jonathan Hart17d00452015-04-21 17:10:00 -0700382 // Attempt to lookup the handler in the cache
383 DriverHandler handler = driverHandlers.get(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700384 cTime = now();
385
Jonathan Hart17d00452015-04-21 17:10:00 -0700386 if (handler == null) {
387 try {
388 // Otherwise create it and if it has pipeline behaviour, cache it
389 handler = driverService.createHandler(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700390 dTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700391 if (!handler.driver().hasBehaviour(Pipeliner.class)) {
Yuta HIGUCHIa2a4f342017-03-17 11:38:57 -0700392 log.debug("Pipeline behaviour not supported for device {}",
Jonathan Hart17d00452015-04-21 17:10:00 -0700393 deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700394 return null;
alshabib2a441c62015-04-13 18:39:38 -0700395 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700396 } catch (ItemNotFoundException e) {
397 log.warn("No applicable driver for device {}", deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700398 return null;
alshabib2a441c62015-04-13 18:39:38 -0700399 }
400
Jonathan Hart17d00452015-04-21 17:10:00 -0700401 driverHandlers.put(deviceId, handler);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700402 eTime = now();
alshabib2a441c62015-04-13 18:39:38 -0700403 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700404
405 // Always (re)initialize the pipeline behaviour
406 log.info("Driver {} bound to device {} ... initializing driver",
407 handler.driver().name(), deviceId);
Thomas Vachuska0121a612015-07-21 11:18:09 -0700408 hTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700409 Pipeliner pipeliner = handler.behaviour(Pipeliner.class);
Thomas Vachuska94c3cf42015-07-20 13:01:12 -0700410 hbTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700411 pipeliner.init(deviceId, context);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700412 stopWatch();
413 return pipeliner;
alshabibaebe7752015-04-07 17:45:42 -0700414 }
alshabib77b88482015-04-07 15:47:50 -0700415
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700416 private void invalidatePipelinerIfNecessary(Device device) {
417 DriverHandler handler = driverHandlers.get(device.id());
418 if (handler != null &&
419 !Objects.equals(handler.driver().name(),
420 device.annotations().value(DRIVER))) {
421 invalidatePipeliner(device.id());
422 }
423 }
424
425 private void invalidatePipeliner(DeviceId id) {
426 log.info("Invalidating cached pipeline behaviour for {}", id);
427 driverHandlers.remove(id);
428 pipeliners.remove(id);
429 if (deviceService.isAvailable(id)) {
430 getAndInitDevicePipeliner(id);
431 }
432 }
433
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700434 // Triggers driver setup when a device is (re)detected.
alshabibaebe7752015-04-07 17:45:42 -0700435 private class InnerDeviceListener implements DeviceListener {
436 @Override
437 public void event(DeviceEvent event) {
438 switch (event.type()) {
439 case DEVICE_ADDED:
440 case DEVICE_AVAILABILITY_CHANGED:
Madan Jampani0174f452015-05-29 11:52:05 -0700441 log.debug("Device either added or availability changed {}",
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700442 event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700443 if (deviceService.isAvailable(event.subject().id())) {
Madan Jampani0174f452015-05-29 11:52:05 -0700444 log.debug("Device is now available {}", event.subject().id());
Pier Ventre57a61cd2016-09-07 10:55:41 -0700445 getAndInitDevicePipeliner(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700446 } else {
447 log.debug("Device is no longer available {}", event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700448 }
449 break;
450 case DEVICE_UPDATED:
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700451 // Invalidate pipeliner and handler caches if the driver name
452 // device annotation changed.
453 invalidatePipelinerIfNecessary(event.subject());
alshabib4313d102015-04-08 18:55:08 -0700454 break;
455 case DEVICE_REMOVED:
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700456 // evict Pipeliner and Handler cache, when
457 // the Device was administratively removed.
458 //
459 // System expect the user to clear all existing flows,
460 // before removing device, especially if they intend to
461 // replace driver/pipeliner assigned to the device.
462 driverHandlers.remove(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700463 pipeliners.remove(event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700464 break;
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700465 case DEVICE_SUSPENDED:
466 break;
alshabib4313d102015-04-08 18:55:08 -0700467 case PORT_ADDED:
468 break;
469 case PORT_UPDATED:
470 break;
471 case PORT_REMOVED:
alshabibaebe7752015-04-07 17:45:42 -0700472 break;
473 default:
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700474 break;
alshabibaebe7752015-04-07 17:45:42 -0700475 }
alshabib77b88482015-04-07 15:47:50 -0700476 }
477 }
alshabibaebe7752015-04-07 17:45:42 -0700478
Thomas Vachuskacfeff192017-08-23 15:29:34 -0700479 // Monitors driver configuration changes and invalidates the pipeliner cache entries.
480 // Note that this may leave stale entries on the device if the driver changes
481 // in manner where the new driver does not produce backward compatible flow objectives.
482 // In such cases, it is the operator's responsibility to force device re-connect.
483 private class InnerDriverListener implements DriverListener {
484 @Override
485 public void event(DriverEvent event) {
486 String driverName = event.subject().name();
487 driverHandlers.entrySet().stream()
488 .filter(e -> driverName.equals(e.getValue().driver().name()))
489 .map(Map.Entry::getKey)
490 .distinct()
491 .forEach(FlowObjectiveManager.this::invalidatePipeliner);
492 }
493 }
494
Thomas Vachuska174bb912015-07-16 21:27:14 -0700495 // Temporary mechanism to monitor pipeliner setup time-cost; there are
496 // intermittent time where this takes in excess of 2 seconds. Why?
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700497 private long start = 0, totals = 0, count = 0;
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700498 private long cTime, dTime, eTime, hTime, hbTime;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700499 private static final long LIMIT = 500;
Thomas Vachuska174bb912015-07-16 21:27:14 -0700500
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700501 private long now() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700502 return System.currentTimeMillis();
503 }
504
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700505 private void stopWatch() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700506 long duration = System.currentTimeMillis() - start;
507 totals += duration;
508 count += 1;
509 if (duration > LIMIT) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700510 log.info("Pipeline setup took {} ms; avg {} ms; cTime={}, dTime={}, eTime={}, hTime={}, hbTime={}",
511 duration, totals / count, diff(cTime), diff(dTime), diff(eTime), diff(hTime), diff(hbTime));
Thomas Vachuska174bb912015-07-16 21:27:14 -0700512 }
513 }
514
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700515 private long diff(long bTime) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700516 long diff = bTime - start;
517 return diff < 0 ? 0 : diff;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700518 }
519
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700520 // Processing context for initializing pipeline driver behaviours.
521 private class InnerPipelineContext implements PipelinerContext {
522 @Override
523 public ServiceDirectory directory() {
524 return serviceDirectory;
alshabibaebe7752015-04-07 17:45:42 -0700525 }
alshabib2a441c62015-04-13 18:39:38 -0700526
527 @Override
528 public FlowObjectiveStore store() {
529 return flowObjectiveStore;
530 }
alshabib2a441c62015-04-13 18:39:38 -0700531 }
532
533 private class InternalStoreDelegate implements FlowObjectiveStoreDelegate {
534 @Override
535 public void notify(ObjectiveEvent event) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800536 if (event.type() == Type.ADD) {
537 log.debug("Received notification of obj event {}", event);
Saurav Das1547b3f2017-05-05 17:01:08 -0700538 Set<PendingFlowObjective> pending;
539
540 // first send all pending flows
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700541 synchronized (pendingForwards) {
542 // needs to be synchronized for queueObjective lookup
543 pending = pendingForwards.remove(event.subject());
544 }
Saurav Das423fe2b2015-12-04 10:52:59 -0800545 if (pending == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700546 log.debug("No forwarding objectives pending for this "
547 + "obj event {}", event);
548 } else {
549 log.debug("Processing {} pending forwarding objectives for nextId {}",
550 pending.size(), event.subject());
551 pending.forEach(p -> getDevicePipeliner(p.deviceId())
552 .forward((ForwardingObjective) p.flowObjective()));
Saurav Das423fe2b2015-12-04 10:52:59 -0800553 }
554
Saurav Das1547b3f2017-05-05 17:01:08 -0700555 // now check for pending next-objectives
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800556 List<PendingFlowObjective> pendNexts;
Saurav Das1547b3f2017-05-05 17:01:08 -0700557 synchronized (pendingNexts) {
558 // needs to be synchronized for queueObjective lookup
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800559 pendNexts = pendingNexts.remove(event.subject());
Saurav Das1547b3f2017-05-05 17:01:08 -0700560 }
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800561 if (pendNexts == null) {
Saurav Das1547b3f2017-05-05 17:01:08 -0700562 log.debug("No next objectives pending for this "
563 + "obj event {}", event);
564 } else {
565 log.debug("Processing {} pending next objectives for nextId {}",
Saurav Dasf14d9ef2017-12-05 15:00:23 -0800566 pendNexts.size(), event.subject());
567 pendNexts.forEach(p -> getDevicePipeliner(p.deviceId())
Saurav Das1547b3f2017-05-05 17:01:08 -0700568 .next((NextObjective) p.flowObjective()));
569 }
alshabib2a441c62015-04-13 18:39:38 -0700570 }
alshabib2a441c62015-04-13 18:39:38 -0700571 }
572 }
573
574 /**
Saurav Das1547b3f2017-05-05 17:01:08 -0700575 * Data class used to hold a pending flow objective that could not
alshabib2a441c62015-04-13 18:39:38 -0700576 * be processed because the associated next object was not present.
Saurav Das1547b3f2017-05-05 17:01:08 -0700577 * Note that this pending flow objective could be a forwarding objective
578 * waiting for a next objective to complete execution. Or it could a
579 * next objective (with a different operation - remove, addToExisting, or
580 * removeFromExisting) waiting for a next objective with the same id to
581 * complete execution.
alshabib2a441c62015-04-13 18:39:38 -0700582 */
Charles Chana7903c82018-03-15 20:14:16 -0700583 protected class PendingFlowObjective {
alshabib2a441c62015-04-13 18:39:38 -0700584 private final DeviceId deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700585 private final Objective flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700586
Charles Chana7903c82018-03-15 20:14:16 -0700587 PendingFlowObjective(DeviceId deviceId, Objective flowObj) {
alshabib2a441c62015-04-13 18:39:38 -0700588 this.deviceId = deviceId;
Saurav Das1547b3f2017-05-05 17:01:08 -0700589 this.flowObj = flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700590 }
591
592 public DeviceId deviceId() {
593 return deviceId;
594 }
595
Saurav Das1547b3f2017-05-05 17:01:08 -0700596 public Objective flowObjective() {
597 return flowObj;
alshabib2a441c62015-04-13 18:39:38 -0700598 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800599
600 @Override
601 public int hashCode() {
Saurav Das1547b3f2017-05-05 17:01:08 -0700602 return Objects.hash(deviceId, flowObj);
Saurav Das8a0732e2015-11-20 15:27:53 -0800603 }
604
605 @Override
606 public boolean equals(final Object obj) {
607 if (this == obj) {
608 return true;
609 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700610 if (!(obj instanceof PendingFlowObjective)) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800611 return false;
612 }
Saurav Das1547b3f2017-05-05 17:01:08 -0700613 final PendingFlowObjective other = (PendingFlowObjective) obj;
Charles Chana7903c82018-03-15 20:14:16 -0700614
615 return this.deviceId.equals(other.deviceId) &&
616 this.flowObj.equals(other.flowObj);
Saurav Das8a0732e2015-11-20 15:27:53 -0800617 }
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 Dasf14d9ef2017-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 }
alshabib77b88482015-04-07 15:47:50 -0700689}