blob: ccbbd4ae95d200e2a7dc6e01fcd60d4a64613c36 [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;
55import org.onosproject.net.flow.FlowRuleOperationsContext;
Brian O'Connorabafb502014-12-02 22:26:20 -080056import org.onosproject.net.flow.FlowRuleProvider;
57import org.onosproject.net.flow.FlowRuleProviderRegistry;
58import org.onosproject.net.flow.FlowRuleProviderService;
59import org.onosproject.net.flow.FlowRuleService;
60import org.onosproject.net.flow.FlowRuleStore;
61import org.onosproject.net.flow.FlowRuleStoreDelegate;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070062import org.onosproject.net.flow.TableStatisticsEntry;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080063import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080064import org.onosproject.net.provider.AbstractProviderService;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070065import org.osgi.service.component.ComponentContext;
alshabib57044ba2014-09-16 15:58:01 -070066import org.slf4j.Logger;
67
Brian O'Connord12267c2015-02-17 18:17:08 -080068import java.util.Collections;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070069import java.util.Dictionary;
Sho SHIMIZUb837cb72016-08-30 14:44:50 -070070import java.util.HashSet;
Brian O'Connord12267c2015-02-17 18:17:08 -080071import java.util.List;
72import java.util.Map;
73import java.util.Set;
74import java.util.concurrent.ConcurrentHashMap;
75import java.util.concurrent.ExecutorService;
76import java.util.concurrent.Executors;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080077
Thomas Vachuska9b2da212014-11-10 19:30:25 -080078import static com.google.common.base.Preconditions.checkNotNull;
Charles Chan0c7c43b2016-01-14 17:39:20 -080079import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080080import static org.onlab.util.Tools.get;
Brian O'Connord12267c2015-02-17 18:17:08 -080081import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070082import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_ADD_REQUESTED;
83import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVE_REQUESTED;
Changhoon Yoon541ef712015-05-23 17:18:34 +090084import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080085import static org.onosproject.security.AppPermission.Type.FLOWRULE_READ;
86import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070087import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +090088
Changhoon Yoon541ef712015-05-23 17:18:34 +090089
alshabiba7f7ca82014-09-22 11:41:23 -070090
tome4729872014-09-23 00:37:37 -070091/**
92 * Provides implementation of the flow NB & SB APIs.
93 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -070094@Component(immediate = true)
alshabib57044ba2014-09-16 15:58:01 -070095@Service
tom202175a2014-09-19 19:00:11 -070096public class FlowRuleManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070097 extends AbstractListenerProviderRegistry<FlowRuleEvent, FlowRuleListener,
98 FlowRuleProvider, FlowRuleProviderService>
tom9b4030d2014-10-06 10:39:03 -070099 implements FlowRuleService, FlowRuleProviderRegistry {
alshabib57044ba2014-09-16 15:58:01 -0700100
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800101 private final Logger log = getLogger(getClass());
102
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700103 public static final String FLOW_RULE_NULL = "FlowRule cannot be null";
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700104 private static final boolean ALLOW_EXTRANEOUS_RULES = false;
105
106 @Property(name = "allowExtraneousRules", boolValue = ALLOW_EXTRANEOUS_RULES,
107 label = "Allow flow rules in switch not installed by ONOS")
108 private boolean allowExtraneousRules = ALLOW_EXTRANEOUS_RULES;
109
Charles Chan0c7c43b2016-01-14 17:39:20 -0800110 @Property(name = "purgeOnDisconnection", boolValue = false,
111 label = "Purge entries associated with a device when the device goes offline")
112 private boolean purgeOnDisconnection = false;
113
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800114 private static final int DEFAULT_POLL_FREQUENCY = 30;
115 @Property(name = "fallbackFlowPollFrequency", intValue = DEFAULT_POLL_FREQUENCY,
116 label = "Frequency (in seconds) for polling flow statistics via fallback provider")
117 private int fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
alshabib57044ba2014-09-16 15:58:01 -0700118
alshabibbb42cad2014-09-25 11:43:05 -0700119 private final FlowRuleStoreDelegate delegate = new InternalStoreDelegate();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800120 private final DeviceListener deviceListener = new InternalDeviceListener();
tomc78acee2014-09-24 15:16:55 -0700121
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800122 private final FlowRuleDriverProvider defaultProvider = new FlowRuleDriverProvider();
123
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800124 protected ExecutorService deviceInstallers =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800125 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "device-installer-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800126
127 protected ExecutorService operationsService =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700128 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "operations-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800129
130 private IdGenerator idGenerator;
131
Sho SHIMIZU9f950742016-09-01 09:55:38 -0700132 private final Map<Long, FlowOperationsProcessor> pendingFlowOperations = 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() {
Andrea Campanella3f1c61e2016-04-01 17:30:12 -0700162 deviceService.removeListener(deviceListener);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700163 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800164 deviceInstallers.shutdownNow();
165 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700166 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700167 eventDispatcher.removeSink(FlowRuleEvent.class);
168 log.info("Stopped");
169 }
170
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700171 @Modified
172 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800173 if (context != null) {
174 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700175 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800176 defaultProvider.init(new InternalFlowRuleProviderService(defaultProvider),
177 deviceService, mastershipService, fallbackFlowPollFrequency);
178 }
179
180 @Override
181 protected FlowRuleProvider defaultProvider() {
182 return defaultProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800183 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700184
Charles Chan0c7c43b2016-01-14 17:39:20 -0800185 /**
186 * Extracts properties from the component configuration context.
187 *
188 * @param context the component context
189 */
190 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700191 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800192 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700193
Jian Lid9b5f552016-03-11 18:15:31 -0800194 flag = Tools.isPropertyEnabled(properties, "allowExtraneousRules");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800195 if (flag == null) {
196 log.info("AllowExtraneousRules is not configured, " +
197 "using current value of {}", allowExtraneousRules);
198 } else {
199 allowExtraneousRules = flag;
200 log.info("Configured. AllowExtraneousRules is {}",
201 allowExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700202 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800203
Jian Lid9b5f552016-03-11 18:15:31 -0800204 flag = Tools.isPropertyEnabled(properties, "purgeOnDisconnection");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800205 if (flag == null) {
206 log.info("PurgeOnDisconnection is not configured, " +
207 "using current value of {}", purgeOnDisconnection);
208 } else {
209 purgeOnDisconnection = flag;
210 log.info("Configured. PurgeOnDisconnection is {}",
211 purgeOnDisconnection ? "enabled" : "disabled");
212 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800213
214 String s = get(properties, "fallbackFlowPollFrequency");
215 try {
216 fallbackFlowPollFrequency = isNullOrEmpty(s) ? DEFAULT_POLL_FREQUENCY : Integer.parseInt(s);
217 } catch (NumberFormatException e) {
218 fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
219 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800220 }
221
alshabib57044ba2014-09-16 15:58:01 -0700222 @Override
tom9b4030d2014-10-06 10:39:03 -0700223 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900224 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700225 return store.getFlowRuleCount();
226 }
227
228 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700229 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900230 checkPermission(FLOWRULE_READ);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700231 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700232 }
233
234 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700235 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900236 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900237
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800238 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800239 for (FlowRule flowRule : flowRules) {
240 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700241 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800242 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700243 }
244
245 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530246 public void purgeFlowRules(DeviceId deviceId) {
247 checkPermission(FLOWRULE_WRITE);
248 store.purgeFlowRule(deviceId);
249 }
250
251 @Override
alshabib57044ba2014-09-16 15:58:01 -0700252 public void removeFlowRules(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.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700258 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800259 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700260 }
alshabib57044ba2014-09-16 15:58:01 -0700261
alshabiba68eb962014-09-24 20:34:13 -0700262 @Override
263 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900264 checkPermission(FLOWRULE_WRITE);
Madan Jampani6a456162014-10-24 11:36:17 -0700265 removeFlowRules(Iterables.toArray(getFlowRulesById(id), FlowRule.class));
alshabiba68eb962014-09-24 20:34:13 -0700266 }
267
268 @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
alshabibaa7e7de2014-11-12 19:20:44 -0800284 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900285 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900286
alshabibaa7e7de2014-11-12 19:20:44 -0800287 Set<FlowRule> matches = Sets.newHashSet();
288 long toLookUp = ((long) appId.id() << 16) | groupId;
289 for (Device d : deviceService.getDevices()) {
290 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
291 if ((flowEntry.id().value() >>> 32) == toLookUp) {
292 matches.add(flowEntry);
293 }
294 }
295 }
296 return matches;
297 }
298
299 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800300 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900301 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700302 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700303 }
304
305 @Override
alshabib57044ba2014-09-16 15:58:01 -0700306 protected FlowRuleProviderService createProviderService(
307 FlowRuleProvider provider) {
308 return new InternalFlowRuleProviderService(provider);
309 }
310
311 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700312 extends AbstractProviderService<FlowRuleProvider>
313 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700314
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700315 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700316 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
317
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700318
alshabib57044ba2014-09-16 15:58:01 -0700319 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
320 super(provider);
321 }
322
323 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700324 public void flowRemoved(FlowEntry flowEntry) {
325 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700326 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700327 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700328 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700329 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700330 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800331 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700332 return;
333 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700334 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
335 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
336 }
alshabib1c319ff2014-10-04 20:29:09 -0700337 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700338 FlowRuleProvider frp = getProvider(device.providerId());
339 FlowRuleEvent event = null;
340 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700341 case ADDED:
342 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700343 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700344 break;
345 case PENDING_REMOVE:
346 case REMOVED:
347 event = store.removeFlowRule(stored);
348 break;
349 default:
350 break;
alshabib57044ba2014-09-16 15:58:01 -0700351
alshabiba68eb962014-09-24 20:34:13 -0700352 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700353 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700354 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700355 post(event);
356 }
alshabib57044ba2014-09-16 15:58:01 -0700357 }
358
alshabibba5ac482014-10-02 17:15:20 -0700359
alshabib1c319ff2014-10-04 20:29:09 -0700360 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700361 checkNotNull(flowRule, FLOW_RULE_NULL);
362 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700363 Device device = deviceService.getDevice(flowRule.deviceId());
364 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700365 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700366 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700367 case PENDING_REMOVE:
368 case REMOVED:
369 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700370 break;
371 case ADDED:
372 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800373 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800374 try {
375 frp.applyFlowRule(flowRule);
376 } catch (UnsupportedOperationException e) {
377 log.warn(e.getMessage());
378 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800379 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800380 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
381 }
382 }
tom9b4030d2014-10-06 10:39:03 -0700383 break;
384 default:
385 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700386 }
387
alshabibbb42cad2014-09-25 11:43:05 -0700388 if (event != null) {
389 log.debug("Flow {} removed", flowRule);
390 post(event);
391 }
alshabib57044ba2014-09-16 15:58:01 -0700392 }
393
alshabibba5ac482014-10-02 17:15:20 -0700394 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700395 checkNotNull(flowRule, FLOW_RULE_NULL);
396 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700397 FlowRuleProvider frp = getProvider(flowRule.deviceId());
398 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700399 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700400 }
401
alshabib1c319ff2014-10-04 20:29:09 -0700402 private void flowAdded(FlowEntry flowEntry) {
403 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700404 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700405
alshabib1c319ff2014-10-04 20:29:09 -0700406 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700407 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700408 if (event == null) {
409 log.debug("No flow store event generated.");
410 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800411 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700412 post(event);
413 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700414 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800415 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700416 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700417 }
alshabib57044ba2014-09-16 15:58:01 -0700418 }
419
alshabib1c319ff2014-10-04 20:29:09 -0700420 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
421 if (storedRule == null) {
422 return false;
423 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700424 if (storedRule.isPermanent()) {
425 return true;
426 }
427
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700428 final long timeout = storedRule.timeout() * 1000;
429 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700430
431 // Checking flow with hardTimeout
432 if (storedRule.hardTimeout() != 0) {
433 if (!firstSeen.containsKey(storedRule)) {
434 // First time rule adding
435 firstSeen.put(storedRule, currentTime);
436 } else {
437 Long first = firstSeen.get(storedRule);
438 final long hardTimeout = storedRule.hardTimeout() * 1000;
439 if ((currentTime - first) > hardTimeout) {
440 return false;
441 }
442 }
443 }
444
alshabib85c41972014-10-03 13:48:39 -0700445 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700446 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700447 return true;
448 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700449 if (!lastSeen.containsKey(storedRule)) {
450 // checking for the first time
451 lastSeen.put(storedRule, storedRule.lastSeen());
452 // Use following if lastSeen attr. was removed.
453 //lastSeen.put(storedRule, currentTime);
454 }
455 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700456
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800457 // concurrently removed? let the liveness check fail
458 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700459 }
460
alshabib5c370ff2014-09-18 10:12:14 -0700461 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700462 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900463 pushFlowMetricsInternal(deviceId, flowEntries, true);
464 }
465
466 @Override
467 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
468 pushFlowMetricsInternal(deviceId, flowEntries, false);
469 }
470
471 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
472 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700473 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
474 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
475
Saurav Dasfa2fa932015-03-03 11:29:48 -0800476 for (FlowEntry rule : flowEntries) {
477 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700478 FlowEntry storedRule = storedRules.remove(rule);
479 if (storedRule != null) {
480 if (storedRule.exactMatch(rule)) {
481 // we both have the rule, let's update some info then.
482 flowAdded(rule);
483 } else {
484 // the two rules are not an exact match - remove the
485 // switch's rule and install our rule
486 extraneousFlow(rule);
487 flowMissing(storedRule);
488 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800489 } else {
490 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700491 if (!allowExtraneousRules) {
492 extraneousFlow(rule);
493 }
alshabib93cb57f2015-02-12 17:43:26 -0800494 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700495 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800496 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800497 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800498 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900499
500 // DO NOT reinstall
501 if (useMissingFlow) {
502 for (FlowEntry rule : storedRules.keySet()) {
503 try {
504 // there are rules in the store that aren't on the switch
505 log.debug("Adding rule in store, but not on switch {}", rule);
506 flowMissing(rule);
507 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800508 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900509 }
alshabib93cb57f2015-02-12 17:43:26 -0800510 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800511 }
alshabib5c370ff2014-09-18 10:12:14 -0700512 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800513
514 @Override
515 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
516 store.batchOperationComplete(FlowRuleBatchEvent.completed(
517 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
518 operation
519 ));
520 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700521
522 @Override
523 public void pushTableStatistics(DeviceId deviceId,
524 List<TableStatisticsEntry> tableStats) {
525 store.updateTableStatistics(deviceId, tableStats);
526 }
alshabib57044ba2014-09-16 15:58:01 -0700527 }
528
tomc78acee2014-09-24 15:16:55 -0700529 // Store delegate to re-post events emitted from the store.
530 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800531
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800532
Madan Jampani117aaae2014-10-23 10:04:05 -0700533 // TODO: Right now we only dispatch events at individual flowEntry level.
534 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700535 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700536 public void notify(FlowRuleBatchEvent event) {
537 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700538 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700539 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800540 // Request has been forwarded to MASTER Node, and was
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700541 request.ops().forEach(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800542 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800543 switch (op.operator()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800544 case ADD:
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700545 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800546 break;
547 case REMOVE:
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700548 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800549 break;
550 case MODIFY:
551 //TODO: do something here when the time comes.
552 break;
553 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800554 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800555 }
556 }
557 );
558
559 DeviceId deviceId = event.deviceId();
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700560 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
Thomas Vachuska27bee092015-06-23 19:03:10 -0700561 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
562 if (flowRuleProvider != null) {
563 flowRuleProvider.executeBatch(batchOperation);
564 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800565
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800566 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700567
Madan Jampani117aaae2014-10-23 10:04:05 -0700568 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800569
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800570 FlowOperationsProcessor fops = pendingFlowOperations.remove(
571 event.subject().batchId());
572 if (event.result().isSuccess()) {
573 if (fops != null) {
574 fops.satisfy(event.deviceId());
575 }
576 } else {
577 fops.fail(event.deviceId(), event.result().failedItems());
578 }
579
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700580 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800581
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700582 default:
583 break;
584 }
tomc78acee2014-09-24 15:16:55 -0700585 }
586 }
alshabib902d41b2014-10-07 16:52:05 -0700587
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700588 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
589 switch (input) {
590 case ADD:
591 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
592 case MODIFY:
593 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
594 case REMOVE:
595 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
596 default:
597 throw new UnsupportedOperationException("Unknown flow rule type " + input);
598 }
599 }
600
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800601 private class FlowOperationsProcessor implements Runnable {
alshabib902d41b2014-10-07 16:52:05 -0700602
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800603 private final List<Set<FlowRuleOperation>> stages;
604 private final FlowRuleOperationsContext context;
605 private final FlowRuleOperations fops;
Sho SHIMIZU27124192016-08-30 14:47:12 -0700606 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700607
Sho SHIMIZUb837cb72016-08-30 14:44:50 -0700608 private final Set<DeviceId> pendingDevices = new HashSet<>();
alshabib902d41b2014-10-07 16:52:05 -0700609
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700610 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800611 this.stages = Lists.newArrayList(ops.stages());
612 this.context = ops.callback();
613 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700614 }
615
616 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700617 public synchronized void run() {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800618 if (stages.size() > 0) {
619 process(stages.remove(0));
Sho SHIMIZU27124192016-08-30 14:47:12 -0700620 } else if (!hasFailed && context != null) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800621 context.onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700622 }
623 }
624
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800625 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700626 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800627
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700628 for (FlowRuleOperation op : ops) {
629 perDeviceBatches.put(op.rule().deviceId(),
630 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800631 }
Sho SHIMIZU2ad5f412016-08-31 15:23:42 -0700632 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800633
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800634 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700635 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800636 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
637 deviceId, id);
638 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700639 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700640 }
641 }
642
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700643 synchronized void satisfy(DeviceId devId) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800644 pendingDevices.remove(devId);
645 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700646 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700647 }
alshabib193525b2014-10-08 18:58:03 -0700648 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800649
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700650 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZU27124192016-08-30 14:47:12 -0700651 hasFailed = true;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800652 pendingDevices.remove(devId);
653 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700654 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800655 }
656
657 if (context != null) {
658 final FlowRuleOperations.Builder failedOpsBuilder =
659 FlowRuleOperations.builder();
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700660 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800661
662 context.onError(failedOpsBuilder.build());
663 }
664 }
alshabib902d41b2014-10-07 16:52:05 -0700665 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700666
667 @Override
668 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
669 checkPermission(FLOWRULE_READ);
670 return store.getTableStatistics(deviceId);
671 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800672
673 private class InternalDeviceListener implements DeviceListener {
674 @Override
675 public void event(DeviceEvent event) {
676 switch (event.type()) {
677 case DEVICE_REMOVED:
678 case DEVICE_AVAILABILITY_CHANGED:
679 DeviceId deviceId = event.subject().id();
680 if (!deviceService.isAvailable(deviceId)) {
681 if (purgeOnDisconnection) {
682 store.purgeFlowRule(deviceId);
683 }
684 }
685 break;
686 default:
687 break;
688 }
689 }
690 }
alshabib57044ba2014-09-16 15:58:01 -0700691}