blob: cd244ff4ee8fd71d5ecb049b4e0eeedea513f5ce [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.net.flow.impl;
alshabib57044ba2014-09-16 15:58:01 -070017
Brian O'Connord12267c2015-02-17 18:17:08 -080018import com.google.common.collect.ArrayListMultimap;
19import com.google.common.collect.Iterables;
20import com.google.common.collect.Lists;
21import com.google.common.collect.Maps;
22import com.google.common.collect.Multimap;
23import com.google.common.collect.Sets;
alshabib57044ba2014-09-16 15:58:01 -070024import org.apache.felix.scr.annotations.Activate;
25import org.apache.felix.scr.annotations.Component;
26import org.apache.felix.scr.annotations.Deactivate;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070027import org.apache.felix.scr.annotations.Modified;
28import org.apache.felix.scr.annotations.Property;
alshabib57044ba2014-09-16 15:58:01 -070029import org.apache.felix.scr.annotations.Reference;
30import org.apache.felix.scr.annotations.ReferenceCardinality;
31import org.apache.felix.scr.annotations.Service;
Jian Lid9b5f552016-03-11 18:15:31 -080032import org.onlab.util.Tools;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070033import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.core.ApplicationId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080035import org.onosproject.core.CoreService;
36import org.onosproject.core.IdGenerator;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080037import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.Device;
39import org.onosproject.net.DeviceId;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080040import org.onosproject.net.device.DeviceEvent;
41import org.onosproject.net.device.DeviceListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.device.DeviceService;
43import org.onosproject.net.flow.CompletedBatchOperation;
Charles M.C. Chan1229eca2015-05-18 06:27:52 +080044import org.onosproject.net.flow.DefaultFlowEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080045import org.onosproject.net.flow.FlowEntry;
46import org.onosproject.net.flow.FlowRule;
47import org.onosproject.net.flow.FlowRuleBatchEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.net.flow.FlowRuleBatchEvent;
49import org.onosproject.net.flow.FlowRuleBatchOperation;
50import org.onosproject.net.flow.FlowRuleBatchRequest;
51import org.onosproject.net.flow.FlowRuleEvent;
52import org.onosproject.net.flow.FlowRuleListener;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080053import org.onosproject.net.flow.FlowRuleOperation;
54import org.onosproject.net.flow.FlowRuleOperations;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.flow.FlowRuleProvider;
56import org.onosproject.net.flow.FlowRuleProviderRegistry;
57import org.onosproject.net.flow.FlowRuleProviderService;
58import org.onosproject.net.flow.FlowRuleService;
59import org.onosproject.net.flow.FlowRuleStore;
60import org.onosproject.net.flow.FlowRuleStoreDelegate;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070061import org.onosproject.net.flow.TableStatisticsEntry;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080062import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.provider.AbstractProviderService;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070064import org.osgi.service.component.ComponentContext;
alshabib57044ba2014-09-16 15:58:01 -070065import org.slf4j.Logger;
66
Brian O'Connord12267c2015-02-17 18:17:08 -080067import java.util.Collections;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070068import java.util.Dictionary;
Sho SHIMIZUb837cb72016-08-30 14:44:50 -070069import java.util.HashSet;
Brian O'Connord12267c2015-02-17 18:17:08 -080070import java.util.List;
71import java.util.Map;
72import java.util.Set;
73import java.util.concurrent.ConcurrentHashMap;
74import java.util.concurrent.ExecutorService;
75import java.util.concurrent.Executors;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080076
Thomas Vachuska9b2da212014-11-10 19:30:25 -080077import static com.google.common.base.Preconditions.checkNotNull;
Charles Chan0c7c43b2016-01-14 17:39:20 -080078import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080079import static org.onlab.util.Tools.get;
Brian O'Connord12267c2015-02-17 18:17:08 -080080import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070081import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_ADD_REQUESTED;
82import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVE_REQUESTED;
Changhoon Yoon541ef712015-05-23 17:18:34 +090083import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080084import static org.onosproject.security.AppPermission.Type.FLOWRULE_READ;
85import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070086import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +090087
Changhoon Yoon541ef712015-05-23 17:18:34 +090088
alshabiba7f7ca82014-09-22 11:41:23 -070089
tome4729872014-09-23 00:37:37 -070090/**
91 * Provides implementation of the flow NB & SB APIs.
92 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -070093@Component(immediate = true)
alshabib57044ba2014-09-16 15:58:01 -070094@Service
tom202175a2014-09-19 19:00:11 -070095public class FlowRuleManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070096 extends AbstractListenerProviderRegistry<FlowRuleEvent, FlowRuleListener,
97 FlowRuleProvider, FlowRuleProviderService>
tom9b4030d2014-10-06 10:39:03 -070098 implements FlowRuleService, FlowRuleProviderRegistry {
alshabib57044ba2014-09-16 15:58:01 -070099
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800100 private final Logger log = getLogger(getClass());
101
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700102 public static final String FLOW_RULE_NULL = "FlowRule cannot be null";
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700103 private static final boolean ALLOW_EXTRANEOUS_RULES = false;
104
105 @Property(name = "allowExtraneousRules", boolValue = ALLOW_EXTRANEOUS_RULES,
106 label = "Allow flow rules in switch not installed by ONOS")
107 private boolean allowExtraneousRules = ALLOW_EXTRANEOUS_RULES;
108
Charles Chan0c7c43b2016-01-14 17:39:20 -0800109 @Property(name = "purgeOnDisconnection", boolValue = false,
110 label = "Purge entries associated with a device when the device goes offline")
111 private boolean purgeOnDisconnection = false;
112
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800113 private static final int DEFAULT_POLL_FREQUENCY = 30;
114 @Property(name = "fallbackFlowPollFrequency", intValue = DEFAULT_POLL_FREQUENCY,
115 label = "Frequency (in seconds) for polling flow statistics via fallback provider")
116 private int fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
alshabib57044ba2014-09-16 15:58:01 -0700117
alshabibbb42cad2014-09-25 11:43:05 -0700118 private final FlowRuleStoreDelegate delegate = new InternalStoreDelegate();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800119 private final DeviceListener deviceListener = new InternalDeviceListener();
tomc78acee2014-09-24 15:16:55 -0700120
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800121 private final FlowRuleDriverProvider defaultProvider = new FlowRuleDriverProvider();
122
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800123 protected ExecutorService deviceInstallers =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800124 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "device-installer-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800125
126 protected ExecutorService operationsService =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700127 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "operations-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800128
129 private IdGenerator idGenerator;
130
Sho SHIMIZU9f950742016-09-01 09:55:38 -0700131 private final Map<Long, FlowOperationsProcessor> pendingFlowOperations = new ConcurrentHashMap<>();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700132
tombe988312014-09-19 18:38:47 -0700133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
134 protected FlowRuleStore store;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700135
alshabib57044ba2014-09-16 15:58:01 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibeb55524f2014-09-18 09:59:24 -0700137 protected DeviceService deviceService;
alshabib57044ba2014-09-16 15:58:01 -0700138
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
140 protected CoreService coreService;
141
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700142 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800143 protected MastershipService mastershipService;
144
145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700146 protected ComponentConfigService cfgService;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800147
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700148 @Activate
149 public void activate(ComponentContext context) {
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800150 modified(context);
tomc78acee2014-09-24 15:16:55 -0700151 store.setDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700152 eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800153 deviceService.addListener(deviceListener);
154 cfgService.registerProperties(getClass());
155 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
alshabib57044ba2014-09-16 15:58:01 -0700156 log.info("Started");
157 }
158
159 @Deactivate
160 public void deactivate() {
Andrea Campanella3f1c61e2016-04-01 17:30:12 -0700161 deviceService.removeListener(deviceListener);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700162 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800163 deviceInstallers.shutdownNow();
164 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700165 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700166 eventDispatcher.removeSink(FlowRuleEvent.class);
167 log.info("Stopped");
168 }
169
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700170 @Modified
171 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800172 if (context != null) {
173 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700174 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800175 defaultProvider.init(new InternalFlowRuleProviderService(defaultProvider),
176 deviceService, mastershipService, fallbackFlowPollFrequency);
177 }
178
179 @Override
180 protected FlowRuleProvider defaultProvider() {
181 return defaultProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800182 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700183
Charles Chan0c7c43b2016-01-14 17:39:20 -0800184 /**
185 * Extracts properties from the component configuration context.
186 *
187 * @param context the component context
188 */
189 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700190 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800191 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700192
Jian Lid9b5f552016-03-11 18:15:31 -0800193 flag = Tools.isPropertyEnabled(properties, "allowExtraneousRules");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800194 if (flag == null) {
195 log.info("AllowExtraneousRules is not configured, " +
196 "using current value of {}", allowExtraneousRules);
197 } else {
198 allowExtraneousRules = flag;
199 log.info("Configured. AllowExtraneousRules is {}",
200 allowExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700201 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800202
Jian Lid9b5f552016-03-11 18:15:31 -0800203 flag = Tools.isPropertyEnabled(properties, "purgeOnDisconnection");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800204 if (flag == null) {
205 log.info("PurgeOnDisconnection is not configured, " +
206 "using current value of {}", purgeOnDisconnection);
207 } else {
208 purgeOnDisconnection = flag;
209 log.info("Configured. PurgeOnDisconnection is {}",
210 purgeOnDisconnection ? "enabled" : "disabled");
211 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800212
213 String s = get(properties, "fallbackFlowPollFrequency");
214 try {
215 fallbackFlowPollFrequency = isNullOrEmpty(s) ? DEFAULT_POLL_FREQUENCY : Integer.parseInt(s);
216 } catch (NumberFormatException e) {
217 fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
218 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800219 }
220
alshabib57044ba2014-09-16 15:58:01 -0700221 @Override
tom9b4030d2014-10-06 10:39:03 -0700222 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900223 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700224 return store.getFlowRuleCount();
225 }
226
227 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700228 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900229 checkPermission(FLOWRULE_READ);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700230 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700231 }
232
233 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700234 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900235 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900236
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800237 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800238 for (FlowRule flowRule : flowRules) {
239 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700240 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800241 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700242 }
243
244 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530245 public void purgeFlowRules(DeviceId deviceId) {
246 checkPermission(FLOWRULE_WRITE);
247 store.purgeFlowRule(deviceId);
248 }
249
250 @Override
alshabib57044ba2014-09-16 15:58:01 -0700251 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900252 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900253
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800254 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800255 for (FlowRule flowRule : flowRules) {
256 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700257 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800258 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700259 }
alshabib57044ba2014-09-16 15:58:01 -0700260
alshabiba68eb962014-09-24 20:34:13 -0700261 @Override
262 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900263 checkPermission(FLOWRULE_WRITE);
Madan Jampani6a456162014-10-24 11:36:17 -0700264 removeFlowRules(Iterables.toArray(getFlowRulesById(id), FlowRule.class));
alshabiba68eb962014-09-24 20:34:13 -0700265 }
266
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530267 @Deprecated
alshabiba68eb962014-09-24 20:34:13 -0700268 @Override
269 public Iterable<FlowRule> getFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900270 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900271
Madan Jampani6a456162014-10-24 11:36:17 -0700272 Set<FlowRule> flowEntries = Sets.newHashSet();
273 for (Device d : deviceService.getDevices()) {
274 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
275 if (flowEntry.appId() == id.id()) {
276 flowEntries.add(flowEntry);
277 }
278 }
279 }
280 return flowEntries;
alshabib57044ba2014-09-16 15:58:01 -0700281 }
282
283 @Override
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530284 public Iterable<FlowEntry> getFlowEntriesById(ApplicationId id) {
285 checkPermission(FLOWRULE_READ);
286
287 Set<FlowEntry> flowEntries = Sets.newHashSet();
288 for (Device d : deviceService.getDevices()) {
289 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
290 if (flowEntry.appId() == id.id()) {
291 flowEntries.add(flowEntry);
292 }
293 }
294 }
295 return flowEntries;
296 }
297
298 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800299 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900300 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900301
alshabibaa7e7de2014-11-12 19:20:44 -0800302 Set<FlowRule> matches = Sets.newHashSet();
303 long toLookUp = ((long) appId.id() << 16) | groupId;
304 for (Device d : deviceService.getDevices()) {
305 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
306 if ((flowEntry.id().value() >>> 32) == toLookUp) {
307 matches.add(flowEntry);
308 }
309 }
310 }
311 return matches;
312 }
313
314 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800315 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900316 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700317 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700318 }
319
320 @Override
alshabib57044ba2014-09-16 15:58:01 -0700321 protected FlowRuleProviderService createProviderService(
322 FlowRuleProvider provider) {
323 return new InternalFlowRuleProviderService(provider);
324 }
325
326 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700327 extends AbstractProviderService<FlowRuleProvider>
328 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700329
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700330 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700331 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
332
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700333
alshabib57044ba2014-09-16 15:58:01 -0700334 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
335 super(provider);
336 }
337
338 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700339 public void flowRemoved(FlowEntry flowEntry) {
340 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700341 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700342 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700343 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700344 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700345 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800346 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700347 return;
348 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700349 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
350 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
351 }
alshabib1c319ff2014-10-04 20:29:09 -0700352 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700353 FlowRuleProvider frp = getProvider(device.providerId());
354 FlowRuleEvent event = null;
355 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700356 case ADDED:
357 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700358 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700359 break;
360 case PENDING_REMOVE:
361 case REMOVED:
362 event = store.removeFlowRule(stored);
363 break;
364 default:
365 break;
alshabib57044ba2014-09-16 15:58:01 -0700366
alshabiba68eb962014-09-24 20:34:13 -0700367 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700368 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700369 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700370 post(event);
371 }
alshabib57044ba2014-09-16 15:58:01 -0700372 }
373
alshabibba5ac482014-10-02 17:15:20 -0700374
alshabib1c319ff2014-10-04 20:29:09 -0700375 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700376 checkNotNull(flowRule, FLOW_RULE_NULL);
377 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700378 Device device = deviceService.getDevice(flowRule.deviceId());
379 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700380 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700381 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700382 case PENDING_REMOVE:
383 case REMOVED:
384 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700385 break;
386 case ADDED:
387 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800388 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800389 try {
390 frp.applyFlowRule(flowRule);
391 } catch (UnsupportedOperationException e) {
392 log.warn(e.getMessage());
393 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800394 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800395 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
396 }
397 }
tom9b4030d2014-10-06 10:39:03 -0700398 break;
399 default:
400 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700401 }
402
alshabibbb42cad2014-09-25 11:43:05 -0700403 if (event != null) {
404 log.debug("Flow {} removed", flowRule);
405 post(event);
406 }
alshabib57044ba2014-09-16 15:58:01 -0700407 }
408
alshabibba5ac482014-10-02 17:15:20 -0700409 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700410 checkNotNull(flowRule, FLOW_RULE_NULL);
411 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700412 FlowRuleProvider frp = getProvider(flowRule.deviceId());
413 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700414 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700415 }
416
alshabib1c319ff2014-10-04 20:29:09 -0700417 private void flowAdded(FlowEntry flowEntry) {
418 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700419 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700420
alshabib1c319ff2014-10-04 20:29:09 -0700421 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700422 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700423 if (event == null) {
424 log.debug("No flow store event generated.");
425 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800426 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700427 post(event);
428 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700429 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800430 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700431 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700432 }
alshabib57044ba2014-09-16 15:58:01 -0700433 }
434
alshabib1c319ff2014-10-04 20:29:09 -0700435 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
436 if (storedRule == null) {
437 return false;
438 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700439 if (storedRule.isPermanent()) {
440 return true;
441 }
442
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700443 final long timeout = storedRule.timeout() * 1000;
444 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700445
446 // Checking flow with hardTimeout
447 if (storedRule.hardTimeout() != 0) {
448 if (!firstSeen.containsKey(storedRule)) {
449 // First time rule adding
450 firstSeen.put(storedRule, currentTime);
451 } else {
452 Long first = firstSeen.get(storedRule);
453 final long hardTimeout = storedRule.hardTimeout() * 1000;
454 if ((currentTime - first) > hardTimeout) {
455 return false;
456 }
457 }
458 }
459
alshabib85c41972014-10-03 13:48:39 -0700460 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700461 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700462 return true;
463 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700464 if (!lastSeen.containsKey(storedRule)) {
465 // checking for the first time
466 lastSeen.put(storedRule, storedRule.lastSeen());
467 // Use following if lastSeen attr. was removed.
468 //lastSeen.put(storedRule, currentTime);
469 }
470 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700471
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800472 // concurrently removed? let the liveness check fail
473 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700474 }
475
alshabib5c370ff2014-09-18 10:12:14 -0700476 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700477 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900478 pushFlowMetricsInternal(deviceId, flowEntries, true);
479 }
480
481 @Override
482 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
483 pushFlowMetricsInternal(deviceId, flowEntries, false);
484 }
485
486 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
487 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700488 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
489 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
490
Saurav Dasfa2fa932015-03-03 11:29:48 -0800491 for (FlowEntry rule : flowEntries) {
492 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700493 FlowEntry storedRule = storedRules.remove(rule);
494 if (storedRule != null) {
495 if (storedRule.exactMatch(rule)) {
496 // we both have the rule, let's update some info then.
497 flowAdded(rule);
498 } else {
499 // the two rules are not an exact match - remove the
500 // switch's rule and install our rule
501 extraneousFlow(rule);
502 flowMissing(storedRule);
503 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800504 } else {
505 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700506 if (!allowExtraneousRules) {
507 extraneousFlow(rule);
508 }
alshabib93cb57f2015-02-12 17:43:26 -0800509 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700510 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800511 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800512 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800513 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900514
515 // DO NOT reinstall
516 if (useMissingFlow) {
517 for (FlowEntry rule : storedRules.keySet()) {
518 try {
519 // there are rules in the store that aren't on the switch
520 log.debug("Adding rule in store, but not on switch {}", rule);
521 flowMissing(rule);
522 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800523 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900524 }
alshabib93cb57f2015-02-12 17:43:26 -0800525 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800526 }
alshabib5c370ff2014-09-18 10:12:14 -0700527 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800528
529 @Override
530 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
531 store.batchOperationComplete(FlowRuleBatchEvent.completed(
532 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
533 operation
534 ));
535 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700536
537 @Override
538 public void pushTableStatistics(DeviceId deviceId,
539 List<TableStatisticsEntry> tableStats) {
540 store.updateTableStatistics(deviceId, tableStats);
541 }
alshabib57044ba2014-09-16 15:58:01 -0700542 }
543
tomc78acee2014-09-24 15:16:55 -0700544 // Store delegate to re-post events emitted from the store.
545 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800546
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800547
Madan Jampani117aaae2014-10-23 10:04:05 -0700548 // TODO: Right now we only dispatch events at individual flowEntry level.
549 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700550 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700551 public void notify(FlowRuleBatchEvent event) {
552 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700553 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700554 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800555 // Request has been forwarded to MASTER Node, and was
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700556 request.ops().forEach(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800557 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800558 switch (op.operator()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800559 case ADD:
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700560 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800561 break;
562 case REMOVE:
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700563 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800564 break;
565 case MODIFY:
566 //TODO: do something here when the time comes.
567 break;
568 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800569 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800570 }
571 }
572 );
573
574 DeviceId deviceId = event.deviceId();
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700575 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
Thomas Vachuska27bee092015-06-23 19:03:10 -0700576 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
577 if (flowRuleProvider != null) {
578 flowRuleProvider.executeBatch(batchOperation);
579 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800580
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800581 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700582
Madan Jampani117aaae2014-10-23 10:04:05 -0700583 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800584
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800585 FlowOperationsProcessor fops = pendingFlowOperations.remove(
586 event.subject().batchId());
587 if (event.result().isSuccess()) {
588 if (fops != null) {
589 fops.satisfy(event.deviceId());
590 }
591 } else {
592 fops.fail(event.deviceId(), event.result().failedItems());
593 }
594
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700595 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800596
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700597 default:
598 break;
599 }
tomc78acee2014-09-24 15:16:55 -0700600 }
601 }
alshabib902d41b2014-10-07 16:52:05 -0700602
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700603 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
604 switch (input) {
605 case ADD:
606 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
607 case MODIFY:
608 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
609 case REMOVE:
610 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
611 default:
612 throw new UnsupportedOperationException("Unknown flow rule type " + input);
613 }
614 }
615
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800616 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700617 // Immutable
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800618 private final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700619
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700620 // Mutable
621 private final List<Set<FlowRuleOperation>> stages;
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700622 private final Set<DeviceId> pendingDevices = new HashSet<>();
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700623 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700624
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700625 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800626 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800627 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700628 }
629
630 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700631 public synchronized void run() {
Jon Hallcbd1b392017-01-18 20:15:44 -0800632 if (!stages.isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800633 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700634 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700635 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700636 }
637 }
638
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800639 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700640 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800641
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700642 for (FlowRuleOperation op : ops) {
643 perDeviceBatches.put(op.rule().deviceId(),
644 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800645 }
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000646 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800647
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800648 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700649 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800650 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
651 deviceId, id);
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000652 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700653 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700654 }
655 }
656
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700657 synchronized void satisfy(DeviceId devId) {
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000658 pendingDevices.remove(devId);
659 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700660 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700661 }
alshabib193525b2014-10-08 18:58:03 -0700662 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800663
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700664 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZUb9e0ab72016-09-14 16:54:13 -0700665 hasFailed = true;
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000666 pendingDevices.remove(devId);
667 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700668 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800669 }
670
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700671 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
672 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800673
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700674 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800675 }
alshabib902d41b2014-10-07 16:52:05 -0700676 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700677
678 @Override
679 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
680 checkPermission(FLOWRULE_READ);
681 return store.getTableStatistics(deviceId);
682 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800683
684 private class InternalDeviceListener implements DeviceListener {
685 @Override
686 public void event(DeviceEvent event) {
687 switch (event.type()) {
688 case DEVICE_REMOVED:
689 case DEVICE_AVAILABILITY_CHANGED:
690 DeviceId deviceId = event.subject().id();
691 if (!deviceService.isAvailable(deviceId)) {
692 if (purgeOnDisconnection) {
693 store.purgeFlowRule(deviceId);
694 }
695 }
696 break;
697 default:
698 break;
699 }
700 }
701 }
alshabib57044ba2014-09-16 15:58:01 -0700702}