blob: c3f1200ba08a8add3ba8883661bde8adf2d84935 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 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() {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700163 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800164 deviceInstallers.shutdownNow();
165 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700166 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700167 eventDispatcher.removeSink(FlowRuleEvent.class);
168 log.info("Stopped");
169 }
170
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700171 @Modified
172 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800173 if (context != null) {
174 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700175 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800176 defaultProvider.init(new InternalFlowRuleProviderService(defaultProvider),
177 deviceService, mastershipService, fallbackFlowPollFrequency);
178 }
179
180 @Override
181 protected FlowRuleProvider defaultProvider() {
182 return defaultProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800183 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700184
Charles Chan0c7c43b2016-01-14 17:39:20 -0800185 /**
186 * Extracts properties from the component configuration context.
187 *
188 * @param context the component context
189 */
190 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700191 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800192 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700193
Jian Lid9b5f552016-03-11 18:15:31 -0800194 flag = Tools.isPropertyEnabled(properties, "allowExtraneousRules");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800195 if (flag == null) {
196 log.info("AllowExtraneousRules is not configured, " +
197 "using current value of {}", allowExtraneousRules);
198 } else {
199 allowExtraneousRules = flag;
200 log.info("Configured. AllowExtraneousRules is {}",
201 allowExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700202 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800203
Jian Lid9b5f552016-03-11 18:15:31 -0800204 flag = Tools.isPropertyEnabled(properties, "purgeOnDisconnection");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800205 if (flag == null) {
206 log.info("PurgeOnDisconnection is not configured, " +
207 "using current value of {}", purgeOnDisconnection);
208 } else {
209 purgeOnDisconnection = flag;
210 log.info("Configured. PurgeOnDisconnection is {}",
211 purgeOnDisconnection ? "enabled" : "disabled");
212 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800213
214 String s = get(properties, "fallbackFlowPollFrequency");
215 try {
216 fallbackFlowPollFrequency = isNullOrEmpty(s) ? DEFAULT_POLL_FREQUENCY : Integer.parseInt(s);
217 } catch (NumberFormatException e) {
218 fallbackFlowPollFrequency = DEFAULT_POLL_FREQUENCY;
219 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800220 }
221
alshabib57044ba2014-09-16 15:58:01 -0700222 @Override
tom9b4030d2014-10-06 10:39:03 -0700223 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900224 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700225 return store.getFlowRuleCount();
226 }
227
228 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700229 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900230 checkPermission(FLOWRULE_READ);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700231 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700232 }
233
234 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700235 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900236 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900237
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800238 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800239 for (FlowRule flowRule : flowRules) {
240 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700241 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800242 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700243 }
244
245 @Override
246 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900247 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900248
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800249 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800250 for (FlowRule flowRule : flowRules) {
251 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700252 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800253 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700254 }
alshabib57044ba2014-09-16 15:58:01 -0700255
alshabiba68eb962014-09-24 20:34:13 -0700256 @Override
257 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900258 checkPermission(FLOWRULE_WRITE);
Madan Jampani6a456162014-10-24 11:36:17 -0700259 removeFlowRules(Iterables.toArray(getFlowRulesById(id), FlowRule.class));
alshabiba68eb962014-09-24 20:34:13 -0700260 }
261
262 @Override
263 public Iterable<FlowRule> getFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900264 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900265
Madan Jampani6a456162014-10-24 11:36:17 -0700266 Set<FlowRule> flowEntries = Sets.newHashSet();
267 for (Device d : deviceService.getDevices()) {
268 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
269 if (flowEntry.appId() == id.id()) {
270 flowEntries.add(flowEntry);
271 }
272 }
273 }
274 return flowEntries;
alshabib57044ba2014-09-16 15:58:01 -0700275 }
276
277 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800278 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900279 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900280
alshabibaa7e7de2014-11-12 19:20:44 -0800281 Set<FlowRule> matches = Sets.newHashSet();
282 long toLookUp = ((long) appId.id() << 16) | groupId;
283 for (Device d : deviceService.getDevices()) {
284 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
285 if ((flowEntry.id().value() >>> 32) == toLookUp) {
286 matches.add(flowEntry);
287 }
288 }
289 }
290 return matches;
291 }
292
293 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800294 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900295 checkPermission(FLOWRULE_WRITE);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800296 operationsService.submit(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700297 }
298
299 @Override
alshabib57044ba2014-09-16 15:58:01 -0700300 protected FlowRuleProviderService createProviderService(
301 FlowRuleProvider provider) {
302 return new InternalFlowRuleProviderService(provider);
303 }
304
305 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700306 extends AbstractProviderService<FlowRuleProvider>
307 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700308
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700309 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
310
alshabib57044ba2014-09-16 15:58:01 -0700311 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
312 super(provider);
313 }
314
315 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700316 public void flowRemoved(FlowEntry flowEntry) {
317 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700318 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700319 lastSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700320 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700321 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800322 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700323 return;
324 }
alshabib1c319ff2014-10-04 20:29:09 -0700325 Device device = deviceService.getDevice(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700326 FlowRuleProvider frp = getProvider(device.providerId());
327 FlowRuleEvent event = null;
328 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700329 case ADDED:
330 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700331 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700332 break;
333 case PENDING_REMOVE:
334 case REMOVED:
335 event = store.removeFlowRule(stored);
336 break;
337 default:
338 break;
alshabib57044ba2014-09-16 15:58:01 -0700339
alshabiba68eb962014-09-24 20:34:13 -0700340 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700341 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700342 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700343 post(event);
344 }
alshabib57044ba2014-09-16 15:58:01 -0700345 }
346
alshabibba5ac482014-10-02 17:15:20 -0700347
alshabib1c319ff2014-10-04 20:29:09 -0700348 private void flowMissing(FlowEntry flowRule) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700349 checkNotNull(flowRule, FLOW_RULE_NULL);
350 checkValidity();
alshabiba68eb962014-09-24 20:34:13 -0700351 Device device = deviceService.getDevice(flowRule.deviceId());
352 FlowRuleProvider frp = getProvider(device.providerId());
alshabibbb42cad2014-09-25 11:43:05 -0700353 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700354 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700355 case PENDING_REMOVE:
356 case REMOVED:
357 event = store.removeFlowRule(flowRule);
tom9b4030d2014-10-06 10:39:03 -0700358 break;
359 case ADDED:
360 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800361 event = store.pendingFlowRule(flowRule);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800362 try {
363 frp.applyFlowRule(flowRule);
364 } catch (UnsupportedOperationException e) {
365 log.warn(e.getMessage());
366 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800367 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800368 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
369 }
370 }
tom9b4030d2014-10-06 10:39:03 -0700371 break;
372 default:
373 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700374 }
375
alshabibbb42cad2014-09-25 11:43:05 -0700376 if (event != null) {
377 log.debug("Flow {} removed", flowRule);
378 post(event);
379 }
alshabib57044ba2014-09-16 15:58:01 -0700380 }
381
alshabibba5ac482014-10-02 17:15:20 -0700382 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700383 checkNotNull(flowRule, FLOW_RULE_NULL);
384 checkValidity();
alshabib2374fc92014-10-22 11:03:23 -0700385 FlowRuleProvider frp = getProvider(flowRule.deviceId());
386 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700387 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700388 }
389
alshabib1c319ff2014-10-04 20:29:09 -0700390 private void flowAdded(FlowEntry flowEntry) {
391 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700392 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700393
alshabib1c319ff2014-10-04 20:29:09 -0700394 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700395 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700396 if (event == null) {
397 log.debug("No flow store event generated.");
398 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800399 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700400 post(event);
401 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700402 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800403 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700404 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700405 }
alshabib57044ba2014-09-16 15:58:01 -0700406 }
407
alshabib1c319ff2014-10-04 20:29:09 -0700408 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
409 if (storedRule == null) {
410 return false;
411 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700412 if (storedRule.isPermanent()) {
413 return true;
414 }
415
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700416 final long timeout = storedRule.timeout() * 1000;
417 final long currentTime = System.currentTimeMillis();
alshabib85c41972014-10-03 13:48:39 -0700418 if (storedRule.packets() != swRule.packets()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700419 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700420 return true;
421 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700422 if (!lastSeen.containsKey(storedRule)) {
423 // checking for the first time
424 lastSeen.put(storedRule, storedRule.lastSeen());
425 // Use following if lastSeen attr. was removed.
426 //lastSeen.put(storedRule, currentTime);
427 }
428 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700429
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800430 // concurrently removed? let the liveness check fail
431 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700432 }
433
alshabib5c370ff2014-09-18 10:12:14 -0700434 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700435 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900436 pushFlowMetricsInternal(deviceId, flowEntries, true);
437 }
438
439 @Override
440 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
441 pushFlowMetricsInternal(deviceId, flowEntries, false);
442 }
443
444 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
445 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700446 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
447 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
448
Saurav Dasfa2fa932015-03-03 11:29:48 -0800449 for (FlowEntry rule : flowEntries) {
450 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700451 FlowEntry storedRule = storedRules.remove(rule);
452 if (storedRule != null) {
453 if (storedRule.exactMatch(rule)) {
454 // we both have the rule, let's update some info then.
455 flowAdded(rule);
456 } else {
457 // the two rules are not an exact match - remove the
458 // switch's rule and install our rule
459 extraneousFlow(rule);
460 flowMissing(storedRule);
461 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800462 } else {
463 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700464 if (!allowExtraneousRules) {
465 extraneousFlow(rule);
466 }
alshabib93cb57f2015-02-12 17:43:26 -0800467 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700468 } catch (Exception e) {
Saurav Dasfa2fa932015-03-03 11:29:48 -0800469 log.debug("Can't process added or extra rule {}", e.getMessage());
alshabib93cb57f2015-02-12 17:43:26 -0800470 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800471 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900472
473 // DO NOT reinstall
474 if (useMissingFlow) {
475 for (FlowEntry rule : storedRules.keySet()) {
476 try {
477 // there are rules in the store that aren't on the switch
478 log.debug("Adding rule in store, but not on switch {}", rule);
479 flowMissing(rule);
480 } catch (Exception e) {
Jonathan Hart26a8d952015-12-02 15:16:35 -0800481 log.debug("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900482 }
alshabib93cb57f2015-02-12 17:43:26 -0800483 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800484 }
alshabib5c370ff2014-09-18 10:12:14 -0700485 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800486
487 @Override
488 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
489 store.batchOperationComplete(FlowRuleBatchEvent.completed(
490 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
491 operation
492 ));
493 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700494
495 @Override
496 public void pushTableStatistics(DeviceId deviceId,
497 List<TableStatisticsEntry> tableStats) {
498 store.updateTableStatistics(deviceId, tableStats);
499 }
alshabib57044ba2014-09-16 15:58:01 -0700500 }
501
tomc78acee2014-09-24 15:16:55 -0700502 // Store delegate to re-post events emitted from the store.
503 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800504
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800505
Madan Jampani117aaae2014-10-23 10:04:05 -0700506 // TODO: Right now we only dispatch events at individual flowEntry level.
507 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700508 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700509 public void notify(FlowRuleBatchEvent event) {
510 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700511 switch (event.type()) {
Madan Jampani117aaae2014-10-23 10:04:05 -0700512 case BATCH_OPERATION_REQUESTED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800513 // Request has been forwarded to MASTER Node, and was
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800514 request.ops().stream().forEach(
515 op -> {
Ray Milkeyf7329c72015-02-17 11:37:01 -0800516 switch (op.operator()) {
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700517
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800518 case ADD:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700519 post(new FlowRuleEvent(RULE_ADD_REQUESTED,
520 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800521 break;
522 case REMOVE:
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700523 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED,
524 op.target()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800525 break;
526 case MODIFY:
527 //TODO: do something here when the time comes.
528 break;
529 default:
Ray Milkeyf7329c72015-02-17 11:37:01 -0800530 log.warn("Unknown flow operation operator: {}", op.operator());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800531 }
532 }
533 );
534
535 DeviceId deviceId = event.deviceId();
536
537 FlowRuleBatchOperation batchOperation =
538 request.asBatchOperation(deviceId);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700539
Thomas Vachuska27bee092015-06-23 19:03:10 -0700540 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
541 if (flowRuleProvider != null) {
542 flowRuleProvider.executeBatch(batchOperation);
543 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800544
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800545 break;
Madan Jampani117aaae2014-10-23 10:04:05 -0700546
Madan Jampani117aaae2014-10-23 10:04:05 -0700547 case BATCH_OPERATION_COMPLETED:
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800548
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800549 FlowOperationsProcessor fops = pendingFlowOperations.remove(
550 event.subject().batchId());
551 if (event.result().isSuccess()) {
552 if (fops != null) {
553 fops.satisfy(event.deviceId());
554 }
555 } else {
556 fops.fail(event.deviceId(), event.result().failedItems());
557 }
558
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700559 break;
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800560
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700561 default:
562 break;
563 }
tomc78acee2014-09-24 15:16:55 -0700564 }
565 }
alshabib902d41b2014-10-07 16:52:05 -0700566
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800567 private class FlowOperationsProcessor implements Runnable {
alshabib902d41b2014-10-07 16:52:05 -0700568
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800569 private final List<Set<FlowRuleOperation>> stages;
570 private final FlowRuleOperationsContext context;
571 private final FlowRuleOperations fops;
572 private final AtomicBoolean hasFailed = new AtomicBoolean(false);
alshabib902d41b2014-10-07 16:52:05 -0700573
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800574 private Set<DeviceId> pendingDevices;
alshabib902d41b2014-10-07 16:52:05 -0700575
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800576 public FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800577 this.stages = Lists.newArrayList(ops.stages());
578 this.context = ops.callback();
579 this.fops = ops;
580 pendingDevices = Sets.newConcurrentHashSet();
alshabib902d41b2014-10-07 16:52:05 -0700581 }
582
583 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800584 public void run() {
585 if (stages.size() > 0) {
586 process(stages.remove(0));
587 } else if (!hasFailed.get() && context != null) {
588 context.onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700589 }
590 }
591
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800592 private void process(Set<FlowRuleOperation> ops) {
593 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches =
594 ArrayListMultimap.create();
595
596 FlowRuleBatchEntry fbe;
597 for (FlowRuleOperation flowRuleOperation : ops) {
598 switch (flowRuleOperation.type()) {
599 // FIXME: Brian needs imagination when creating class names.
600 case ADD:
601 fbe = new FlowRuleBatchEntry(
602 FlowRuleBatchEntry.FlowRuleOperation.ADD, flowRuleOperation.rule());
603 break;
604 case MODIFY:
605 fbe = new FlowRuleBatchEntry(
606 FlowRuleBatchEntry.FlowRuleOperation.MODIFY, flowRuleOperation.rule());
607 break;
608 case REMOVE:
609 fbe = new FlowRuleBatchEntry(
610 FlowRuleBatchEntry.FlowRuleOperation.REMOVE, flowRuleOperation.rule());
611 break;
612 default:
613 throw new UnsupportedOperationException("Unknown flow rule type " + flowRuleOperation.type());
614 }
615 pendingDevices.add(flowRuleOperation.rule().deviceId());
616 perDeviceBatches.put(flowRuleOperation.rule().deviceId(), fbe);
617 }
618
619
620 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700621 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800622 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
623 deviceId, id);
624 pendingFlowOperations.put(id, this);
Sho SHIMIZUf88e5932015-05-27 12:03:51 -0700625 deviceInstallers.submit(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700626 }
627 }
628
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800629 public void satisfy(DeviceId devId) {
630 pendingDevices.remove(devId);
631 if (pendingDevices.isEmpty()) {
632 operationsService.submit(this);
alshabib193525b2014-10-08 18:58:03 -0700633 }
alshabib193525b2014-10-08 18:58:03 -0700634 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800635
636
637
638 public void fail(DeviceId devId, Set<? extends FlowRule> failures) {
639 hasFailed.set(true);
640 pendingDevices.remove(devId);
641 if (pendingDevices.isEmpty()) {
642 operationsService.submit(this);
643 }
644
645 if (context != null) {
646 final FlowRuleOperations.Builder failedOpsBuilder =
647 FlowRuleOperations.builder();
648 failures.stream().forEach(failedOpsBuilder::add);
649
650 context.onError(failedOpsBuilder.build());
651 }
652 }
653
alshabib902d41b2014-10-07 16:52:05 -0700654 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700655
656 @Override
657 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
658 checkPermission(FLOWRULE_READ);
659 return store.getTableStatistics(deviceId);
660 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800661
662 private class InternalDeviceListener implements DeviceListener {
663 @Override
664 public void event(DeviceEvent event) {
665 switch (event.type()) {
666 case DEVICE_REMOVED:
667 case DEVICE_AVAILABILITY_CHANGED:
668 DeviceId deviceId = event.subject().id();
669 if (!deviceService.isAvailable(deviceId)) {
670 if (purgeOnDisconnection) {
671 store.purgeFlowRule(deviceId);
672 }
673 }
674 break;
675 default:
676 break;
677 }
678 }
679 }
alshabib57044ba2014-09-16 15:58:01 -0700680}