blob: d9aca56b962a554e49f3ef2c45ce2e593e3cfe79 [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 ||
268 flowObjectiveStore.getNextGroup(fwd.nextId()) != null) {
269 // fast path
270 return false;
alshabib2a441c62015-04-13 18:39:38 -0700271 }
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700272 boolean queued = false;
273 synchronized (pendingForwards) {
274 // double check the flow objective store, because this block could run
275 // after a notification arrives
276 if (flowObjectiveStore.getNextGroup(fwd.nextId()) == null) {
277 pendingForwards.compute(fwd.nextId(), (id, pending) -> {
278 PendingNext next = new PendingNext(deviceId, fwd);
279 if (pending == null) {
280 return Sets.newHashSet(next);
281 } else {
282 pending.add(next);
283 return pending;
284 }
285 });
286 queued = true;
287 }
288 }
289 if (queued) {
290 log.debug("Queued forwarding objective {} for nextId {} meant for device {}",
291 fwd.id(), fwd.nextId(), deviceId);
292 }
293 return queued;
alshabib2a441c62015-04-13 18:39:38 -0700294 }
295
Pier Ventre57a61cd2016-09-07 10:55:41 -0700296 /**
297 * Retrieves (if it exists) the device pipeline behaviour from the cache.
298 * Otherwise it warms the caches and triggers the init method of the Pipeline.
299 *
300 * @param deviceId the id of the device associated to the pipeline
301 * @return the implementation of the Pipeliner behaviour
302 */
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700303 private Pipeliner getDevicePipeliner(DeviceId deviceId) {
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700304 return pipeliners.computeIfAbsent(deviceId, this::initPipelineHandler);
alshabib77b88482015-04-07 15:47:50 -0700305 }
306
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700307 /**
Pier Ventre57a61cd2016-09-07 10:55:41 -0700308 * Retrieves (if it exists) the device pipeline behaviour from the cache and
309 * and triggers the init method of the pipeline. Otherwise (DEVICE_ADDED) it warms
310 * the caches and triggers the init method of the Pipeline. The rationale of this
311 * method is for managing the scenario of a switch that goes down for a failure
312 * and goes up after a while.
313 *
314 * @param deviceId the id of the device associated to the pipeline
315 * @return the implementation of the Pipeliner behaviour
316 */
317 private Pipeliner getAndInitDevicePipeliner(DeviceId deviceId) {
318 return pipeliners.compute(deviceId, (deviceIdValue, pipelinerValue) -> {
319 if (pipelinerValue != null) {
320 pipelinerValue.init(deviceId, context);
321 return pipelinerValue;
322 }
323 return this.initPipelineHandler(deviceId);
324 });
325 }
326
327 /**
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700328 * Creates and initialize {@link Pipeliner}.
329 * <p>
330 * Note: Expected to be called under per-Device lock.
331 * e.g., {@code pipeliners}' Map#compute family methods
332 *
333 * @param deviceId Device to initialize pipeliner
334 * @return {@link Pipeliner} instance or null
335 */
336 private Pipeliner initPipelineHandler(DeviceId deviceId) {
337 start = now();
Thomas Vachuska866b46a2015-04-30 00:26:55 -0700338
Jonathan Hart17d00452015-04-21 17:10:00 -0700339 // Attempt to lookup the handler in the cache
340 DriverHandler handler = driverHandlers.get(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700341 cTime = now();
342
Jonathan Hart17d00452015-04-21 17:10:00 -0700343 if (handler == null) {
344 try {
345 // Otherwise create it and if it has pipeline behaviour, cache it
346 handler = driverService.createHandler(deviceId);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700347 dTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700348 if (!handler.driver().hasBehaviour(Pipeliner.class)) {
349 log.warn("Pipeline behaviour not supported for device {}",
350 deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700351 return null;
alshabib2a441c62015-04-13 18:39:38 -0700352 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700353 } catch (ItemNotFoundException e) {
354 log.warn("No applicable driver for device {}", deviceId);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700355 return null;
alshabib2a441c62015-04-13 18:39:38 -0700356 }
357
Jonathan Hart17d00452015-04-21 17:10:00 -0700358 driverHandlers.put(deviceId, handler);
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700359 eTime = now();
alshabib2a441c62015-04-13 18:39:38 -0700360 }
Jonathan Hart17d00452015-04-21 17:10:00 -0700361
362 // Always (re)initialize the pipeline behaviour
363 log.info("Driver {} bound to device {} ... initializing driver",
364 handler.driver().name(), deviceId);
Thomas Vachuska0121a612015-07-21 11:18:09 -0700365 hTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700366 Pipeliner pipeliner = handler.behaviour(Pipeliner.class);
Thomas Vachuska94c3cf42015-07-20 13:01:12 -0700367 hbTime = now();
Jonathan Hart17d00452015-04-21 17:10:00 -0700368 pipeliner.init(deviceId, context);
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700369 stopWatch();
370 return pipeliner;
alshabibaebe7752015-04-07 17:45:42 -0700371 }
alshabib77b88482015-04-07 15:47:50 -0700372
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700373 // Triggers driver setup when a device is (re)detected.
alshabibaebe7752015-04-07 17:45:42 -0700374 private class InnerDeviceListener implements DeviceListener {
375 @Override
376 public void event(DeviceEvent event) {
377 switch (event.type()) {
378 case DEVICE_ADDED:
379 case DEVICE_AVAILABILITY_CHANGED:
Madan Jampani0174f452015-05-29 11:52:05 -0700380 log.debug("Device either added or availability changed {}",
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700381 event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700382 if (deviceService.isAvailable(event.subject().id())) {
Madan Jampani0174f452015-05-29 11:52:05 -0700383 log.debug("Device is now available {}", event.subject().id());
Pier Ventre57a61cd2016-09-07 10:55:41 -0700384 getAndInitDevicePipeliner(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700385 } else {
386 log.debug("Device is no longer available {}", event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700387 }
388 break;
389 case DEVICE_UPDATED:
390 break;
391 case DEVICE_REMOVED:
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700392 // evict Pipeliner and Handler cache, when
393 // the Device was administratively removed.
394 //
395 // System expect the user to clear all existing flows,
396 // before removing device, especially if they intend to
397 // replace driver/pipeliner assigned to the device.
398 driverHandlers.remove(event.subject().id());
Yuta HIGUCHI1fb0a8c2016-08-12 10:59:24 -0700399 pipeliners.remove(event.subject().id());
alshabib4313d102015-04-08 18:55:08 -0700400 break;
Yuta HIGUCHIad0c9902016-08-23 10:37:32 -0700401 case DEVICE_SUSPENDED:
402 break;
alshabib4313d102015-04-08 18:55:08 -0700403 case PORT_ADDED:
404 break;
405 case PORT_UPDATED:
406 break;
407 case PORT_REMOVED:
alshabibaebe7752015-04-07 17:45:42 -0700408 break;
409 default:
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700410 break;
alshabibaebe7752015-04-07 17:45:42 -0700411 }
alshabib77b88482015-04-07 15:47:50 -0700412 }
413 }
alshabibaebe7752015-04-07 17:45:42 -0700414
Thomas Vachuska174bb912015-07-16 21:27:14 -0700415 // Temporary mechanism to monitor pipeliner setup time-cost; there are
416 // intermittent time where this takes in excess of 2 seconds. Why?
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700417 private long start = 0, totals = 0, count = 0;
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700418 private long cTime, dTime, eTime, hTime, hbTime;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700419 private static final long LIMIT = 500;
Thomas Vachuska174bb912015-07-16 21:27:14 -0700420
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700421 private long now() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700422 return System.currentTimeMillis();
423 }
424
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700425 private void stopWatch() {
Thomas Vachuska174bb912015-07-16 21:27:14 -0700426 long duration = System.currentTimeMillis() - start;
427 totals += duration;
428 count += 1;
429 if (duration > LIMIT) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700430 log.info("Pipeline setup took {} ms; avg {} ms; cTime={}, dTime={}, eTime={}, hTime={}, hbTime={}",
431 duration, totals / count, diff(cTime), diff(dTime), diff(eTime), diff(hTime), diff(hbTime));
Thomas Vachuska174bb912015-07-16 21:27:14 -0700432 }
433 }
434
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700435 private long diff(long bTime) {
Thomas Vachuskab19bffb2015-07-22 10:56:16 -0700436 long diff = bTime - start;
437 return diff < 0 ? 0 : diff;
Thomas Vachuska9c9ff7c2015-07-20 10:38:59 -0700438 }
439
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700440 // Processing context for initializing pipeline driver behaviours.
441 private class InnerPipelineContext implements PipelinerContext {
442 @Override
443 public ServiceDirectory directory() {
444 return serviceDirectory;
alshabibaebe7752015-04-07 17:45:42 -0700445 }
alshabib2a441c62015-04-13 18:39:38 -0700446
447 @Override
448 public FlowObjectiveStore store() {
449 return flowObjectiveStore;
450 }
alshabib2a441c62015-04-13 18:39:38 -0700451 }
452
453 private class InternalStoreDelegate implements FlowObjectiveStoreDelegate {
454 @Override
455 public void notify(ObjectiveEvent event) {
Saurav Das423fe2b2015-12-04 10:52:59 -0800456 if (event.type() == Type.ADD) {
457 log.debug("Received notification of obj event {}", event);
Thomas Vachuskad27097c2016-06-14 19:10:41 -0700458 Set<PendingNext> pending;
459 synchronized (pendingForwards) {
460 // needs to be synchronized for queueObjective lookup
461 pending = pendingForwards.remove(event.subject());
462 }
alshabib2a441c62015-04-13 18:39:38 -0700463
Saurav Das423fe2b2015-12-04 10:52:59 -0800464 if (pending == null) {
Saurav Das25190812016-05-27 13:54:07 -0700465 log.debug("Nothing pending for this obj event {}", event);
Saurav Das423fe2b2015-12-04 10:52:59 -0800466 return;
467 }
468
Saurav Das49cb5a12016-01-16 22:54:07 -0800469 log.debug("Processing {} pending forwarding objectives for nextId {}",
470 pending.size(), event.subject());
Saurav Das423fe2b2015-12-04 10:52:59 -0800471 pending.forEach(p -> getDevicePipeliner(p.deviceId())
472 .forward(p.forwardingObjective()));
alshabib2a441c62015-04-13 18:39:38 -0700473 }
alshabib2a441c62015-04-13 18:39:38 -0700474 }
475 }
476
477 /**
478 * Data class used to hold a pending forwarding objective that could not
479 * be processed because the associated next object was not present.
480 */
481 private class PendingNext {
482 private final DeviceId deviceId;
483 private final ForwardingObjective fwd;
484
485 public PendingNext(DeviceId deviceId, ForwardingObjective fwd) {
486 this.deviceId = deviceId;
487 this.fwd = fwd;
488 }
489
490 public DeviceId deviceId() {
491 return deviceId;
492 }
493
494 public ForwardingObjective forwardingObjective() {
495 return fwd;
496 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800497
498 @Override
499 public int hashCode() {
500 return Objects.hash(deviceId, fwd);
501 }
502
503 @Override
504 public boolean equals(final Object obj) {
505 if (this == obj) {
506 return true;
507 }
508 if (!(obj instanceof PendingNext)) {
509 return false;
510 }
511 final PendingNext other = (PendingNext) obj;
512 if (this.deviceId.equals(other.deviceId) &&
513 this.fwd.equals(other.fwd)) {
514 return true;
515 }
516 return false;
517 }
alshabibaebe7752015-04-07 17:45:42 -0700518 }
Saurav Das24431192016-03-07 19:13:00 -0800519
520 @Override
521 public List<String> getNextMappings() {
522 List<String> mappings = new ArrayList<>();
523 Map<Integer, NextGroup> allnexts = flowObjectiveStore.getAllGroups();
Saurav Das25190812016-05-27 13:54:07 -0700524 // XXX if the NextGroup after de-serialization actually stored info of the deviceId
Saurav Das24431192016-03-07 19:13:00 -0800525 // then info on any nextObj could be retrieved from one controller instance.
526 // Right now the drivers on one instance can only fetch for next-ids that came
527 // to them.
528 // Also, we still need to send the right next-id to the right driver as potentially
529 // there can be different drivers for different devices. But on that account,
530 // no instance should be decoding for another instance's nextIds.
531
532 for (Map.Entry<Integer, NextGroup> e : allnexts.entrySet()) {
533 // get the device this next Objective was sent to
534 DeviceId deviceId = nextToDevice.get(e.getKey());
535 mappings.add("NextId " + e.getKey() + ": " +
536 ((deviceId != null) ? deviceId : "nextId not in this onos instance"));
537 if (deviceId != null) {
538 // this instance of the controller sent the nextObj to a driver
539 Pipeliner pipeliner = getDevicePipeliner(deviceId);
540 List<String> nextMappings = pipeliner.getNextMappings(e.getValue());
541 if (nextMappings != null) {
542 mappings.addAll(nextMappings);
543 }
544 }
545 }
546 return mappings;
547 }
Saurav Dasb5c236e2016-06-07 10:08:06 -0700548
549 @Override
550 public List<String> getPendingNexts() {
551 List<String> pendingNexts = new ArrayList<>();
552 for (Integer nextId : pendingForwards.keySet()) {
553 Set<PendingNext> pnext = pendingForwards.get(nextId);
Sho SHIMIZU81470a52016-08-12 17:24:55 -0700554 StringBuilder pend = new StringBuilder();
Saurav Dasb5c236e2016-06-07 10:08:06 -0700555 pend.append("Next Id: ").append(Integer.toString(nextId))
556 .append(" :: ");
557 for (PendingNext pn : pnext) {
558 pend.append(Integer.toString(pn.forwardingObjective().id()))
559 .append(" ");
560 }
561 pendingNexts.add(pend.toString());
562 }
563 return pendingNexts;
564 }
alshabib77b88482015-04-07 15:47:50 -0700565}