blob: 2cebdd9ee330587e743bf54b25bcf1ea963eff8a [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
Brian O'Connord12267c2015-02-17 18:17:08 -0800132 private Map<Long, FlowOperationsProcessor> pendingFlowOperations
133 = new ConcurrentHashMap<>();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700134
tombe988312014-09-19 18:38:47 -0700135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
136 protected FlowRuleStore store;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700137
alshabib57044ba2014-09-16 15:58:01 -0700138 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibeb55524f2014-09-18 09:59:24 -0700139 protected DeviceService deviceService;
alshabib57044ba2014-09-16 15:58:01 -0700140
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected CoreService coreService;
143
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800145 protected MastershipService mastershipService;
146
147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700148 protected ComponentConfigService cfgService;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800149
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700150 @Activate
151 public void activate(ComponentContext context) {
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800152 modified(context);
tomc78acee2014-09-24 15:16:55 -0700153 store.setDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700154 eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800155 deviceService.addListener(deviceListener);
156 cfgService.registerProperties(getClass());
157 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
alshabib57044ba2014-09-16 15:58:01 -0700158 log.info("Started");
159 }
160
161 @Deactivate
162 public void deactivate() {
Andrea Campanella3f1c61e2016-04-01 17:30:12 -0700163 deviceService.removeListener(deviceListener);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700164 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800165 deviceInstallers.shutdownNow();
166 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700167 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700168 eventDispatcher.removeSink(FlowRuleEvent.class);
169 log.info("Stopped");
170 }
171
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700172 @Modified
173 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800174 if (context != null) {
175 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700176 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800177 defaultProvider.init(new InternalFlowRuleProviderService(defaultProvider),
178 deviceService, mastershipService, fallbackFlowPollFrequency);
179 }
180
181 @Override
182 protected FlowRuleProvider defaultProvider() {
183 return defaultProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800184 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700185
Charles Chan0c7c43b2016-01-14 17:39:20 -0800186 /**
187 * Extracts properties from the component configuration context.
188 *
189 * @param context the component context
190 */
191 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700192 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800193 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700194
Jian Lid9b5f552016-03-11 18:15:31 -0800195 flag = Tools.isPropertyEnabled(properties, "allowExtraneousRules");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800196 if (flag == null) {
197 log.info("AllowExtraneousRules is not configured, " +
198 "using current value of {}", allowExtraneousRules);
199 } else {
200 allowExtraneousRules = flag;
201 log.info("Configured. AllowExtraneousRules is {}",
202 allowExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700203 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800204
Jian Lid9b5f552016-03-11 18:15:31 -0800205 flag = Tools.isPropertyEnabled(properties, "purgeOnDisconnection");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800206 if (flag == null) {
207 log.info("PurgeOnDisconnection is not configured, " +
208 "using current value of {}", purgeOnDisconnection);
209 } else {
210 purgeOnDisconnection = flag;
211 log.info("Configured. PurgeOnDisconnection is {}",
212 purgeOnDisconnection ? "enabled" : "disabled");
213 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800214
215 String s = get(properties, "fallbackFlowPollFrequency");
216 try {
217 fallbackFlowPollFrequency = isNullOrEmpty(s) ? DEFAULT_POLL_FREQUENCY : Integer.parseInt(s);
218 } catch (NumberFormatException e) {
219 fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
220 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800221 }
222
alshabib57044ba2014-09-16 15:58:01 -0700223 @Override
tom9b4030d2014-10-06 10:39:03 -0700224 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900225 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700226 return store.getFlowRuleCount();
227 }
228
229 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700230 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900231 checkPermission(FLOWRULE_READ);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700232 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700233 }
234
235 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700236 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900237 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900238
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800239 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800240 for (FlowRule flowRule : flowRules) {
241 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700242 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800243 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700244 }
245
246 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530247 public void purgeFlowRules(DeviceId deviceId) {
248 checkPermission(FLOWRULE_WRITE);
249 store.purgeFlowRule(deviceId);
250 }
251
252 @Override
alshabib57044ba2014-09-16 15:58:01 -0700253 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900254 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900255
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800256 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800257 for (FlowRule flowRule : flowRules) {
258 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700259 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800260 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700261 }
alshabib57044ba2014-09-16 15:58:01 -0700262
alshabiba68eb962014-09-24 20:34:13 -0700263 @Override
264 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900265 checkPermission(FLOWRULE_WRITE);
Madan Jampani6a456162014-10-24 11:36:17 -0700266 removeFlowRules(Iterables.toArray(getFlowRulesById(id), FlowRule.class));
alshabiba68eb962014-09-24 20:34:13 -0700267 }
268
269 @Override
270 public Iterable<FlowRule> getFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900271 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900272
Madan Jampani6a456162014-10-24 11:36:17 -0700273 Set<FlowRule> flowEntries = Sets.newHashSet();
274 for (Device d : deviceService.getDevices()) {
275 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
276 if (flowEntry.appId() == id.id()) {
277 flowEntries.add(flowEntry);
278 }
279 }
280 }
281 return flowEntries;
alshabib57044ba2014-09-16 15:58:01 -0700282 }
283
284 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800285 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900286 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900287
alshabibaa7e7de2014-11-12 19:20:44 -0800288 Set<FlowRule> matches = Sets.newHashSet();
289 long toLookUp = ((long) appId.id() << 16) | groupId;
290 for (Device d : deviceService.getDevices()) {
291 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
292 if ((flowEntry.id().value() >>> 32) == toLookUp) {
293 matches.add(flowEntry);
294 }
295 }
296 }
297 return matches;
298 }
299
300 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800301 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900302 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700303 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700304 }
305
306 @Override
alshabib57044ba2014-09-16 15:58:01 -0700307 protected FlowRuleProviderService createProviderService(
308 FlowRuleProvider provider) {
309 return new InternalFlowRuleProviderService(provider);
310 }
311
312 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700313 extends AbstractProviderService<FlowRuleProvider>
314 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700315
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700316 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700317 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
318
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700319
alshabib57044ba2014-09-16 15:58:01 -0700320 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
321 super(provider);
322 }
323
324 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700325 public void flowRemoved(FlowEntry flowEntry) {
326 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700327 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700328 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700329 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700330 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700331 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800332 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700333 return;
334 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700335 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
336 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
337 }
alshabib1c319ff2014-10-04 20:29:09 -0700338 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700339 FlowRuleProvider frp = getProvider(device.providerId());
340 FlowRuleEvent event = null;
341 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700342 case ADDED:
343 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700344 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700345 break;
346 case PENDING_REMOVE:
347 case REMOVED:
348 event = store.removeFlowRule(stored);
349 break;
350 default:
351 break;
alshabib57044ba2014-09-16 15:58:01 -0700352
alshabiba68eb962014-09-24 20:34:13 -0700353 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700354 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700355 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700356 post(event);
357 }
alshabib57044ba2014-09-16 15:58:01 -0700358 }
359
alshabibba5ac482014-10-02 17:15:20 -0700360
alshabib1c319ff2014-10-04 20:29:09 -0700361 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700362 checkNotNull(flowRule, FLOW_RULE_NULL);
363 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700364 Device device = deviceService.getDevice(flowRule.deviceId());
365 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700366 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700367 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700368 case PENDING_REMOVE:
369 case REMOVED:
370 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700371 break;
372 case ADDED:
373 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800374 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800375 try {
376 frp.applyFlowRule(flowRule);
377 } catch (UnsupportedOperationException e) {
378 log.warn(e.getMessage());
379 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800380 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800381 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
382 }
383 }
tom9b4030d2014-10-06 10:39:03 -0700384 break;
385 default:
386 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700387 }
388
alshabibbb42cad2014-09-25 11:43:05 -0700389 if (event != null) {
390 log.debug("Flow {} removed", flowRule);
391 post(event);
392 }
alshabib57044ba2014-09-16 15:58:01 -0700393 }
394
alshabibba5ac482014-10-02 17:15:20 -0700395 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700396 checkNotNull(flowRule, FLOW_RULE_NULL);
397 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700398 FlowRuleProvider frp = getProvider(flowRule.deviceId());
399 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700400 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700401 }
402
alshabib1c319ff2014-10-04 20:29:09 -0700403 private void flowAdded(FlowEntry flowEntry) {
404 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700405 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700406
alshabib1c319ff2014-10-04 20:29:09 -0700407 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700408 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700409 if (event == null) {
410 log.debug("No flow store event generated.");
411 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800412 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700413 post(event);
414 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700415 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800416 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700417 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700418 }
alshabib57044ba2014-09-16 15:58:01 -0700419 }
420
alshabib1c319ff2014-10-04 20:29:09 -0700421 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
422 if (storedRule == null) {
423 return false;
424 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700425 if (storedRule.isPermanent()) {
426 return true;
427 }
428
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700429 final long timeout = storedRule.timeout() * 1000;
430 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700431
432 // Checking flow with hardTimeout
433 if (storedRule.hardTimeout() != 0) {
434 if (!firstSeen.containsKey(storedRule)) {
435 // First time rule adding
436 firstSeen.put(storedRule, currentTime);
437 } else {
438 Long first = firstSeen.get(storedRule);
439 final long hardTimeout = storedRule.hardTimeout() * 1000;
440 if ((currentTime - first) > hardTimeout) {
441 return false;
442 }
443 }
444 }
445
alshabib85c41972014-10-03 13:48:39 -0700446 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700447 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700448 return true;
449 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700450 if (!lastSeen.containsKey(storedRule)) {
451 // checking for the first time
452 lastSeen.put(storedRule, storedRule.lastSeen());
453 // Use following if lastSeen attr. was removed.
454 //lastSeen.put(storedRule, currentTime);
455 }
456 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700457
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800458 // concurrently removed? let the liveness check fail
459 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700460 }
461
alshabib5c370ff2014-09-18 10:12:14 -0700462 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700463 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900464 pushFlowMetricsInternal(deviceId, flowEntries, true);
465 }
466
467 @Override
468 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
469 pushFlowMetricsInternal(deviceId, flowEntries, false);
470 }
471
472 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
473 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700474 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
475 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
476
Saurav Dasfa2fa932015-03-03 11:29:48 -0800477 for (FlowEntry rule : flowEntries) {
478 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700479 FlowEntry storedRule = storedRules.remove(rule);
480 if (storedRule != null) {
481 if (storedRule.exactMatch(rule)) {
482 // we both have the rule, let's update some info then.
483 flowAdded(rule);
484 } else {
485 // the two rules are not an exact match - remove the
486 // switch's rule and install our rule
487 extraneousFlow(rule);
488 flowMissing(storedRule);
489 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800490 } else {
491 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700492 if (!allowExtraneousRules) {
493 extraneousFlow(rule);
494 }
alshabib93cb57f2015-02-12 17:43:26 -0800495 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700496 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800497 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800498 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800499 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900500
501 // DO NOT reinstall
502 if (useMissingFlow) {
503 for (FlowEntry rule : storedRules.keySet()) {
504 try {
505 // there are rules in the store that aren't on the switch
506 log.debug("Adding rule in store, but not on switch {}", rule);
507 flowMissing(rule);
508 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800509 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900510 }
alshabib93cb57f2015-02-12 17:43:26 -0800511 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800512 }
alshabib5c370ff2014-09-18 10:12:14 -0700513 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800514
515 @Override
516 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
517 store.batchOperationComplete(FlowRuleBatchEvent.completed(
518 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
519 operation
520 ));
521 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700522
523 @Override
524 public void pushTableStatistics(DeviceId deviceId,
525 List<TableStatisticsEntry> tableStats) {
526 store.updateTableStatistics(deviceId, tableStats);
527 }
alshabib57044ba2014-09-16 15:58:01 -0700528 }
529
tomc78acee2014-09-24 15:16:55 -0700530 // Store delegate to re-post events emitted from the store.
531 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800532
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800533
Madan Jampani117aaae2014-10-23 10:04:05 -0700534 // TODO: Right now we only dispatch events at individual flowEntry level.
535 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700536 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700537 public void notify(FlowRuleBatchEvent event) {
538 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700539 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700540 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800541 // Request has been forwarded to MASTER Node, and was
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700542 request.ops().forEach(
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800543 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800544 switch (op.operator()) {
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700545
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800546 case ADD:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700547 post(new FlowRuleEvent(RULE_ADD_REQUESTED,
548 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800549 break;
550 case REMOVE:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700551 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED,
552 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800553 break;
554 case MODIFY:
555 //TODO: do something here when the time comes.
556 break;
557 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800558 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800559 }
560 }
561 );
562
563 DeviceId deviceId = event.deviceId();
564
565 FlowRuleBatchOperation batchOperation =
566 request.asBatchOperation(deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700567
Thomas Vachuska27bee092015-06-23 19:03:10 -0700568 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
569 if (flowRuleProvider != null) {
570 flowRuleProvider.executeBatch(batchOperation);
571 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800572
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800573 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700574
Madan Jampani117aaae2014-10-23 10:04:05 -0700575 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800576
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800577 FlowOperationsProcessor fops = pendingFlowOperations.remove(
578 event.subject().batchId());
579 if (event.result().isSuccess()) {
580 if (fops != null) {
581 fops.satisfy(event.deviceId());
582 }
583 } else {
584 fops.fail(event.deviceId(), event.result().failedItems());
585 }
586
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700587 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800588
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700589 default:
590 break;
591 }
tomc78acee2014-09-24 15:16:55 -0700592 }
593 }
alshabib902d41b2014-10-07 16:52:05 -0700594
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800595 private class FlowOperationsProcessor implements Runnable {
alshabib902d41b2014-10-07 16:52:05 -0700596
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800597 private final List<Set<FlowRuleOperation>> stages;
598 private final FlowRuleOperationsContext context;
599 private final FlowRuleOperations fops;
Sho SHIMIZU27124192016-08-30 14:47:12 -0700600 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700601
Sho SHIMIZUb837cb72016-08-30 14:44:50 -0700602 private final Set<DeviceId> pendingDevices = new HashSet<>();
alshabib902d41b2014-10-07 16:52:05 -0700603
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700604 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800605 this.stages = Lists.newArrayList(ops.stages());
606 this.context = ops.callback();
607 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700608 }
609
610 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700611 public synchronized void run() {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800612 if (stages.size() > 0) {
613 process(stages.remove(0));
Sho SHIMIZU27124192016-08-30 14:47:12 -0700614 } else if (!hasFailed && context != null) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800615 context.onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700616 }
617 }
618
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800619 private void process(Set<FlowRuleOperation> ops) {
620 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches =
621 ArrayListMultimap.create();
622
623 FlowRuleBatchEntry fbe;
624 for (FlowRuleOperation flowRuleOperation : ops) {
625 switch (flowRuleOperation.type()) {
626 // FIXME: Brian needs imagination when creating class names.
627 case ADD:
628 fbe = new FlowRuleBatchEntry(
629 FlowRuleBatchEntry.FlowRuleOperation.ADD, flowRuleOperation.rule());
630 break;
631 case MODIFY:
632 fbe = new FlowRuleBatchEntry(
633 FlowRuleBatchEntry.FlowRuleOperation.MODIFY, flowRuleOperation.rule());
634 break;
635 case REMOVE:
636 fbe = new FlowRuleBatchEntry(
637 FlowRuleBatchEntry.FlowRuleOperation.REMOVE, flowRuleOperation.rule());
638 break;
639 default:
640 throw new UnsupportedOperationException("Unknown flow rule type " + flowRuleOperation.type());
641 }
642 pendingDevices.add(flowRuleOperation.rule().deviceId());
643 perDeviceBatches.put(flowRuleOperation.rule().deviceId(), fbe);
644 }
645
646
647 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700648 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800649 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
650 deviceId, id);
651 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700652 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700653 }
654 }
655
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700656 synchronized void satisfy(DeviceId devId) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800657 pendingDevices.remove(devId);
658 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700659 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700660 }
alshabib193525b2014-10-08 18:58:03 -0700661 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800662
663
664
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700665 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZU27124192016-08-30 14:47:12 -0700666 hasFailed = true;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800667 pendingDevices.remove(devId);
668 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700669 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800670 }
671
672 if (context != null) {
673 final FlowRuleOperations.Builder failedOpsBuilder =
674 FlowRuleOperations.builder();
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -0700675 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800676
677 context.onError(failedOpsBuilder.build());
678 }
679 }
680
alshabib902d41b2014-10-07 16:52:05 -0700681 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700682
683 @Override
684 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
685 checkPermission(FLOWRULE_READ);
686 return store.getTableStatistics(deviceId);
687 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800688
689 private class InternalDeviceListener implements DeviceListener {
690 @Override
691 public void event(DeviceEvent event) {
692 switch (event.type()) {
693 case DEVICE_REMOVED:
694 case DEVICE_AVAILABILITY_CHANGED:
695 DeviceId deviceId = event.subject().id();
696 if (!deviceService.isAvailable(deviceId)) {
697 if (purgeOnDisconnection) {
698 store.purgeFlowRule(deviceId);
699 }
700 }
701 break;
702 default:
703 break;
704 }
705 }
706 }
alshabib57044ba2014-09-16 15:58:01 -0700707}