blob: 37bf9d27d9d6e6da2db41ac9c26f20094569ec3c [file] [log] [blame]
alshabib77b88482015-04-07 15:47:50 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
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
18import com.google.common.collect.Maps;
Thomas Vachuskad27097c2016-06-14 19:10:41 -070019import com.google.common.collect.Sets;
alshabib77b88482015-04-07 15:47:50 -070020import org.apache.felix.scr.annotations.Activate;
21import org.apache.felix.scr.annotations.Component;
22import org.apache.felix.scr.annotations.Deactivate;
Yi Tseng374c5f32017-03-05 22:51:35 -080023import org.apache.felix.scr.annotations.Modified;
24import org.apache.felix.scr.annotations.Property;
alshabib77b88482015-04-07 15:47:50 -070025import org.apache.felix.scr.annotations.Reference;
26import org.apache.felix.scr.annotations.ReferenceCardinality;
27import org.apache.felix.scr.annotations.Service;
28import org.onlab.osgi.DefaultServiceDirectory;
29import org.onlab.osgi.ServiceDirectory;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070030import org.onlab.util.ItemNotFoundException;
Yi Tseng374c5f32017-03-05 22:51:35 -080031import org.onlab.util.Tools;
32import org.onosproject.cfg.ComponentConfigService;
alshabib77b88482015-04-07 15:47:50 -070033import org.onosproject.cluster.ClusterService;
alshabib77b88482015-04-07 15:47:50 -070034import org.onosproject.net.DeviceId;
Saurav Das24431192016-03-07 19:13:00 -080035import org.onosproject.net.behaviour.NextGroup;
alshabib77b88482015-04-07 15:47:50 -070036import org.onosproject.net.behaviour.Pipeliner;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070037import org.onosproject.net.behaviour.PipelinerContext;
alshabibaebe7752015-04-07 17:45:42 -070038import org.onosproject.net.device.DeviceEvent;
39import org.onosproject.net.device.DeviceListener;
alshabib77b88482015-04-07 15:47:50 -070040import org.onosproject.net.device.DeviceService;
Thomas Vachuska866b46a2015-04-30 00:26:55 -070041import org.onosproject.net.driver.DefaultDriverProviderService;
alshabib77b88482015-04-07 15:47:50 -070042import org.onosproject.net.driver.DriverHandler;
43import org.onosproject.net.driver.DriverService;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070044import org.onosproject.net.flow.FlowRuleService;
alshabib77b88482015-04-07 15:47:50 -070045import org.onosproject.net.flowobjective.FilteringObjective;
46import org.onosproject.net.flowobjective.FlowObjectiveService;
alshabib2a441c62015-04-13 18:39:38 -070047import org.onosproject.net.flowobjective.FlowObjectiveStore;
48import org.onosproject.net.flowobjective.FlowObjectiveStoreDelegate;
alshabib77b88482015-04-07 15:47:50 -070049import org.onosproject.net.flowobjective.ForwardingObjective;
50import org.onosproject.net.flowobjective.NextObjective;
alshabib910aff12015-04-09 16:55:57 -070051import org.onosproject.net.flowobjective.Objective;
Jonathan Hart17d00452015-04-21 17:10:00 -070052import org.onosproject.net.flowobjective.ObjectiveError;
alshabib2a441c62015-04-13 18:39:38 -070053import org.onosproject.net.flowobjective.ObjectiveEvent;
Saurav Das423fe2b2015-12-04 10:52:59 -080054import org.onosproject.net.flowobjective.ObjectiveEvent.Type;
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070055import org.onosproject.net.group.GroupService;
Yi Tseng374c5f32017-03-05 22:51:35 -080056import org.osgi.service.component.ComponentContext;
alshabib77b88482015-04-07 15:47:50 -070057import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
Saurav Das24431192016-03-07 19:13:00 -080060import java.util.ArrayList;
Saurav Das24431192016-03-07 19:13:00 -080061import java.util.List;
alshabib77b88482015-04-07 15:47:50 -070062import java.util.Map;
Saurav Das8a0732e2015-11-20 15:27:53 -080063import java.util.Objects;
alshabib2a441c62015-04-13 18:39:38 -070064import java.util.Set;
Jonathan Hart17d00452015-04-21 17:10:00 -070065import java.util.concurrent.ExecutorService;
alshabib77b88482015-04-07 15:47:50 -070066
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -070067import static com.google.common.base.Preconditions.checkNotNull;
Yi Tseng374c5f32017-03-05 22:51:35 -080068import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuska866b46a2015-04-30 00:26:55 -070069import static java.util.concurrent.Executors.newFixedThreadPool;
Jonathan Hart17d00452015-04-21 17:10:00 -070070import static org.onlab.util.Tools.groupedThreads;
Changhoon Yoon541ef712015-05-23 17:18:34 +090071import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskad27097c2016-06-14 19:10:41 -070072import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
alshabib77b88482015-04-07 15:47:50 -070073
74/**
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070075 * Provides implementation of the flow objective programming service.
alshabib77b88482015-04-07 15:47:50 -070076 */
alshabib2a441c62015-04-13 18:39:38 -070077@Component(immediate = true)
alshabib77b88482015-04-07 15:47:50 -070078@Service
79public class FlowObjectiveManager implements FlowObjectiveService {
80
Saurav Dasbd7f7422015-04-23 16:31:47 -070081 public static final int INSTALL_RETRY_ATTEMPTS = 5;
Jonathan Hart17d00452015-04-21 17:10:00 -070082 public static final long INSTALL_RETRY_INTERVAL = 1000; // ms
alshabib77b88482015-04-07 15:47:50 -070083
Yi Tseng374c5f32017-03-05 22:51:35 -080084 private static final String WORKER_PATTERN = "objective-installer-%d";
85 private static final String GROUP_THREAD_NAME = "onos/objective-installer";
86 private static final String NUM_THREAD = "numThreads";
87
Jonathan Hart17d00452015-04-21 17:10:00 -070088 private final Logger log = LoggerFactory.getLogger(getClass());
Thomas Vachuskaca88bb72015-04-08 19:38:02 -070089
Yi Tseng9753fc12017-03-10 18:42:46 -080090 private static final int DEFAULT_NUM_THREADS = 4;
Yi Tseng374c5f32017-03-05 22:51:35 -080091 @Property(name = NUM_THREAD,
92 intValue = DEFAULT_NUM_THREADS,
93 label = "Number of worker threads")
94 private int numThreads = DEFAULT_NUM_THREADS;
95
alshabib77b88482015-04-07 15:47:50 -070096 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
97 protected DriverService driverService;
98
99 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
100 protected DeviceService deviceService;
101
102 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
alshabib77b88482015-04-07 15:47:50 -0700103 protected ClusterService clusterService;
104
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700105 // Note: The following dependencies are added on behalf of the pipeline
106 // driver behaviours to assure these services are available for their
107 // initialization.
108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
109 protected FlowRuleService flowRuleService;
110
111 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
112 protected GroupService groupService;
113
alshabib2a441c62015-04-13 18:39:38 -0700114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
115 protected FlowObjectiveStore flowObjectiveStore;
116
Yi Tseng374c5f32017-03-05 22:51:35 -0800117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
118 protected ComponentConfigService cfgService;
119
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700120 // Note: This must remain an optional dependency to allow re-install of default drivers.
121 // Note: For now disabled until we can move to OPTIONAL_UNARY dependency
122 // @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY, policy = ReferencePolicy.DYNAMIC)
123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
124 protected DefaultDriverProviderService defaultDriverService;
125
alshabib2a441c62015-04-13 18:39:38 -0700126 private final FlowObjectiveStoreDelegate delegate = new InternalStoreDelegate();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700127
128 private final Map<DeviceId, DriverHandler> driverHandlers = Maps.newConcurrentMap();
alshabib910aff12015-04-09 16:55:57 -0700129 private final Map<DeviceId, Pipeliner> pipeliners = Maps.newConcurrentMap();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700130
131 private final PipelinerContext context = new InnerPipelineContext();
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700132 private final DeviceListener deviceListener = new InnerDeviceListener();
133
alshabib77b88482015-04-07 15:47:50 -0700134 protected ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
alshabib910aff12015-04-09 16:55:57 -0700135
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700136 private final Map<Integer, Set<PendingNext>> pendingForwards = Maps.newConcurrentMap();
alshabib2a441c62015-04-13 18:39:38 -0700137
Saurav Das24431192016-03-07 19:13:00 -0800138 // local store to track which nextObjectives were sent to which device
139 // for debugging purposes
140 private Map<Integer, DeviceId> nextToDevice = Maps.newConcurrentMap();
141
Jonathan Hart17d00452015-04-21 17:10:00 -0700142 private ExecutorService executorService;
alshabib2a441c62015-04-13 18:39:38 -0700143
alshabib77b88482015-04-07 15:47:50 -0700144 @Activate
145 protected void activate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800146 cfgService.registerProperties(getClass());
147 executorService = newFixedThreadPool(numThreads,
148 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
alshabib2a441c62015-04-13 18:39:38 -0700149 flowObjectiveStore.setDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700150 deviceService.addListener(deviceListener);
alshabib77b88482015-04-07 15:47:50 -0700151 log.info("Started");
152 }
153
154 @Deactivate
155 protected void deactivate() {
Yi Tseng374c5f32017-03-05 22:51:35 -0800156 cfgService.unregisterProperties(getClass(), false);
alshabib2a441c62015-04-13 18:39:38 -0700157 flowObjectiveStore.unsetDelegate(delegate);
alshabibaebe7752015-04-07 17:45:42 -0700158 deviceService.removeListener(deviceListener);
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700159 executorService.shutdown();
160 pipeliners.clear();
161 driverHandlers.clear();
Saurav Das24431192016-03-07 19:13:00 -0800162 nextToDevice.clear();
alshabib77b88482015-04-07 15:47:50 -0700163 log.info("Stopped");
164 }
165
Yi Tseng374c5f32017-03-05 22:51:35 -0800166 @Modified
167 protected void modified(ComponentContext context) {
168 String propertyValue =
169 Tools.get(context.getProperties(), NUM_THREAD);
170 int newNumThreads = isNullOrEmpty(propertyValue) ? numThreads : Integer.parseInt(propertyValue);
171
172 if (newNumThreads != numThreads && newNumThreads > 0) {
173 numThreads = newNumThreads;
174 ExecutorService oldWorkerExecutor = executorService;
175 executorService = newFixedThreadPool(numThreads,
176 groupedThreads(GROUP_THREAD_NAME, WORKER_PATTERN, log));
177 if (oldWorkerExecutor != null) {
178 oldWorkerExecutor.shutdown();
179 }
180 log.info("Reconfigured number of worker threads to {}", numThreads);
181 }
182 }
183
Jonathan Hart17d00452015-04-21 17:10:00 -0700184 /**
185 * Task that passes the flow objective down to the driver. The task will
186 * make a few attempts to find the appropriate driver, then eventually give
187 * up and report an error if no suitable driver could be found.
188 */
189 private class ObjectiveInstaller implements Runnable {
190 private final DeviceId deviceId;
191 private final Objective objective;
192
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700193 private final int numAttempts;
Jonathan Hart17d00452015-04-21 17:10:00 -0700194
195 public ObjectiveInstaller(DeviceId deviceId, Objective objective) {
Sho SHIMIZUf45d85d2015-07-01 14:39:11 -0700196 this(deviceId, objective, 1);
197 }
198
199 public ObjectiveInstaller(DeviceId deviceId, Objective objective, int attemps) {
200 this.deviceId = checkNotNull(deviceId);
201 this.objective = checkNotNull(objective);
202 this.numAttempts = checkNotNull(attemps);
alshabib910aff12015-04-09 16:55:57 -0700203 }
alshabib77b88482015-04-07 15:47:50 -0700204
Jonathan Hart17d00452015-04-21 17:10:00 -0700205 @Override
206 public void run() {
207 try {
Jonathan Hart17d00452015-04-21 17:10:00 -0700208 Pipeliner pipeliner = getDevicePipeliner(deviceId);
209
210 if (pipeliner != null) {
211 if (objective instanceof NextObjective) {
212 pipeliner.next((NextObjective) objective);
213 } else if (objective instanceof ForwardingObjective) {
214 pipeliner.forward((ForwardingObjective) objective);
215 } else {
216 pipeliner.filter((FilteringObjective) objective);
217 }
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800218 //Attempts to check if pipeliner is null for retry attempts
Jonathan Hart17d00452015-04-21 17:10:00 -0700219 } else if (numAttempts < INSTALL_RETRY_ATTEMPTS) {
Saurav Das3d038262015-04-23 12:36:58 -0700220 Thread.sleep(INSTALL_RETRY_INTERVAL);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700221 executorService.execute(new ObjectiveInstaller(deviceId, objective, numAttempts + 1));
Jonathan Hart17d00452015-04-21 17:10:00 -0700222 } else {
223 // Otherwise we've tried a few times and failed, report an
224 // error back to the user.
225 objective.context().ifPresent(
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800226 c -> c.onError(objective, ObjectiveError.NOPIPELINER));
Jonathan Hart17d00452015-04-21 17:10:00 -0700227 }
Andrea Campanella1f8188d2016-02-29 13:24:54 -0800228 //Excpetion thrown
Jonathan Hart17d00452015-04-21 17:10:00 -0700229 } catch (Exception e) {
230 log.warn("Exception while installing flow objective", e);
231 }
232 }
233 }
234
235 @Override
236 public void filter(DeviceId deviceId, FilteringObjective filteringObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900237 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700238 executorService.execute(new ObjectiveInstaller(deviceId, filteringObjective));
alshabib77b88482015-04-07 15:47:50 -0700239 }
240
241 @Override
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700242 public void forward(DeviceId deviceId, ForwardingObjective forwardingObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900243 checkPermission(FLOWRULE_WRITE);
alshabib2a441c62015-04-13 18:39:38 -0700244 if (queueObjective(deviceId, forwardingObjective)) {
245 return;
alshabib910aff12015-04-09 16:55:57 -0700246 }
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700247 executorService.execute(new ObjectiveInstaller(deviceId, forwardingObjective));
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700248 }
249
alshabib2a441c62015-04-13 18:39:38 -0700250 @Override
Jonathan Hart17d00452015-04-21 17:10:00 -0700251 public void next(DeviceId deviceId, NextObjective nextObjective) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900252 checkPermission(FLOWRULE_WRITE);
Saurav Das24431192016-03-07 19:13:00 -0800253 nextToDevice.put(nextObjective.id(), deviceId);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700254 executorService.execute(new ObjectiveInstaller(deviceId, nextObjective));
alshabib2a441c62015-04-13 18:39:38 -0700255 }
256
alshabibf6ea9e62015-04-21 17:08:26 -0700257 @Override
258 public int allocateNextId() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900259 checkPermission(FLOWRULE_WRITE);
alshabibf6ea9e62015-04-21 17:08:26 -0700260 return flowObjectiveStore.allocateNextId();
261 }
262
Xin Jin313708b2015-07-09 13:43:04 -0700263 @Override
264 public void initPolicy(String policy) {}
265
alshabib2a441c62015-04-13 18:39:38 -0700266 private boolean queueObjective(DeviceId deviceId, ForwardingObjective fwd) {
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700267 if (fwd.nextId() == null ||
Yi Tseng38fc71e2017-02-03 14:50:47 -0800268 flowObjectiveStore.getNextGroup(fwd.nextId()) != null ||
269 fwd.op() == Objective.Operation.REMOVE) {
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700270 // fast path
271 return false;
alshabib2a441c62015-04-13 18:39:38 -0700272 }
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700273 boolean queued = false;
274 synchronized (pendingForwards) {
275 // double check the flow objective store, because this block could run
276 // after a notification arrives
277 if (flowObjectiveStore.getNextGroup(fwd.nextId()) == null) {
278 pendingForwards.compute(fwd.nextId(), (id, pending) -> {
279 PendingNext next = new PendingNext(deviceId, fwd);
280 if (pending == null) {
281 return Sets.newHashSet(next);
282 } else {
283 pending.add(next);
284 return pending;
285 }
286 });
287 queued = true;
288 }
289 }
290 if (queued) {
291 log.debug("Queued forwarding objective {} for nextId {} meant for device {}",
292 fwd.id(), fwd.nextId(), deviceId);
293 }
294 return queued;
alshabib2a441c62015-04-13 18:39:38 -0700295 }
296
Pier Ventre57a61cd2016-09-07 10:55:41 -0700297 /**
298 * Retrieves (if it exists) the device pipeline behaviour from the cache.
299 * Otherwise it warms the caches and triggers the init method of the Pipeline.
300 *
301 * @param deviceId the id of the device associated to the pipeline
302 * @return the implementation of the Pipeliner behaviour
303 */
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700304 private Pipeliner getDevicePipeliner(DeviceId deviceId) {
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700305 return pipeliners.computeIfAbsent(deviceId, this::initPipelineHandler);
alshabib77b88482015-04-07 15:47:50 -0700306 }
307
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700308 /**
Pier Ventre57a61cd2016-09-07 10:55:41 -0700309 * Retrieves (if it exists) the device pipeline behaviour from the cache and
310 * and triggers the init method of the pipeline. Otherwise (DEVICE_ADDED) it warms
311 * the caches and triggers the init method of the Pipeline. The rationale of this
312 * method is for managing the scenario of a switch that goes down for a failure
313 * and goes up after a while.
314 *
315 * @param deviceId the id of the device associated to the pipeline
316 * @return the implementation of the Pipeliner behaviour
317 */
318 private Pipeliner getAndInitDevicePipeliner(DeviceId deviceId) {
319 return pipeliners.compute(deviceId, (deviceIdValue, pipelinerValue) -> {
320 if (pipelinerValue != null) {
321 pipelinerValue.init(deviceId, context);
322 return pipelinerValue;
323 }
324 return this.initPipelineHandler(deviceId);
325 });
326 }
327
328 /**
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700329 * Creates and initialize {@link Pipeliner}.
330 * <p>
331 * Note: Expected to be called under per-Device lock.
332 * e.g., {@code pipeliners}' Map#compute family methods
333 *
334 * @param deviceId Device to initialize pipeliner
335 * @return {@link Pipeliner} instance or null
336 */
337 private Pipeliner initPipelineHandler(DeviceId deviceId) {
338 start = now();
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700339
Jonathan Hart17d00452015-04-21 17:10:00 -0700340 // Attempt to lookup the handler in the cache
341 DriverHandler handler = driverHandlers.get(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700342 cTime = now();
343
Jonathan Hart17d00452015-04-21 17:10:00 -0700344 if (handler == null) {
345 try {
346 // Otherwise create it and if it has pipeline behaviour, cache it
347 handler = driverService.createHandler(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700348 dTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700349 if (!handler.driver().hasBehaviour(Pipeliner.class)) {
Yuta HIGUCHIa2a4f342017-03-17 11:38:57 -0700350 log.debug("Pipeline behaviour not supported for device {}",
Jonathan Hart17d00452015-04-21 17:10:00 -0700351 deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700352 return null;
alshabib2a441c62015-04-13 18:39:38 -0700353 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700354 } catch (ItemNotFoundException e) {
355 log.warn("No applicable driver for device {}", deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700356 return null;
alshabib2a441c62015-04-13 18:39:38 -0700357 }
358
Jonathan Hart17d00452015-04-21 17:10:00 -0700359 driverHandlers.put(deviceId, handler);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700360 eTime = now();
alshabib2a441c62015-04-13 18:39:38 -0700361 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700362
363 // Always (re)initialize the pipeline behaviour
364 log.info("Driver {} bound to device {} ... initializing driver",
365 handler.driver().name(), deviceId);
Thomas Vachuska0121a612015-07-21 11:18:09 -0700366 hTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700367 Pipeliner pipeliner = handler.behaviour(Pipeliner.class);
Thomas Vachuska94c3cf42015-07-20 13:01:12 -0700368 hbTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700369 pipeliner.init(deviceId, context);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700370 stopWatch();
371 return pipeliner;
alshabibaebe7752015-04-07 17:45:42 -0700372 }
alshabib77b88482015-04-07 15:47:50 -0700373
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700374 // Triggers driver setup when a device is (re)detected.
alshabibaebe7752015-04-07 17:45:42 -0700375 private class InnerDeviceListener implements DeviceListener {
376 @Override
377 public void event(DeviceEvent event) {
378 switch (event.type()) {
379 case DEVICE_ADDED:
380 case DEVICE_AVAILABILITY_CHANGED:
Madan Jampani0174f452015-05-29 11:52:05 -0700381 log.debug("Device either added or availability changed {}",
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700382 event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700383 if (deviceService.isAvailable(event.subject().id())) {
Madan Jampani0174f452015-05-29 11:52:05 -0700384 log.debug("Device is now available {}", event.subject().id());
Pier Ventre57a61cd2016-09-07 10:55:41 -0700385 getAndInitDevicePipeliner(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700386 } else {
387 log.debug("Device is no longer available {}", event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700388 }
389 break;
390 case DEVICE_UPDATED:
391 break;
392 case DEVICE_REMOVED:
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700393 // evict Pipeliner and Handler cache, when
394 // the Device was administratively removed.
395 //
396 // System expect the user to clear all existing flows,
397 // before removing device, especially if they intend to
398 // replace driver/pipeliner assigned to the device.
399 driverHandlers.remove(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700400 pipeliners.remove(event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700401 break;
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700402 case DEVICE_SUSPENDED:
403 break;
alshabib4313d102015-04-08 18:55:08 -0700404 case PORT_ADDED:
405 break;
406 case PORT_UPDATED:
407 break;
408 case PORT_REMOVED:
alshabibaebe7752015-04-07 17:45:42 -0700409 break;
410 default:
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700411 break;
alshabibaebe7752015-04-07 17:45:42 -0700412 }
alshabib77b88482015-04-07 15:47:50 -0700413 }
414 }
alshabibaebe7752015-04-07 17:45:42 -0700415
Thomas Vachuska174bb912015-07-16 21:27:14 -0700416 // Temporary mechanism to monitor pipeliner setup time-cost; there are
417 // intermittent time where this takes in excess of 2 seconds. Why?
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700418 private long start = 0, totals = 0, count = 0;
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700419 private long cTime, dTime, eTime, hTime, hbTime;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700420 private static final long LIMIT = 500;
Thomas Vachuska174bb912015-07-16 21:27:14 -0700421
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700422 private long now() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700423 return System.currentTimeMillis();
424 }
425
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700426 private void stopWatch() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700427 long duration = System.currentTimeMillis() - start;
428 totals += duration;
429 count += 1;
430 if (duration > LIMIT) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700431 log.info("Pipeline setup took {} ms; avg {} ms; cTime={}, dTime={}, eTime={}, hTime={}, hbTime={}",
432 duration, totals / count, diff(cTime), diff(dTime), diff(eTime), diff(hTime), diff(hbTime));
Thomas Vachuska174bb912015-07-16 21:27:14 -0700433 }
434 }
435
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700436 private long diff(long bTime) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700437 long diff = bTime - start;
438 return diff < 0 ? 0 : diff;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700439 }
440
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700441 // Processing context for initializing pipeline driver behaviours.
442 private class InnerPipelineContext implements PipelinerContext {
443 @Override
444 public ServiceDirectory directory() {
445 return serviceDirectory;
alshabibaebe7752015-04-07 17:45:42 -0700446 }
alshabib2a441c62015-04-13 18:39:38 -0700447
448 @Override
449 public FlowObjectiveStore store() {
450 return flowObjectiveStore;
451 }
alshabib2a441c62015-04-13 18:39:38 -0700452 }
453
454 private class InternalStoreDelegate implements FlowObjectiveStoreDelegate {
455 @Override
456 public void notify(ObjectiveEvent event) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800457 if (event.type() == Type.ADD) {
458 log.debug("Received notification of obj event {}", event);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700459 Set<PendingNext> pending;
460 synchronized (pendingForwards) {
461 // needs to be synchronized for queueObjective lookup
462 pending = pendingForwards.remove(event.subject());
463 }
alshabib2a441c62015-04-13 18:39:38 -0700464
Saurav Das423fe2b2015-12-04 10:52:59 -0800465 if (pending == null) {
Saurav Das25190812016-05-27 13:54:07 -0700466 log.debug("Nothing pending for this obj event {}", event);
Saurav Das423fe2b2015-12-04 10:52:59 -0800467 return;
468 }
469
Saurav Das49cb5a12016-01-16 22:54:07 -0800470 log.debug("Processing {} pending forwarding objectives for nextId {}",
471 pending.size(), event.subject());
Saurav Das423fe2b2015-12-04 10:52:59 -0800472 pending.forEach(p -> getDevicePipeliner(p.deviceId())
473 .forward(p.forwardingObjective()));
alshabib2a441c62015-04-13 18:39:38 -0700474 }
alshabib2a441c62015-04-13 18:39:38 -0700475 }
476 }
477
478 /**
479 * Data class used to hold a pending forwarding objective that could not
480 * be processed because the associated next object was not present.
481 */
482 private class PendingNext {
483 private final DeviceId deviceId;
484 private final ForwardingObjective fwd;
485
486 public PendingNext(DeviceId deviceId, ForwardingObjective fwd) {
487 this.deviceId = deviceId;
488 this.fwd = fwd;
489 }
490
491 public DeviceId deviceId() {
492 return deviceId;
493 }
494
495 public ForwardingObjective forwardingObjective() {
496 return fwd;
497 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800498
499 @Override
500 public int hashCode() {
501 return Objects.hash(deviceId, fwd);
502 }
503
504 @Override
505 public boolean equals(final Object obj) {
506 if (this == obj) {
507 return true;
508 }
509 if (!(obj instanceof PendingNext)) {
510 return false;
511 }
512 final PendingNext other = (PendingNext) obj;
513 if (this.deviceId.equals(other.deviceId) &&
514 this.fwd.equals(other.fwd)) {
515 return true;
516 }
517 return false;
518 }
alshabibaebe7752015-04-07 17:45:42 -0700519 }
Saurav Das24431192016-03-07 19:13:00 -0800520
521 @Override
522 public List<String> getNextMappings() {
523 List<String> mappings = new ArrayList<>();
524 Map<Integer, NextGroup> allnexts = flowObjectiveStore.getAllGroups();
Saurav Das25190812016-05-27 13:54:07 -0700525 // XXX if the NextGroup after de-serialization actually stored info of the deviceId
Saurav Das24431192016-03-07 19:13:00 -0800526 // then info on any nextObj could be retrieved from one controller instance.
527 // Right now the drivers on one instance can only fetch for next-ids that came
528 // to them.
529 // Also, we still need to send the right next-id to the right driver as potentially
530 // there can be different drivers for different devices. But on that account,
531 // no instance should be decoding for another instance's nextIds.
532
533 for (Map.Entry<Integer, NextGroup> e : allnexts.entrySet()) {
534 // get the device this next Objective was sent to
535 DeviceId deviceId = nextToDevice.get(e.getKey());
536 mappings.add("NextId " + e.getKey() + ": " +
537 ((deviceId != null) ? deviceId : "nextId not in this onos instance"));
538 if (deviceId != null) {
539 // this instance of the controller sent the nextObj to a driver
540 Pipeliner pipeliner = getDevicePipeliner(deviceId);
541 List<String> nextMappings = pipeliner.getNextMappings(e.getValue());
542 if (nextMappings != null) {
543 mappings.addAll(nextMappings);
544 }
545 }
546 }
547 return mappings;
548 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700549
550 @Override
551 public List<String> getPendingNexts() {
552 List<String> pendingNexts = new ArrayList<>();
553 for (Integer nextId : pendingForwards.keySet()) {
554 Set<PendingNext> pnext = pendingForwards.get(nextId);
Charles Chan54734712017-03-29 11:07:55 -0700555
Sho SHIMIZU81470a52016-08-12 17:24:55 -0700556 StringBuilder pend = new StringBuilder();
Charles Chan54734712017-03-29 11:07:55 -0700557 pend.append("NextId: ")
558 .append(nextId);
Saurav Dasb5c236e2016-06-07 10:08:06 -0700559 for (PendingNext pn : pnext) {
Charles Chan54734712017-03-29 11:07:55 -0700560 pend.append("\n FwdId: ")
561 .append(String.format("%11s", pn.forwardingObjective().id()))
562 .append(", DeviceId: ")
563 .append(pn.deviceId())
564 .append(", Selector: ")
565 .append(pn.forwardingObjective().selector().criteria());
Saurav Dasb5c236e2016-06-07 10:08:06 -0700566 }
567 pendingNexts.add(pend.toString());
568 }
569 return pendingNexts;
570 }
alshabib77b88482015-04-07 15:47:50 -0700571}