blob: 9e0db6a397dc0cee2f51474b72e970d92f18e1eb [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
267 @Override
268 public Iterable<FlowRule> getFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900269 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900270
Madan Jampani6a456162014-10-24 11:36:17 -0700271 Set<FlowRule> flowEntries = Sets.newHashSet();
272 for (Device d : deviceService.getDevices()) {
273 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
274 if (flowEntry.appId() == id.id()) {
275 flowEntries.add(flowEntry);
276 }
277 }
278 }
279 return flowEntries;
alshabib57044ba2014-09-16 15:58:01 -0700280 }
281
282 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800283 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900284 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900285
alshabibaa7e7de2014-11-12 19:20:44 -0800286 Set<FlowRule> matches = Sets.newHashSet();
287 long toLookUp = ((long) appId.id() << 16) | groupId;
288 for (Device d : deviceService.getDevices()) {
289 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
290 if ((flowEntry.id().value() >>> 32) == toLookUp) {
291 matches.add(flowEntry);
292 }
293 }
294 }
295 return matches;
296 }
297
298 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800299 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900300 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700301 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700302 }
303
304 @Override
alshabib57044ba2014-09-16 15:58:01 -0700305 protected FlowRuleProviderService createProviderService(
306 FlowRuleProvider provider) {
307 return new InternalFlowRuleProviderService(provider);
308 }
309
310 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700311 extends AbstractProviderService<FlowRuleProvider>
312 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700313
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700314 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700315 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
316
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700317
alshabib57044ba2014-09-16 15:58:01 -0700318 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
319 super(provider);
320 }
321
322 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700323 public void flowRemoved(FlowEntry flowEntry) {
324 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700325 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700326 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700327 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700328 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700329 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800330 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700331 return;
332 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700333 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
334 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
335 }
alshabib1c319ff2014-10-04 20:29:09 -0700336 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700337 FlowRuleProvider frp = getProvider(device.providerId());
338 FlowRuleEvent event = null;
339 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700340 case ADDED:
341 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700342 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700343 break;
344 case PENDING_REMOVE:
345 case REMOVED:
346 event = store.removeFlowRule(stored);
347 break;
348 default:
349 break;
alshabib57044ba2014-09-16 15:58:01 -0700350
alshabiba68eb962014-09-24 20:34:13 -0700351 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700352 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700353 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700354 post(event);
355 }
alshabib57044ba2014-09-16 15:58:01 -0700356 }
357
alshabibba5ac482014-10-02 17:15:20 -0700358
alshabib1c319ff2014-10-04 20:29:09 -0700359 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700360 checkNotNull(flowRule, FLOW_RULE_NULL);
361 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700362 Device device = deviceService.getDevice(flowRule.deviceId());
363 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700364 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700365 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700366 case PENDING_REMOVE:
367 case REMOVED:
368 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700369 break;
370 case ADDED:
371 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800372 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800373 try {
374 frp.applyFlowRule(flowRule);
375 } catch (UnsupportedOperationException e) {
376 log.warn(e.getMessage());
377 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800378 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800379 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
380 }
381 }
tom9b4030d2014-10-06 10:39:03 -0700382 break;
383 default:
384 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700385 }
386
alshabibbb42cad2014-09-25 11:43:05 -0700387 if (event != null) {
388 log.debug("Flow {} removed", flowRule);
389 post(event);
390 }
alshabib57044ba2014-09-16 15:58:01 -0700391 }
392
alshabibba5ac482014-10-02 17:15:20 -0700393 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700394 checkNotNull(flowRule, FLOW_RULE_NULL);
395 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700396 FlowRuleProvider frp = getProvider(flowRule.deviceId());
397 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700398 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700399 }
400
alshabib1c319ff2014-10-04 20:29:09 -0700401 private void flowAdded(FlowEntry flowEntry) {
402 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700403 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700404
alshabib1c319ff2014-10-04 20:29:09 -0700405 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700406 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700407 if (event == null) {
408 log.debug("No flow store event generated.");
409 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800410 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700411 post(event);
412 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700413 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800414 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700415 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700416 }
alshabib57044ba2014-09-16 15:58:01 -0700417 }
418
alshabib1c319ff2014-10-04 20:29:09 -0700419 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
420 if (storedRule == null) {
421 return false;
422 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700423 if (storedRule.isPermanent()) {
424 return true;
425 }
426
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700427 final long timeout = storedRule.timeout() * 1000;
428 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700429
430 // Checking flow with hardTimeout
431 if (storedRule.hardTimeout() != 0) {
432 if (!firstSeen.containsKey(storedRule)) {
433 // First time rule adding
434 firstSeen.put(storedRule, currentTime);
435 } else {
436 Long first = firstSeen.get(storedRule);
437 final long hardTimeout = storedRule.hardTimeout() * 1000;
438 if ((currentTime - first) > hardTimeout) {
439 return false;
440 }
441 }
442 }
443
alshabib85c41972014-10-03 13:48:39 -0700444 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700445 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700446 return true;
447 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700448 if (!lastSeen.containsKey(storedRule)) {
449 // checking for the first time
450 lastSeen.put(storedRule, storedRule.lastSeen());
451 // Use following if lastSeen attr. was removed.
452 //lastSeen.put(storedRule, currentTime);
453 }
454 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700455
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800456 // concurrently removed? let the liveness check fail
457 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700458 }
459
alshabib5c370ff2014-09-18 10:12:14 -0700460 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700461 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900462 pushFlowMetricsInternal(deviceId, flowEntries, true);
463 }
464
465 @Override
466 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
467 pushFlowMetricsInternal(deviceId, flowEntries, false);
468 }
469
470 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
471 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700472 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
473 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
474
Saurav Dasfa2fa932015-03-03 11:29:48 -0800475 for (FlowEntry rule : flowEntries) {
476 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700477 FlowEntry storedRule = storedRules.remove(rule);
478 if (storedRule != null) {
479 if (storedRule.exactMatch(rule)) {
480 // we both have the rule, let's update some info then.
481 flowAdded(rule);
482 } else {
483 // the two rules are not an exact match - remove the
484 // switch's rule and install our rule
485 extraneousFlow(rule);
486 flowMissing(storedRule);
487 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800488 } else {
489 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700490 if (!allowExtraneousRules) {
491 extraneousFlow(rule);
492 }
alshabib93cb57f2015-02-12 17:43:26 -0800493 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700494 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800495 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800496 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800497 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900498
499 // DO NOT reinstall
500 if (useMissingFlow) {
501 for (FlowEntry rule : storedRules.keySet()) {
502 try {
503 // there are rules in the store that aren't on the switch
504 log.debug("Adding rule in store, but not on switch {}", rule);
505 flowMissing(rule);
506 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800507 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900508 }
alshabib93cb57f2015-02-12 17:43:26 -0800509 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800510 }
alshabib5c370ff2014-09-18 10:12:14 -0700511 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800512
513 @Override
514 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
515 store.batchOperationComplete(FlowRuleBatchEvent.completed(
516 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
517 operation
518 ));
519 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700520
521 @Override
522 public void pushTableStatistics(DeviceId deviceId,
523 List<TableStatisticsEntry> tableStats) {
524 store.updateTableStatistics(deviceId, tableStats);
525 }
alshabib57044ba2014-09-16 15:58:01 -0700526 }
527
tomc78acee2014-09-24 15:16:55 -0700528 // Store delegate to re-post events emitted from the store.
529 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800530
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800531
Madan Jampani117aaae2014-10-23 10:04:05 -0700532 // TODO: Right now we only dispatch events at individual flowEntry level.
533 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700534 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700535 public void notify(FlowRuleBatchEvent event) {
536 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700537 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700538 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800539 // Request has been forwarded to MASTER Node, and was
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700540 request.ops().forEach(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800541 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800542 switch (op.operator()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800543 case ADD:
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700544 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800545 break;
546 case REMOVE:
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700547 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800548 break;
549 case MODIFY:
550 //TODO: do something here when the time comes.
551 break;
552 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800553 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800554 }
555 }
556 );
557
558 DeviceId deviceId = event.deviceId();
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700559 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
Thomas Vachuska27bee092015-06-23 19:03:10 -0700560 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
561 if (flowRuleProvider != null) {
562 flowRuleProvider.executeBatch(batchOperation);
563 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800564
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800565 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700566
Madan Jampani117aaae2014-10-23 10:04:05 -0700567 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800568
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800569 FlowOperationsProcessor fops = pendingFlowOperations.remove(
570 event.subject().batchId());
571 if (event.result().isSuccess()) {
572 if (fops != null) {
573 fops.satisfy(event.deviceId());
574 }
575 } else {
576 fops.fail(event.deviceId(), event.result().failedItems());
577 }
578
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700579 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800580
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700581 default:
582 break;
583 }
tomc78acee2014-09-24 15:16:55 -0700584 }
585 }
alshabib902d41b2014-10-07 16:52:05 -0700586
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700587 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
588 switch (input) {
589 case ADD:
590 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
591 case MODIFY:
592 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
593 case REMOVE:
594 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
595 default:
596 throw new UnsupportedOperationException("Unknown flow rule type " + input);
597 }
598 }
599
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800600 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700601 // Immutable
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800602 private final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700603
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700604 // Mutable
605 private final List<Set<FlowRuleOperation>> stages;
Sho SHIMIZUdfefecd2016-09-07 10:06:14 -0700606 private final Set<DeviceId> pendingDevices;
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700607 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700608
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700609 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800610 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800611 this.fops = ops;
Sho SHIMIZUdfefecd2016-09-07 10:06:14 -0700612 this.pendingDevices = new HashSet<>();
613 }
614
Sho SHIMIZU4c794682016-09-07 10:29:01 -0700615 FlowOperationsProcessor(FlowOperationsProcessor src, boolean hasFailed) {
Sho SHIMIZUdfefecd2016-09-07 10:06:14 -0700616 this.fops = src.fops;
617 this.stages = Lists.newArrayList(src.stages);
618 this.pendingDevices = new HashSet<>(src.pendingDevices);
Sho SHIMIZU4c794682016-09-07 10:29:01 -0700619 this.hasFailed = hasFailed;
alshabib902d41b2014-10-07 16:52:05 -0700620 }
621
622 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700623 public synchronized void run() {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800624 if (stages.size() > 0) {
625 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700626 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700627 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700628 }
629 }
630
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800631 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700632 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800633
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700634 for (FlowRuleOperation op : ops) {
635 perDeviceBatches.put(op.rule().deviceId(),
636 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800637 }
Sho SHIMIZU2ad5f412016-08-31 15:23:42 -0700638 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800639
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800640 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700641 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800642 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
643 deviceId, id);
644 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700645 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700646 }
647 }
648
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700649 synchronized void satisfy(DeviceId devId) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800650 pendingDevices.remove(devId);
651 if (pendingDevices.isEmpty()) {
Sho SHIMIZU4c794682016-09-07 10:29:01 -0700652 operationsService.execute(new FlowOperationsProcessor(this, hasFailed));
alshabib193525b2014-10-08 18:58:03 -0700653 }
alshabib193525b2014-10-08 18:58:03 -0700654 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800655
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700656 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800657 pendingDevices.remove(devId);
658 if (pendingDevices.isEmpty()) {
Sho SHIMIZU4c794682016-09-07 10:29:01 -0700659 operationsService.execute(new FlowOperationsProcessor(this, true));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800660 }
661
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700662 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
663 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800664
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700665 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800666 }
alshabib902d41b2014-10-07 16:52:05 -0700667 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700668
669 @Override
670 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
671 checkPermission(FLOWRULE_READ);
672 return store.getTableStatistics(deviceId);
673 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800674
675 private class InternalDeviceListener implements DeviceListener {
676 @Override
677 public void event(DeviceEvent event) {
678 switch (event.type()) {
679 case DEVICE_REMOVED:
680 case DEVICE_AVAILABILITY_CHANGED:
681 DeviceId deviceId = event.subject().id();
682 if (!deviceService.isAvailable(deviceId)) {
683 if (purgeOnDisconnection) {
684 store.purgeFlowRule(deviceId);
685 }
686 }
687 break;
688 default:
689 break;
690 }
691 }
692 }
alshabib57044ba2014-09-16 15:58:01 -0700693}