blob: 93ddf1ac57287d55c12c131dfd34fe4f40ee7c92 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 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;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070032import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.core.ApplicationId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080034import org.onosproject.core.CoreService;
35import org.onosproject.core.IdGenerator;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080036import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080037import org.onosproject.net.Device;
38import org.onosproject.net.DeviceId;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080039import org.onosproject.net.device.DeviceEvent;
40import org.onosproject.net.device.DeviceListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.net.device.DeviceService;
42import org.onosproject.net.flow.CompletedBatchOperation;
Charles M.C. Chan1229eca2015-05-18 06:27:52 +080043import org.onosproject.net.flow.DefaultFlowEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080044import org.onosproject.net.flow.FlowEntry;
45import org.onosproject.net.flow.FlowRule;
46import org.onosproject.net.flow.FlowRuleBatchEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080047import org.onosproject.net.flow.FlowRuleBatchEvent;
48import org.onosproject.net.flow.FlowRuleBatchOperation;
49import org.onosproject.net.flow.FlowRuleBatchRequest;
50import org.onosproject.net.flow.FlowRuleEvent;
51import org.onosproject.net.flow.FlowRuleListener;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080052import org.onosproject.net.flow.FlowRuleOperation;
53import org.onosproject.net.flow.FlowRuleOperations;
54import org.onosproject.net.flow.FlowRuleOperationsContext;
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;
Brian O'Connord12267c2015-02-17 18:17:08 -080069import java.util.List;
70import java.util.Map;
71import java.util.Set;
72import java.util.concurrent.ConcurrentHashMap;
73import java.util.concurrent.ExecutorService;
74import java.util.concurrent.Executors;
75import java.util.concurrent.atomic.AtomicBoolean;
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 */
Brian O'Connord12267c2015-02-17 18:17:08 -080093@Component(immediate = true, enabled = 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 =
Brian O'Connord12267c2015-02-17 18:17:08 -0800124 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "device-installer-%d"));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800125
126 protected ExecutorService operationsService =
Brian O'Connord12267c2015-02-17 18:17:08 -0800127 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "operations-%d"));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800128
129 private IdGenerator idGenerator;
130
Brian O'Connord12267c2015-02-17 18:17:08 -0800131 private Map<Long, FlowOperationsProcessor> pendingFlowOperations
132 = new ConcurrentHashMap<>();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700133
tombe988312014-09-19 18:38:47 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected FlowRuleStore store;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700136
alshabib57044ba2014-09-16 15:58:01 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibeb55524f2014-09-18 09:59:24 -0700138 protected DeviceService deviceService;
alshabib57044ba2014-09-16 15:58:01 -0700139
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
141 protected CoreService coreService;
142
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800144 protected MastershipService mastershipService;
145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700147 protected ComponentConfigService cfgService;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800148
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700149 @Activate
150 public void activate(ComponentContext context) {
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800151 modified(context);
tomc78acee2014-09-24 15:16:55 -0700152 store.setDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700153 eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800154 deviceService.addListener(deviceListener);
155 cfgService.registerProperties(getClass());
156 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
alshabib57044ba2014-09-16 15:58:01 -0700157 log.info("Started");
158 }
159
160 @Deactivate
161 public void deactivate() {
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
Charles Chan0c7c43b2016-01-14 17:39:20 -0800193 flag = isPropertyEnabled(properties, "allowExtraneousRules");
194 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
203 flag = isPropertyEnabled(properties, "purgeOnDisconnection");
204 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
221 /**
222 * Check property name is defined and set to true.
223 *
224 * @param properties properties to be looked up
225 * @param propertyName the name of the property to look up
226 * @return value when the propertyName is defined or return null
227 */
228 private static Boolean isPropertyEnabled(Dictionary<?, ?> properties,
229 String propertyName) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800230 try {
231 String s = (String) properties.get(propertyName);
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800232 return isNullOrEmpty(s) ? null : s.trim().equals("true");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800233 } catch (ClassCastException e) {
234 // No propertyName defined.
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800235 return null;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800236 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700237 }
238
alshabib57044ba2014-09-16 15:58:01 -0700239 @Override
tom9b4030d2014-10-06 10:39:03 -0700240 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900241 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700242 return store.getFlowRuleCount();
243 }
244
245 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700246 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900247 checkPermission(FLOWRULE_READ);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700248 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700249 }
250
251 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700252 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900253 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900254
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800255 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800256 for (FlowRule flowRule : flowRules) {
257 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700258 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800259 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700260 }
261
262 @Override
263 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900264 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900265
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800266 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800267 for (FlowRule flowRule : flowRules) {
268 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700269 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800270 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700271 }
alshabib57044ba2014-09-16 15:58:01 -0700272
alshabiba68eb962014-09-24 20:34:13 -0700273 @Override
274 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900275 checkPermission(FLOWRULE_WRITE);
Madan Jampani6a456162014-10-24 11:36:17 -0700276 removeFlowRules(Iterables.toArray(getFlowRulesById(id), FlowRule.class));
alshabiba68eb962014-09-24 20:34:13 -0700277 }
278
279 @Override
280 public Iterable<FlowRule> getFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900281 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900282
Madan Jampani6a456162014-10-24 11:36:17 -0700283 Set<FlowRule> flowEntries = Sets.newHashSet();
284 for (Device d : deviceService.getDevices()) {
285 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
286 if (flowEntry.appId() == id.id()) {
287 flowEntries.add(flowEntry);
288 }
289 }
290 }
291 return flowEntries;
alshabib57044ba2014-09-16 15:58:01 -0700292 }
293
294 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800295 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900296 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900297
alshabibaa7e7de2014-11-12 19:20:44 -0800298 Set<FlowRule> matches = Sets.newHashSet();
299 long toLookUp = ((long) appId.id() << 16) | groupId;
300 for (Device d : deviceService.getDevices()) {
301 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
302 if ((flowEntry.id().value() >>> 32) == toLookUp) {
303 matches.add(flowEntry);
304 }
305 }
306 }
307 return matches;
308 }
309
310 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800311 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900312 checkPermission(FLOWRULE_WRITE);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800313 operationsService.submit(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700314 }
315
316 @Override
alshabib57044ba2014-09-16 15:58:01 -0700317 protected FlowRuleProviderService createProviderService(
318 FlowRuleProvider provider) {
319 return new InternalFlowRuleProviderService(provider);
320 }
321
322 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700323 extends AbstractProviderService<FlowRuleProvider>
324 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700325
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700326 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
327
alshabib57044ba2014-09-16 15:58:01 -0700328 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
329 super(provider);
330 }
331
332 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700333 public void flowRemoved(FlowEntry flowEntry) {
334 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700335 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700336 lastSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700337 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700338 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800339 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700340 return;
341 }
alshabib1c319ff2014-10-04 20:29:09 -0700342 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700343 FlowRuleProvider frp = getProvider(device.providerId());
344 FlowRuleEvent event = null;
345 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700346 case ADDED:
347 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700348 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700349 break;
350 case PENDING_REMOVE:
351 case REMOVED:
352 event = store.removeFlowRule(stored);
353 break;
354 default:
355 break;
alshabib57044ba2014-09-16 15:58:01 -0700356
alshabiba68eb962014-09-24 20:34:13 -0700357 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700358 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700359 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700360 post(event);
361 }
alshabib57044ba2014-09-16 15:58:01 -0700362 }
363
alshabibba5ac482014-10-02 17:15:20 -0700364
alshabib1c319ff2014-10-04 20:29:09 -0700365 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700366 checkNotNull(flowRule, FLOW_RULE_NULL);
367 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700368 Device device = deviceService.getDevice(flowRule.deviceId());
369 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700370 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700371 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700372 case PENDING_REMOVE:
373 case REMOVED:
374 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700375 break;
376 case ADDED:
377 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800378 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800379 try {
380 frp.applyFlowRule(flowRule);
381 } catch (UnsupportedOperationException e) {
382 log.warn(e.getMessage());
383 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800384 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800385 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
386 }
387 }
tom9b4030d2014-10-06 10:39:03 -0700388 break;
389 default:
390 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700391 }
392
alshabibbb42cad2014-09-25 11:43:05 -0700393 if (event != null) {
394 log.debug("Flow {} removed", flowRule);
395 post(event);
396 }
alshabib57044ba2014-09-16 15:58:01 -0700397 }
398
alshabibba5ac482014-10-02 17:15:20 -0700399 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700400 checkNotNull(flowRule, FLOW_RULE_NULL);
401 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700402 FlowRuleProvider frp = getProvider(flowRule.deviceId());
403 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700404 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700405 }
406
alshabib1c319ff2014-10-04 20:29:09 -0700407 private void flowAdded(FlowEntry flowEntry) {
408 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700409 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700410
alshabib1c319ff2014-10-04 20:29:09 -0700411 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700412 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700413 if (event == null) {
414 log.debug("No flow store event generated.");
415 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800416 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700417 post(event);
418 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700419 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800420 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700421 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700422 }
alshabib57044ba2014-09-16 15:58:01 -0700423 }
424
alshabib1c319ff2014-10-04 20:29:09 -0700425 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
426 if (storedRule == null) {
427 return false;
428 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700429 if (storedRule.isPermanent()) {
430 return true;
431 }
432
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700433 final long timeout = storedRule.timeout() * 1000;
434 final long currentTime = System.currentTimeMillis();
alshabib85c41972014-10-03 13:48:39 -0700435 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700436 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700437 return true;
438 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700439 if (!lastSeen.containsKey(storedRule)) {
440 // checking for the first time
441 lastSeen.put(storedRule, storedRule.lastSeen());
442 // Use following if lastSeen attr. was removed.
443 //lastSeen.put(storedRule, currentTime);
444 }
445 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700446
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800447 // concurrently removed? let the liveness check fail
448 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700449 }
450
alshabib5c370ff2014-09-18 10:12:14 -0700451 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700452 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900453 pushFlowMetricsInternal(deviceId, flowEntries, true);
454 }
455
456 @Override
457 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
458 pushFlowMetricsInternal(deviceId, flowEntries, false);
459 }
460
461 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
462 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700463 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
464 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
465
Saurav Dasfa2fa932015-03-03 11:29:48 -0800466 for (FlowEntry rule : flowEntries) {
467 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700468 FlowEntry storedRule = storedRules.remove(rule);
469 if (storedRule != null) {
470 if (storedRule.exactMatch(rule)) {
471 // we both have the rule, let's update some info then.
472 flowAdded(rule);
473 } else {
474 // the two rules are not an exact match - remove the
475 // switch's rule and install our rule
476 extraneousFlow(rule);
477 flowMissing(storedRule);
478 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800479 } else {
480 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700481 if (!allowExtraneousRules) {
482 extraneousFlow(rule);
483 }
alshabib93cb57f2015-02-12 17:43:26 -0800484 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700485 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800486 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800487 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800488 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900489
490 // DO NOT reinstall
491 if (useMissingFlow) {
492 for (FlowEntry rule : storedRules.keySet()) {
493 try {
494 // there are rules in the store that aren't on the switch
495 log.debug("Adding rule in store, but not on switch {}", rule);
496 flowMissing(rule);
497 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800498 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900499 }
alshabib93cb57f2015-02-12 17:43:26 -0800500 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800501 }
alshabib5c370ff2014-09-18 10:12:14 -0700502 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800503
504 @Override
505 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
506 store.batchOperationComplete(FlowRuleBatchEvent.completed(
507 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
508 operation
509 ));
510 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700511
512 @Override
513 public void pushTableStatistics(DeviceId deviceId,
514 List<TableStatisticsEntry> tableStats) {
515 store.updateTableStatistics(deviceId, tableStats);
516 }
alshabib57044ba2014-09-16 15:58:01 -0700517 }
518
tomc78acee2014-09-24 15:16:55 -0700519 // Store delegate to re-post events emitted from the store.
520 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800521
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800522
Madan Jampani117aaae2014-10-23 10:04:05 -0700523 // TODO: Right now we only dispatch events at individual flowEntry level.
524 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700525 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700526 public void notify(FlowRuleBatchEvent event) {
527 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700528 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700529 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800530 // Request has been forwarded to MASTER Node, and was
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800531 request.ops().stream().forEach(
532 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800533 switch (op.operator()) {
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700534
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800535 case ADD:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700536 post(new FlowRuleEvent(RULE_ADD_REQUESTED,
537 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800538 break;
539 case REMOVE:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700540 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED,
541 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800542 break;
543 case MODIFY:
544 //TODO: do something here when the time comes.
545 break;
546 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800547 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800548 }
549 }
550 );
551
552 DeviceId deviceId = event.deviceId();
553
554 FlowRuleBatchOperation batchOperation =
555 request.asBatchOperation(deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700556
Thomas Vachuska27bee092015-06-23 19:03:10 -0700557 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
558 if (flowRuleProvider != null) {
559 flowRuleProvider.executeBatch(batchOperation);
560 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800561
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800562 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700563
Madan Jampani117aaae2014-10-23 10:04:05 -0700564 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800565
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800566 FlowOperationsProcessor fops = pendingFlowOperations.remove(
567 event.subject().batchId());
568 if (event.result().isSuccess()) {
569 if (fops != null) {
570 fops.satisfy(event.deviceId());
571 }
572 } else {
573 fops.fail(event.deviceId(), event.result().failedItems());
574 }
575
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700576 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800577
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700578 default:
579 break;
580 }
tomc78acee2014-09-24 15:16:55 -0700581 }
582 }
alshabib902d41b2014-10-07 16:52:05 -0700583
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800584 private class FlowOperationsProcessor implements Runnable {
alshabib902d41b2014-10-07 16:52:05 -0700585
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800586 private final List<Set<FlowRuleOperation>> stages;
587 private final FlowRuleOperationsContext context;
588 private final FlowRuleOperations fops;
589 private final AtomicBoolean hasFailed = new AtomicBoolean(false);
alshabib902d41b2014-10-07 16:52:05 -0700590
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800591 private Set<DeviceId> pendingDevices;
alshabib902d41b2014-10-07 16:52:05 -0700592
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800593 public FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800594 this.stages = Lists.newArrayList(ops.stages());
595 this.context = ops.callback();
596 this.fops = ops;
597 pendingDevices = Sets.newConcurrentHashSet();
alshabib902d41b2014-10-07 16:52:05 -0700598 }
599
600 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800601 public void run() {
602 if (stages.size() > 0) {
603 process(stages.remove(0));
604 } else if (!hasFailed.get() && context != null) {
605 context.onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700606 }
607 }
608
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800609 private void process(Set<FlowRuleOperation> ops) {
610 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches =
611 ArrayListMultimap.create();
612
613 FlowRuleBatchEntry fbe;
614 for (FlowRuleOperation flowRuleOperation : ops) {
615 switch (flowRuleOperation.type()) {
616 // FIXME: Brian needs imagination when creating class names.
617 case ADD:
618 fbe = new FlowRuleBatchEntry(
619 FlowRuleBatchEntry.FlowRuleOperation.ADD, flowRuleOperation.rule());
620 break;
621 case MODIFY:
622 fbe = new FlowRuleBatchEntry(
623 FlowRuleBatchEntry.FlowRuleOperation.MODIFY, flowRuleOperation.rule());
624 break;
625 case REMOVE:
626 fbe = new FlowRuleBatchEntry(
627 FlowRuleBatchEntry.FlowRuleOperation.REMOVE, flowRuleOperation.rule());
628 break;
629 default:
630 throw new UnsupportedOperationException("Unknown flow rule type " + flowRuleOperation.type());
631 }
632 pendingDevices.add(flowRuleOperation.rule().deviceId());
633 perDeviceBatches.put(flowRuleOperation.rule().deviceId(), fbe);
634 }
635
636
637 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700638 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800639 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
640 deviceId, id);
641 pendingFlowOperations.put(id, this);
Sho SHIMIZUf88e5932015-05-27 12:03:51 -0700642 deviceInstallers.submit(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700643 }
644 }
645
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800646 public void satisfy(DeviceId devId) {
647 pendingDevices.remove(devId);
648 if (pendingDevices.isEmpty()) {
649 operationsService.submit(this);
alshabib193525b2014-10-08 18:58:03 -0700650 }
alshabib193525b2014-10-08 18:58:03 -0700651 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800652
653
654
655 public void fail(DeviceId devId, Set<? extends FlowRule> failures) {
656 hasFailed.set(true);
657 pendingDevices.remove(devId);
658 if (pendingDevices.isEmpty()) {
659 operationsService.submit(this);
660 }
661
662 if (context != null) {
663 final FlowRuleOperations.Builder failedOpsBuilder =
664 FlowRuleOperations.builder();
665 failures.stream().forEach(failedOpsBuilder::add);
666
667 context.onError(failedOpsBuilder.build());
668 }
669 }
670
alshabib902d41b2014-10-07 16:52:05 -0700671 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700672
673 @Override
674 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
675 checkPermission(FLOWRULE_READ);
676 return store.getTableStatistics(deviceId);
677 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800678
679 private class InternalDeviceListener implements DeviceListener {
680 @Override
681 public void event(DeviceEvent event) {
682 switch (event.type()) {
683 case DEVICE_REMOVED:
684 case DEVICE_AVAILABILITY_CHANGED:
685 DeviceId deviceId = event.subject().id();
686 if (!deviceService.isAvailable(deviceId)) {
687 if (purgeOnDisconnection) {
688 store.purgeFlowRule(deviceId);
689 }
690 }
691 break;
692 default:
693 break;
694 }
695 }
696 }
alshabib57044ba2014-09-16 15:58:01 -0700697}