blob: 2301505bc3480e7d1fc940781909695f36570833 [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;
77import java.util.concurrent.atomic.AtomicBoolean;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080078
Thomas Vachuska9b2da212014-11-10 19:30:25 -080079import static com.google.common.base.Preconditions.checkNotNull;
Charles Chan0c7c43b2016-01-14 17:39:20 -080080import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080081import static org.onlab.util.Tools.get;
Brian O'Connord12267c2015-02-17 18:17:08 -080082import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070083import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_ADD_REQUESTED;
84import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVE_REQUESTED;
Changhoon Yoon541ef712015-05-23 17:18:34 +090085import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080086import static org.onosproject.security.AppPermission.Type.FLOWRULE_READ;
87import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070088import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +090089
Changhoon Yoon541ef712015-05-23 17:18:34 +090090
alshabiba7f7ca82014-09-22 11:41:23 -070091
tome4729872014-09-23 00:37:37 -070092/**
93 * Provides implementation of the flow NB & SB APIs.
94 */
Sho SHIMIZU5c396e32016-08-12 15:19:12 -070095@Component(immediate = true)
alshabib57044ba2014-09-16 15:58:01 -070096@Service
tom202175a2014-09-19 19:00:11 -070097public class FlowRuleManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070098 extends AbstractListenerProviderRegistry<FlowRuleEvent, FlowRuleListener,
99 FlowRuleProvider, FlowRuleProviderService>
tom9b4030d2014-10-06 10:39:03 -0700100 implements FlowRuleService, FlowRuleProviderRegistry {
alshabib57044ba2014-09-16 15:58:01 -0700101
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800102 private final Logger log = getLogger(getClass());
103
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700104 public static final String FLOW_RULE_NULL = "FlowRule cannot be null";
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700105 private static final boolean ALLOW_EXTRANEOUS_RULES = false;
106
107 @Property(name = "allowExtraneousRules", boolValue = ALLOW_EXTRANEOUS_RULES,
108 label = "Allow flow rules in switch not installed by ONOS")
109 private boolean allowExtraneousRules = ALLOW_EXTRANEOUS_RULES;
110
Charles Chan0c7c43b2016-01-14 17:39:20 -0800111 @Property(name = "purgeOnDisconnection", boolValue = false,
112 label = "Purge entries associated with a device when the device goes offline")
113 private boolean purgeOnDisconnection = false;
114
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800115 private static final int DEFAULT_POLL_FREQUENCY = 30;
116 @Property(name = "fallbackFlowPollFrequency", intValue = DEFAULT_POLL_FREQUENCY,
117 label = "Frequency (in seconds) for polling flow statistics via fallback provider")
118 private int fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
alshabib57044ba2014-09-16 15:58:01 -0700119
alshabibbb42cad2014-09-25 11:43:05 -0700120 private final FlowRuleStoreDelegate delegate = new InternalStoreDelegate();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800121 private final DeviceListener deviceListener = new InternalDeviceListener();
tomc78acee2014-09-24 15:16:55 -0700122
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800123 private final FlowRuleDriverProvider defaultProvider = new FlowRuleDriverProvider();
124
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800125 protected ExecutorService deviceInstallers =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800126 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "device-installer-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800127
128 protected ExecutorService operationsService =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700129 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "operations-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800130
131 private IdGenerator idGenerator;
132
Brian O'Connord12267c2015-02-17 18:17:08 -0800133 private Map<Long, FlowOperationsProcessor> pendingFlowOperations
134 = new ConcurrentHashMap<>();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700135
tombe988312014-09-19 18:38:47 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
137 protected FlowRuleStore store;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700138
alshabib57044ba2014-09-16 15:58:01 -0700139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibeb55524f2014-09-18 09:59:24 -0700140 protected DeviceService deviceService;
alshabib57044ba2014-09-16 15:58:01 -0700141
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800142 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
143 protected CoreService coreService;
144
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800146 protected MastershipService mastershipService;
147
148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700149 protected ComponentConfigService cfgService;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800150
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700151 @Activate
152 public void activate(ComponentContext context) {
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800153 modified(context);
tomc78acee2014-09-24 15:16:55 -0700154 store.setDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700155 eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800156 deviceService.addListener(deviceListener);
157 cfgService.registerProperties(getClass());
158 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
alshabib57044ba2014-09-16 15:58:01 -0700159 log.info("Started");
160 }
161
162 @Deactivate
163 public void deactivate() {
Andrea Campanella3f1c61e2016-04-01 17:30:12 -0700164 deviceService.removeListener(deviceListener);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700165 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800166 deviceInstallers.shutdownNow();
167 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700168 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700169 eventDispatcher.removeSink(FlowRuleEvent.class);
170 log.info("Stopped");
171 }
172
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700173 @Modified
174 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800175 if (context != null) {
176 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700177 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800178 defaultProvider.init(new InternalFlowRuleProviderService(defaultProvider),
179 deviceService, mastershipService, fallbackFlowPollFrequency);
180 }
181
182 @Override
183 protected FlowRuleProvider defaultProvider() {
184 return defaultProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800185 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700186
Charles Chan0c7c43b2016-01-14 17:39:20 -0800187 /**
188 * Extracts properties from the component configuration context.
189 *
190 * @param context the component context
191 */
192 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700193 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800194 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700195
Jian Lid9b5f552016-03-11 18:15:31 -0800196 flag = Tools.isPropertyEnabled(properties, "allowExtraneousRules");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800197 if (flag == null) {
198 log.info("AllowExtraneousRules is not configured, " +
199 "using current value of {}", allowExtraneousRules);
200 } else {
201 allowExtraneousRules = flag;
202 log.info("Configured. AllowExtraneousRules is {}",
203 allowExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700204 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800205
Jian Lid9b5f552016-03-11 18:15:31 -0800206 flag = Tools.isPropertyEnabled(properties, "purgeOnDisconnection");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800207 if (flag == null) {
208 log.info("PurgeOnDisconnection is not configured, " +
209 "using current value of {}", purgeOnDisconnection);
210 } else {
211 purgeOnDisconnection = flag;
212 log.info("Configured. PurgeOnDisconnection is {}",
213 purgeOnDisconnection ? "enabled" : "disabled");
214 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800215
216 String s = get(properties, "fallbackFlowPollFrequency");
217 try {
218 fallbackFlowPollFrequency = isNullOrEmpty(s) ? DEFAULT_POLL_FREQUENCY : Integer.parseInt(s);
219 } catch (NumberFormatException e) {
220 fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
221 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800222 }
223
alshabib57044ba2014-09-16 15:58:01 -0700224 @Override
tom9b4030d2014-10-06 10:39:03 -0700225 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900226 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700227 return store.getFlowRuleCount();
228 }
229
230 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700231 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900232 checkPermission(FLOWRULE_READ);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700233 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700234 }
235
236 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700237 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900238 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900239
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800240 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800241 for (FlowRule flowRule : flowRules) {
242 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700243 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800244 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700245 }
246
247 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530248 public void purgeFlowRules(DeviceId deviceId) {
249 checkPermission(FLOWRULE_WRITE);
250 store.purgeFlowRule(deviceId);
251 }
252
253 @Override
alshabib57044ba2014-09-16 15:58:01 -0700254 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900255 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900256
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800257 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800258 for (FlowRule flowRule : flowRules) {
259 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700260 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800261 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700262 }
alshabib57044ba2014-09-16 15:58:01 -0700263
alshabiba68eb962014-09-24 20:34:13 -0700264 @Override
265 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900266 checkPermission(FLOWRULE_WRITE);
Madan Jampani6a456162014-10-24 11:36:17 -0700267 removeFlowRules(Iterables.toArray(getFlowRulesById(id), FlowRule.class));
alshabiba68eb962014-09-24 20:34:13 -0700268 }
269
270 @Override
271 public Iterable<FlowRule> getFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900272 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900273
Madan Jampani6a456162014-10-24 11:36:17 -0700274 Set<FlowRule> flowEntries = Sets.newHashSet();
275 for (Device d : deviceService.getDevices()) {
276 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
277 if (flowEntry.appId() == id.id()) {
278 flowEntries.add(flowEntry);
279 }
280 }
281 }
282 return flowEntries;
alshabib57044ba2014-09-16 15:58:01 -0700283 }
284
285 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800286 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900287 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900288
alshabibaa7e7de2014-11-12 19:20:44 -0800289 Set<FlowRule> matches = Sets.newHashSet();
290 long toLookUp = ((long) appId.id() << 16) | groupId;
291 for (Device d : deviceService.getDevices()) {
292 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
293 if ((flowEntry.id().value() >>> 32) == toLookUp) {
294 matches.add(flowEntry);
295 }
296 }
297 }
298 return matches;
299 }
300
301 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800302 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900303 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700304 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700305 }
306
307 @Override
alshabib57044ba2014-09-16 15:58:01 -0700308 protected FlowRuleProviderService createProviderService(
309 FlowRuleProvider provider) {
310 return new InternalFlowRuleProviderService(provider);
311 }
312
313 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700314 extends AbstractProviderService<FlowRuleProvider>
315 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700316
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700317 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700318 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
319
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700320
alshabib57044ba2014-09-16 15:58:01 -0700321 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
322 super(provider);
323 }
324
325 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700326 public void flowRemoved(FlowEntry flowEntry) {
327 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700328 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700329 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700330 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700331 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700332 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800333 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700334 return;
335 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700336 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
337 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
338 }
alshabib1c319ff2014-10-04 20:29:09 -0700339 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700340 FlowRuleProvider frp = getProvider(device.providerId());
341 FlowRuleEvent event = null;
342 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700343 case ADDED:
344 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700345 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700346 break;
347 case PENDING_REMOVE:
348 case REMOVED:
349 event = store.removeFlowRule(stored);
350 break;
351 default:
352 break;
alshabib57044ba2014-09-16 15:58:01 -0700353
alshabiba68eb962014-09-24 20:34:13 -0700354 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700355 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700356 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700357 post(event);
358 }
alshabib57044ba2014-09-16 15:58:01 -0700359 }
360
alshabibba5ac482014-10-02 17:15:20 -0700361
alshabib1c319ff2014-10-04 20:29:09 -0700362 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700363 checkNotNull(flowRule, FLOW_RULE_NULL);
364 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700365 Device device = deviceService.getDevice(flowRule.deviceId());
366 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700367 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700368 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700369 case PENDING_REMOVE:
370 case REMOVED:
371 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700372 break;
373 case ADDED:
374 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800375 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800376 try {
377 frp.applyFlowRule(flowRule);
378 } catch (UnsupportedOperationException e) {
379 log.warn(e.getMessage());
380 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800381 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800382 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
383 }
384 }
tom9b4030d2014-10-06 10:39:03 -0700385 break;
386 default:
387 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700388 }
389
alshabibbb42cad2014-09-25 11:43:05 -0700390 if (event != null) {
391 log.debug("Flow {} removed", flowRule);
392 post(event);
393 }
alshabib57044ba2014-09-16 15:58:01 -0700394 }
395
alshabibba5ac482014-10-02 17:15:20 -0700396 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700397 checkNotNull(flowRule, FLOW_RULE_NULL);
398 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700399 FlowRuleProvider frp = getProvider(flowRule.deviceId());
400 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700401 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700402 }
403
alshabib1c319ff2014-10-04 20:29:09 -0700404 private void flowAdded(FlowEntry flowEntry) {
405 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700406 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700407
alshabib1c319ff2014-10-04 20:29:09 -0700408 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700409 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700410 if (event == null) {
411 log.debug("No flow store event generated.");
412 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800413 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700414 post(event);
415 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700416 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800417 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700418 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700419 }
alshabib57044ba2014-09-16 15:58:01 -0700420 }
421
alshabib1c319ff2014-10-04 20:29:09 -0700422 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
423 if (storedRule == null) {
424 return false;
425 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700426 if (storedRule.isPermanent()) {
427 return true;
428 }
429
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700430 final long timeout = storedRule.timeout() * 1000;
431 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700432
433 // Checking flow with hardTimeout
434 if (storedRule.hardTimeout() != 0) {
435 if (!firstSeen.containsKey(storedRule)) {
436 // First time rule adding
437 firstSeen.put(storedRule, currentTime);
438 } else {
439 Long first = firstSeen.get(storedRule);
440 final long hardTimeout = storedRule.hardTimeout() * 1000;
441 if ((currentTime - first) > hardTimeout) {
442 return false;
443 }
444 }
445 }
446
alshabib85c41972014-10-03 13:48:39 -0700447 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700448 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700449 return true;
450 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700451 if (!lastSeen.containsKey(storedRule)) {
452 // checking for the first time
453 lastSeen.put(storedRule, storedRule.lastSeen());
454 // Use following if lastSeen attr. was removed.
455 //lastSeen.put(storedRule, currentTime);
456 }
457 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700458
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800459 // concurrently removed? let the liveness check fail
460 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700461 }
462
alshabib5c370ff2014-09-18 10:12:14 -0700463 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700464 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900465 pushFlowMetricsInternal(deviceId, flowEntries, true);
466 }
467
468 @Override
469 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
470 pushFlowMetricsInternal(deviceId, flowEntries, false);
471 }
472
473 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
474 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700475 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
476 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
477
Saurav Dasfa2fa932015-03-03 11:29:48 -0800478 for (FlowEntry rule : flowEntries) {
479 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700480 FlowEntry storedRule = storedRules.remove(rule);
481 if (storedRule != null) {
482 if (storedRule.exactMatch(rule)) {
483 // we both have the rule, let's update some info then.
484 flowAdded(rule);
485 } else {
486 // the two rules are not an exact match - remove the
487 // switch's rule and install our rule
488 extraneousFlow(rule);
489 flowMissing(storedRule);
490 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800491 } else {
492 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700493 if (!allowExtraneousRules) {
494 extraneousFlow(rule);
495 }
alshabib93cb57f2015-02-12 17:43:26 -0800496 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700497 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800498 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800499 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800500 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900501
502 // DO NOT reinstall
503 if (useMissingFlow) {
504 for (FlowEntry rule : storedRules.keySet()) {
505 try {
506 // there are rules in the store that aren't on the switch
507 log.debug("Adding rule in store, but not on switch {}", rule);
508 flowMissing(rule);
509 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800510 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900511 }
alshabib93cb57f2015-02-12 17:43:26 -0800512 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800513 }
alshabib5c370ff2014-09-18 10:12:14 -0700514 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800515
516 @Override
517 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
518 store.batchOperationComplete(FlowRuleBatchEvent.completed(
519 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
520 operation
521 ));
522 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700523
524 @Override
525 public void pushTableStatistics(DeviceId deviceId,
526 List<TableStatisticsEntry> tableStats) {
527 store.updateTableStatistics(deviceId, tableStats);
528 }
alshabib57044ba2014-09-16 15:58:01 -0700529 }
530
tomc78acee2014-09-24 15:16:55 -0700531 // Store delegate to re-post events emitted from the store.
532 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800533
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800534
Madan Jampani117aaae2014-10-23 10:04:05 -0700535 // TODO: Right now we only dispatch events at individual flowEntry level.
536 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700537 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700538 public void notify(FlowRuleBatchEvent event) {
539 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700540 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700541 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800542 // Request has been forwarded to MASTER Node, and was
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700543 request.ops().forEach(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800544 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800545 switch (op.operator()) {
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700546
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800547 case ADD:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700548 post(new FlowRuleEvent(RULE_ADD_REQUESTED,
549 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800550 break;
551 case REMOVE:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700552 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED,
553 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800554 break;
555 case MODIFY:
556 //TODO: do something here when the time comes.
557 break;
558 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800559 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800560 }
561 }
562 );
563
564 DeviceId deviceId = event.deviceId();
565
566 FlowRuleBatchOperation batchOperation =
567 request.asBatchOperation(deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700568
Thomas Vachuska27bee092015-06-23 19:03:10 -0700569 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
570 if (flowRuleProvider != null) {
571 flowRuleProvider.executeBatch(batchOperation);
572 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800573
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800574 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700575
Madan Jampani117aaae2014-10-23 10:04:05 -0700576 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800577
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800578 FlowOperationsProcessor fops = pendingFlowOperations.remove(
579 event.subject().batchId());
580 if (event.result().isSuccess()) {
581 if (fops != null) {
582 fops.satisfy(event.deviceId());
583 }
584 } else {
585 fops.fail(event.deviceId(), event.result().failedItems());
586 }
587
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700588 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800589
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700590 default:
591 break;
592 }
tomc78acee2014-09-24 15:16:55 -0700593 }
594 }
alshabib902d41b2014-10-07 16:52:05 -0700595
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800596 private class FlowOperationsProcessor implements Runnable {
alshabib902d41b2014-10-07 16:52:05 -0700597
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800598 private final List<Set<FlowRuleOperation>> stages;
599 private final FlowRuleOperationsContext context;
600 private final FlowRuleOperations fops;
601 private final AtomicBoolean hasFailed = new AtomicBoolean(false);
alshabib902d41b2014-10-07 16:52:05 -0700602
Sho SHIMIZUb837cb72016-08-30 14:44:50 -0700603 private final Set<DeviceId> pendingDevices = new HashSet<>();
alshabib902d41b2014-10-07 16:52:05 -0700604
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700605 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800606 this.stages = Lists.newArrayList(ops.stages());
607 this.context = ops.callback();
608 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700609 }
610
611 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700612 public synchronized void run() {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800613 if (stages.size() > 0) {
614 process(stages.remove(0));
615 } else if (!hasFailed.get() && context != null) {
616 context.onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700617 }
618 }
619
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800620 private void process(Set<FlowRuleOperation> ops) {
621 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches =
622 ArrayListMultimap.create();
623
624 FlowRuleBatchEntry fbe;
625 for (FlowRuleOperation flowRuleOperation : ops) {
626 switch (flowRuleOperation.type()) {
627 // FIXME: Brian needs imagination when creating class names.
628 case ADD:
629 fbe = new FlowRuleBatchEntry(
630 FlowRuleBatchEntry.FlowRuleOperation.ADD, flowRuleOperation.rule());
631 break;
632 case MODIFY:
633 fbe = new FlowRuleBatchEntry(
634 FlowRuleBatchEntry.FlowRuleOperation.MODIFY, flowRuleOperation.rule());
635 break;
636 case REMOVE:
637 fbe = new FlowRuleBatchEntry(
638 FlowRuleBatchEntry.FlowRuleOperation.REMOVE, flowRuleOperation.rule());
639 break;
640 default:
641 throw new UnsupportedOperationException("Unknown flow rule type " + flowRuleOperation.type());
642 }
643 pendingDevices.add(flowRuleOperation.rule().deviceId());
644 perDeviceBatches.put(flowRuleOperation.rule().deviceId(), fbe);
645 }
646
647
648 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700649 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800650 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
651 deviceId, id);
652 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700653 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700654 }
655 }
656
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700657 synchronized void satisfy(DeviceId devId) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800658 pendingDevices.remove(devId);
659 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700660 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700661 }
alshabib193525b2014-10-08 18:58:03 -0700662 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800663
664
665
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700666 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800667 hasFailed.set(true);
668 pendingDevices.remove(devId);
669 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700670 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800671 }
672
673 if (context != null) {
674 final FlowRuleOperations.Builder failedOpsBuilder =
675 FlowRuleOperations.builder();
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700676 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800677
678 context.onError(failedOpsBuilder.build());
679 }
680 }
681
alshabib902d41b2014-10-07 16:52:05 -0700682 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700683
684 @Override
685 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
686 checkPermission(FLOWRULE_READ);
687 return store.getTableStatistics(deviceId);
688 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800689
690 private class InternalDeviceListener implements DeviceListener {
691 @Override
692 public void event(DeviceEvent event) {
693 switch (event.type()) {
694 case DEVICE_REMOVED:
695 case DEVICE_AVAILABILITY_CHANGED:
696 DeviceId deviceId = event.subject().id();
697 if (!deviceService.isAvailable(deviceId)) {
698 if (purgeOnDisconnection) {
699 store.purgeFlowRule(deviceId);
700 }
701 }
702 break;
703 default:
704 break;
705 }
706 }
707 }
alshabib57044ba2014-09-16 15:58:01 -0700708}