blob: 0adc1cb89defb0f92baac67ced6dd8caf0ee156e [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;
Brian O'Connord12267c2015-02-17 18:17:08 -080070import java.util.List;
71import java.util.Map;
72import java.util.Set;
73import java.util.concurrent.ConcurrentHashMap;
74import java.util.concurrent.ExecutorService;
75import java.util.concurrent.Executors;
76import java.util.concurrent.atomic.AtomicBoolean;
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 */
Brian O'Connord12267c2015-02-17 18:17:08 -080094@Component(immediate = true, enabled = 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 Yuta060da9a2016-03-11 19:16:35 -0800128 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
247 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900248 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900249
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800250 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800251 for (FlowRule flowRule : flowRules) {
252 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700253 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800254 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700255 }
alshabib57044ba2014-09-16 15:58:01 -0700256
alshabiba68eb962014-09-24 20:34:13 -0700257 @Override
258 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900259 checkPermission(FLOWRULE_WRITE);
Madan Jampani6a456162014-10-24 11:36:17 -0700260 removeFlowRules(Iterables.toArray(getFlowRulesById(id), FlowRule.class));
alshabiba68eb962014-09-24 20:34:13 -0700261 }
262
263 @Override
264 public Iterable<FlowRule> getFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900265 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900266
Madan Jampani6a456162014-10-24 11:36:17 -0700267 Set<FlowRule> flowEntries = Sets.newHashSet();
268 for (Device d : deviceService.getDevices()) {
269 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
270 if (flowEntry.appId() == id.id()) {
271 flowEntries.add(flowEntry);
272 }
273 }
274 }
275 return flowEntries;
alshabib57044ba2014-09-16 15:58:01 -0700276 }
277
278 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800279 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900280 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900281
alshabibaa7e7de2014-11-12 19:20:44 -0800282 Set<FlowRule> matches = Sets.newHashSet();
283 long toLookUp = ((long) appId.id() << 16) | groupId;
284 for (Device d : deviceService.getDevices()) {
285 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
286 if ((flowEntry.id().value() >>> 32) == toLookUp) {
287 matches.add(flowEntry);
288 }
289 }
290 }
291 return matches;
292 }
293
294 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800295 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900296 checkPermission(FLOWRULE_WRITE);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800297 operationsService.submit(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700298 }
299
300 @Override
alshabib57044ba2014-09-16 15:58:01 -0700301 protected FlowRuleProviderService createProviderService(
302 FlowRuleProvider provider) {
303 return new InternalFlowRuleProviderService(provider);
304 }
305
306 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700307 extends AbstractProviderService<FlowRuleProvider>
308 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700309
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700310 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
311
alshabib57044ba2014-09-16 15:58:01 -0700312 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
313 super(provider);
314 }
315
316 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700317 public void flowRemoved(FlowEntry flowEntry) {
318 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700319 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700320 lastSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700321 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700322 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800323 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700324 return;
325 }
alshabib1c319ff2014-10-04 20:29:09 -0700326 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700327 FlowRuleProvider frp = getProvider(device.providerId());
328 FlowRuleEvent event = null;
329 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700330 case ADDED:
331 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700332 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700333 break;
334 case PENDING_REMOVE:
335 case REMOVED:
336 event = store.removeFlowRule(stored);
337 break;
338 default:
339 break;
alshabib57044ba2014-09-16 15:58:01 -0700340
alshabiba68eb962014-09-24 20:34:13 -0700341 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700342 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700343 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700344 post(event);
345 }
alshabib57044ba2014-09-16 15:58:01 -0700346 }
347
alshabibba5ac482014-10-02 17:15:20 -0700348
alshabib1c319ff2014-10-04 20:29:09 -0700349 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700350 checkNotNull(flowRule, FLOW_RULE_NULL);
351 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700352 Device device = deviceService.getDevice(flowRule.deviceId());
353 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700354 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700355 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700356 case PENDING_REMOVE:
357 case REMOVED:
358 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700359 break;
360 case ADDED:
361 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800362 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800363 try {
364 frp.applyFlowRule(flowRule);
365 } catch (UnsupportedOperationException e) {
366 log.warn(e.getMessage());
367 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800368 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800369 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
370 }
371 }
tom9b4030d2014-10-06 10:39:03 -0700372 break;
373 default:
374 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700375 }
376
alshabibbb42cad2014-09-25 11:43:05 -0700377 if (event != null) {
378 log.debug("Flow {} removed", flowRule);
379 post(event);
380 }
alshabib57044ba2014-09-16 15:58:01 -0700381 }
382
alshabibba5ac482014-10-02 17:15:20 -0700383 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700384 checkNotNull(flowRule, FLOW_RULE_NULL);
385 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700386 FlowRuleProvider frp = getProvider(flowRule.deviceId());
387 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700388 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700389 }
390
alshabib1c319ff2014-10-04 20:29:09 -0700391 private void flowAdded(FlowEntry flowEntry) {
392 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700393 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700394
alshabib1c319ff2014-10-04 20:29:09 -0700395 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700396 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700397 if (event == null) {
398 log.debug("No flow store event generated.");
399 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800400 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700401 post(event);
402 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700403 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800404 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700405 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700406 }
alshabib57044ba2014-09-16 15:58:01 -0700407 }
408
alshabib1c319ff2014-10-04 20:29:09 -0700409 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
410 if (storedRule == null) {
411 return false;
412 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700413 if (storedRule.isPermanent()) {
414 return true;
415 }
416
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700417 final long timeout = storedRule.timeout() * 1000;
418 final long currentTime = System.currentTimeMillis();
alshabib85c41972014-10-03 13:48:39 -0700419 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700420 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700421 return true;
422 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700423 if (!lastSeen.containsKey(storedRule)) {
424 // checking for the first time
425 lastSeen.put(storedRule, storedRule.lastSeen());
426 // Use following if lastSeen attr. was removed.
427 //lastSeen.put(storedRule, currentTime);
428 }
429 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700430
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800431 // concurrently removed? let the liveness check fail
432 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700433 }
434
alshabib5c370ff2014-09-18 10:12:14 -0700435 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700436 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900437 pushFlowMetricsInternal(deviceId, flowEntries, true);
438 }
439
440 @Override
441 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
442 pushFlowMetricsInternal(deviceId, flowEntries, false);
443 }
444
445 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
446 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700447 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
448 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
449
Saurav Dasfa2fa932015-03-03 11:29:48 -0800450 for (FlowEntry rule : flowEntries) {
451 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700452 FlowEntry storedRule = storedRules.remove(rule);
453 if (storedRule != null) {
454 if (storedRule.exactMatch(rule)) {
455 // we both have the rule, let's update some info then.
456 flowAdded(rule);
457 } else {
458 // the two rules are not an exact match - remove the
459 // switch's rule and install our rule
460 extraneousFlow(rule);
461 flowMissing(storedRule);
462 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800463 } else {
464 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700465 if (!allowExtraneousRules) {
466 extraneousFlow(rule);
467 }
alshabib93cb57f2015-02-12 17:43:26 -0800468 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700469 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800470 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800471 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800472 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900473
474 // DO NOT reinstall
475 if (useMissingFlow) {
476 for (FlowEntry rule : storedRules.keySet()) {
477 try {
478 // there are rules in the store that aren't on the switch
479 log.debug("Adding rule in store, but not on switch {}", rule);
480 flowMissing(rule);
481 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800482 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900483 }
alshabib93cb57f2015-02-12 17:43:26 -0800484 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800485 }
alshabib5c370ff2014-09-18 10:12:14 -0700486 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800487
488 @Override
489 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
490 store.batchOperationComplete(FlowRuleBatchEvent.completed(
491 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
492 operation
493 ));
494 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700495
496 @Override
497 public void pushTableStatistics(DeviceId deviceId,
498 List<TableStatisticsEntry> tableStats) {
499 store.updateTableStatistics(deviceId, tableStats);
500 }
alshabib57044ba2014-09-16 15:58:01 -0700501 }
502
tomc78acee2014-09-24 15:16:55 -0700503 // Store delegate to re-post events emitted from the store.
504 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800505
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800506
Madan Jampani117aaae2014-10-23 10:04:05 -0700507 // TODO: Right now we only dispatch events at individual flowEntry level.
508 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700509 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700510 public void notify(FlowRuleBatchEvent event) {
511 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700512 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700513 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800514 // Request has been forwarded to MASTER Node, and was
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800515 request.ops().stream().forEach(
516 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800517 switch (op.operator()) {
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700518
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800519 case ADD:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700520 post(new FlowRuleEvent(RULE_ADD_REQUESTED,
521 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800522 break;
523 case REMOVE:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700524 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED,
525 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800526 break;
527 case MODIFY:
528 //TODO: do something here when the time comes.
529 break;
530 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800531 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800532 }
533 }
534 );
535
536 DeviceId deviceId = event.deviceId();
537
538 FlowRuleBatchOperation batchOperation =
539 request.asBatchOperation(deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700540
Thomas Vachuska27bee092015-06-23 19:03:10 -0700541 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
542 if (flowRuleProvider != null) {
543 flowRuleProvider.executeBatch(batchOperation);
544 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800545
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800546 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700547
Madan Jampani117aaae2014-10-23 10:04:05 -0700548 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800549
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800550 FlowOperationsProcessor fops = pendingFlowOperations.remove(
551 event.subject().batchId());
552 if (event.result().isSuccess()) {
553 if (fops != null) {
554 fops.satisfy(event.deviceId());
555 }
556 } else {
557 fops.fail(event.deviceId(), event.result().failedItems());
558 }
559
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700560 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800561
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700562 default:
563 break;
564 }
tomc78acee2014-09-24 15:16:55 -0700565 }
566 }
alshabib902d41b2014-10-07 16:52:05 -0700567
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800568 private class FlowOperationsProcessor implements Runnable {
alshabib902d41b2014-10-07 16:52:05 -0700569
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800570 private final List<Set<FlowRuleOperation>> stages;
571 private final FlowRuleOperationsContext context;
572 private final FlowRuleOperations fops;
573 private final AtomicBoolean hasFailed = new AtomicBoolean(false);
alshabib902d41b2014-10-07 16:52:05 -0700574
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800575 private Set<DeviceId> pendingDevices;
alshabib902d41b2014-10-07 16:52:05 -0700576
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800577 public FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800578 this.stages = Lists.newArrayList(ops.stages());
579 this.context = ops.callback();
580 this.fops = ops;
581 pendingDevices = Sets.newConcurrentHashSet();
alshabib902d41b2014-10-07 16:52:05 -0700582 }
583
584 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800585 public void run() {
586 if (stages.size() > 0) {
587 process(stages.remove(0));
588 } else if (!hasFailed.get() && context != null) {
589 context.onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700590 }
591 }
592
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800593 private void process(Set<FlowRuleOperation> ops) {
594 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches =
595 ArrayListMultimap.create();
596
597 FlowRuleBatchEntry fbe;
598 for (FlowRuleOperation flowRuleOperation : ops) {
599 switch (flowRuleOperation.type()) {
600 // FIXME: Brian needs imagination when creating class names.
601 case ADD:
602 fbe = new FlowRuleBatchEntry(
603 FlowRuleBatchEntry.FlowRuleOperation.ADD, flowRuleOperation.rule());
604 break;
605 case MODIFY:
606 fbe = new FlowRuleBatchEntry(
607 FlowRuleBatchEntry.FlowRuleOperation.MODIFY, flowRuleOperation.rule());
608 break;
609 case REMOVE:
610 fbe = new FlowRuleBatchEntry(
611 FlowRuleBatchEntry.FlowRuleOperation.REMOVE, flowRuleOperation.rule());
612 break;
613 default:
614 throw new UnsupportedOperationException("Unknown flow rule type " + flowRuleOperation.type());
615 }
616 pendingDevices.add(flowRuleOperation.rule().deviceId());
617 perDeviceBatches.put(flowRuleOperation.rule().deviceId(), fbe);
618 }
619
620
621 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700622 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800623 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
624 deviceId, id);
625 pendingFlowOperations.put(id, this);
Sho SHIMIZUf88e5932015-05-27 12:03:51 -0700626 deviceInstallers.submit(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700627 }
628 }
629
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800630 public void satisfy(DeviceId devId) {
631 pendingDevices.remove(devId);
632 if (pendingDevices.isEmpty()) {
633 operationsService.submit(this);
alshabib193525b2014-10-08 18:58:03 -0700634 }
alshabib193525b2014-10-08 18:58:03 -0700635 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800636
637
638
639 public void fail(DeviceId devId, Set<? extends FlowRule> failures) {
640 hasFailed.set(true);
641 pendingDevices.remove(devId);
642 if (pendingDevices.isEmpty()) {
643 operationsService.submit(this);
644 }
645
646 if (context != null) {
647 final FlowRuleOperations.Builder failedOpsBuilder =
648 FlowRuleOperations.builder();
649 failures.stream().forEach(failedOpsBuilder::add);
650
651 context.onError(failedOpsBuilder.build());
652 }
653 }
654
alshabib902d41b2014-10-07 16:52:05 -0700655 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700656
657 @Override
658 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
659 checkPermission(FLOWRULE_READ);
660 return store.getTableStatistics(deviceId);
661 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800662
663 private class InternalDeviceListener implements DeviceListener {
664 @Override
665 public void event(DeviceEvent event) {
666 switch (event.type()) {
667 case DEVICE_REMOVED:
668 case DEVICE_AVAILABILITY_CHANGED:
669 DeviceId deviceId = event.subject().id();
670 if (!deviceService.isAvailable(deviceId)) {
671 if (purgeOnDisconnection) {
672 store.purgeFlowRule(deviceId);
673 }
674 }
675 break;
676 default:
677 break;
678 }
679 }
680 }
alshabib57044ba2014-09-16 15:58:01 -0700681}