blob: e5220b5cc05698bc0901d3aa948d7f500fc292f9 [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 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
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700316 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
317
alshabib57044ba2014-09-16 15:58:01 -0700318 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
319 super(provider);
320 }
321
322 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700323 public void flowRemoved(FlowEntry flowEntry) {
324 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700325 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700326 lastSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700327 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700328 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800329 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700330 return;
331 }
alshabib1c319ff2014-10-04 20:29:09 -0700332 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700333 FlowRuleProvider frp = getProvider(device.providerId());
334 FlowRuleEvent event = null;
335 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700336 case ADDED:
337 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700338 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700339 break;
340 case PENDING_REMOVE:
341 case REMOVED:
342 event = store.removeFlowRule(stored);
343 break;
344 default:
345 break;
alshabib57044ba2014-09-16 15:58:01 -0700346
alshabiba68eb962014-09-24 20:34:13 -0700347 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700348 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700349 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700350 post(event);
351 }
alshabib57044ba2014-09-16 15:58:01 -0700352 }
353
alshabibba5ac482014-10-02 17:15:20 -0700354
alshabib1c319ff2014-10-04 20:29:09 -0700355 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700356 checkNotNull(flowRule, FLOW_RULE_NULL);
357 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700358 Device device = deviceService.getDevice(flowRule.deviceId());
359 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700360 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700361 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700362 case PENDING_REMOVE:
363 case REMOVED:
364 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700365 break;
366 case ADDED:
367 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800368 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800369 try {
370 frp.applyFlowRule(flowRule);
371 } catch (UnsupportedOperationException e) {
372 log.warn(e.getMessage());
373 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800374 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800375 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
376 }
377 }
tom9b4030d2014-10-06 10:39:03 -0700378 break;
379 default:
380 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700381 }
382
alshabibbb42cad2014-09-25 11:43:05 -0700383 if (event != null) {
384 log.debug("Flow {} removed", flowRule);
385 post(event);
386 }
alshabib57044ba2014-09-16 15:58:01 -0700387 }
388
alshabibba5ac482014-10-02 17:15:20 -0700389 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700390 checkNotNull(flowRule, FLOW_RULE_NULL);
391 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700392 FlowRuleProvider frp = getProvider(flowRule.deviceId());
393 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700394 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700395 }
396
alshabib1c319ff2014-10-04 20:29:09 -0700397 private void flowAdded(FlowEntry flowEntry) {
398 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700399 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700400
alshabib1c319ff2014-10-04 20:29:09 -0700401 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700402 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700403 if (event == null) {
404 log.debug("No flow store event generated.");
405 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800406 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700407 post(event);
408 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700409 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800410 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700411 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700412 }
alshabib57044ba2014-09-16 15:58:01 -0700413 }
414
alshabib1c319ff2014-10-04 20:29:09 -0700415 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
416 if (storedRule == null) {
417 return false;
418 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700419 if (storedRule.isPermanent()) {
420 return true;
421 }
422
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700423 final long timeout = storedRule.timeout() * 1000;
424 final long currentTime = System.currentTimeMillis();
alshabib85c41972014-10-03 13:48:39 -0700425 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700426 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700427 return true;
428 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700429 if (!lastSeen.containsKey(storedRule)) {
430 // checking for the first time
431 lastSeen.put(storedRule, storedRule.lastSeen());
432 // Use following if lastSeen attr. was removed.
433 //lastSeen.put(storedRule, currentTime);
434 }
435 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700436
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800437 // concurrently removed? let the liveness check fail
438 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700439 }
440
alshabib5c370ff2014-09-18 10:12:14 -0700441 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700442 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900443 pushFlowMetricsInternal(deviceId, flowEntries, true);
444 }
445
446 @Override
447 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
448 pushFlowMetricsInternal(deviceId, flowEntries, false);
449 }
450
451 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
452 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700453 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
454 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
455
Saurav Dasfa2fa932015-03-03 11:29:48 -0800456 for (FlowEntry rule : flowEntries) {
457 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700458 FlowEntry storedRule = storedRules.remove(rule);
459 if (storedRule != null) {
460 if (storedRule.exactMatch(rule)) {
461 // we both have the rule, let's update some info then.
462 flowAdded(rule);
463 } else {
464 // the two rules are not an exact match - remove the
465 // switch's rule and install our rule
466 extraneousFlow(rule);
467 flowMissing(storedRule);
468 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800469 } else {
470 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700471 if (!allowExtraneousRules) {
472 extraneousFlow(rule);
473 }
alshabib93cb57f2015-02-12 17:43:26 -0800474 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700475 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800476 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800477 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800478 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900479
480 // DO NOT reinstall
481 if (useMissingFlow) {
482 for (FlowEntry rule : storedRules.keySet()) {
483 try {
484 // there are rules in the store that aren't on the switch
485 log.debug("Adding rule in store, but not on switch {}", rule);
486 flowMissing(rule);
487 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800488 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900489 }
alshabib93cb57f2015-02-12 17:43:26 -0800490 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800491 }
alshabib5c370ff2014-09-18 10:12:14 -0700492 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800493
494 @Override
495 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
496 store.batchOperationComplete(FlowRuleBatchEvent.completed(
497 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
498 operation
499 ));
500 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700501
502 @Override
503 public void pushTableStatistics(DeviceId deviceId,
504 List<TableStatisticsEntry> tableStats) {
505 store.updateTableStatistics(deviceId, tableStats);
506 }
alshabib57044ba2014-09-16 15:58:01 -0700507 }
508
tomc78acee2014-09-24 15:16:55 -0700509 // Store delegate to re-post events emitted from the store.
510 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800511
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800512
Madan Jampani117aaae2014-10-23 10:04:05 -0700513 // TODO: Right now we only dispatch events at individual flowEntry level.
514 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700515 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700516 public void notify(FlowRuleBatchEvent event) {
517 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700518 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700519 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800520 // Request has been forwarded to MASTER Node, and was
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800521 request.ops().stream().forEach(
522 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800523 switch (op.operator()) {
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700524
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800525 case ADD:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700526 post(new FlowRuleEvent(RULE_ADD_REQUESTED,
527 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800528 break;
529 case REMOVE:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700530 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED,
531 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800532 break;
533 case MODIFY:
534 //TODO: do something here when the time comes.
535 break;
536 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800537 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800538 }
539 }
540 );
541
542 DeviceId deviceId = event.deviceId();
543
544 FlowRuleBatchOperation batchOperation =
545 request.asBatchOperation(deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700546
Thomas Vachuska27bee092015-06-23 19:03:10 -0700547 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
548 if (flowRuleProvider != null) {
549 flowRuleProvider.executeBatch(batchOperation);
550 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800551
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800552 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700553
Madan Jampani117aaae2014-10-23 10:04:05 -0700554 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800555
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800556 FlowOperationsProcessor fops = pendingFlowOperations.remove(
557 event.subject().batchId());
558 if (event.result().isSuccess()) {
559 if (fops != null) {
560 fops.satisfy(event.deviceId());
561 }
562 } else {
563 fops.fail(event.deviceId(), event.result().failedItems());
564 }
565
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700566 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800567
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700568 default:
569 break;
570 }
tomc78acee2014-09-24 15:16:55 -0700571 }
572 }
alshabib902d41b2014-10-07 16:52:05 -0700573
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800574 private class FlowOperationsProcessor implements Runnable {
alshabib902d41b2014-10-07 16:52:05 -0700575
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800576 private final List<Set<FlowRuleOperation>> stages;
577 private final FlowRuleOperationsContext context;
578 private final FlowRuleOperations fops;
579 private final AtomicBoolean hasFailed = new AtomicBoolean(false);
alshabib902d41b2014-10-07 16:52:05 -0700580
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800581 private Set<DeviceId> pendingDevices;
alshabib902d41b2014-10-07 16:52:05 -0700582
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800583 public FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800584 this.stages = Lists.newArrayList(ops.stages());
585 this.context = ops.callback();
586 this.fops = ops;
587 pendingDevices = Sets.newConcurrentHashSet();
alshabib902d41b2014-10-07 16:52:05 -0700588 }
589
590 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800591 public void run() {
592 if (stages.size() > 0) {
593 process(stages.remove(0));
594 } else if (!hasFailed.get() && context != null) {
595 context.onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700596 }
597 }
598
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800599 private void process(Set<FlowRuleOperation> ops) {
600 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches =
601 ArrayListMultimap.create();
602
603 FlowRuleBatchEntry fbe;
604 for (FlowRuleOperation flowRuleOperation : ops) {
605 switch (flowRuleOperation.type()) {
606 // FIXME: Brian needs imagination when creating class names.
607 case ADD:
608 fbe = new FlowRuleBatchEntry(
609 FlowRuleBatchEntry.FlowRuleOperation.ADD, flowRuleOperation.rule());
610 break;
611 case MODIFY:
612 fbe = new FlowRuleBatchEntry(
613 FlowRuleBatchEntry.FlowRuleOperation.MODIFY, flowRuleOperation.rule());
614 break;
615 case REMOVE:
616 fbe = new FlowRuleBatchEntry(
617 FlowRuleBatchEntry.FlowRuleOperation.REMOVE, flowRuleOperation.rule());
618 break;
619 default:
620 throw new UnsupportedOperationException("Unknown flow rule type " + flowRuleOperation.type());
621 }
622 pendingDevices.add(flowRuleOperation.rule().deviceId());
623 perDeviceBatches.put(flowRuleOperation.rule().deviceId(), fbe);
624 }
625
626
627 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700628 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800629 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
630 deviceId, id);
631 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700632 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700633 }
634 }
635
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800636 public void satisfy(DeviceId devId) {
637 pendingDevices.remove(devId);
638 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700639 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700640 }
alshabib193525b2014-10-08 18:58:03 -0700641 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800642
643
644
645 public void fail(DeviceId devId, Set<? extends FlowRule> failures) {
646 hasFailed.set(true);
647 pendingDevices.remove(devId);
648 if (pendingDevices.isEmpty()) {
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700649 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800650 }
651
652 if (context != null) {
653 final FlowRuleOperations.Builder failedOpsBuilder =
654 FlowRuleOperations.builder();
655 failures.stream().forEach(failedOpsBuilder::add);
656
657 context.onError(failedOpsBuilder.build());
658 }
659 }
660
alshabib902d41b2014-10-07 16:52:05 -0700661 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700662
663 @Override
664 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
665 checkPermission(FLOWRULE_READ);
666 return store.getTableStatistics(deviceId);
667 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800668
669 private class InternalDeviceListener implements DeviceListener {
670 @Override
671 public void event(DeviceEvent event) {
672 switch (event.type()) {
673 case DEVICE_REMOVED:
674 case DEVICE_AVAILABILITY_CHANGED:
675 DeviceId deviceId = event.subject().id();
676 if (!deviceService.isAvailable(deviceId)) {
677 if (purgeOnDisconnection) {
678 store.purgeFlowRule(deviceId);
679 }
680 }
681 break;
682 default:
683 break;
684 }
685 }
686 }
alshabib57044ba2014-09-16 15:58:01 -0700687}