blob: d25ceaba3375833a292fcc44579b157168f378d3 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
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;
pierventre07af21d2022-03-18 10:31:04 +010024import org.onlab.util.PredictableExecutor;
25import org.onlab.util.PredictableExecutor.PickyRunnable;
Jian Lid9b5f552016-03-11 18:15:31 -080026import org.onlab.util.Tools;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070027import org.onosproject.cfg.ComponentConfigService;
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +000028import org.onosproject.cluster.ClusterService;
29import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080030import org.onosproject.core.ApplicationId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080031import org.onosproject.core.CoreService;
32import org.onosproject.core.IdGenerator;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080033import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.net.Device;
35import org.onosproject.net.DeviceId;
Andrea Campanella32a9c0b2020-03-27 12:53:46 +010036import org.onosproject.net.config.NetworkConfigRegistry;
37import org.onosproject.net.config.basics.BasicDeviceConfig;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080038import org.onosproject.net.device.DeviceEvent;
39import org.onosproject.net.device.DeviceListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.device.DeviceService;
Jordan Halterman4f3193a2017-07-11 20:32:49 -070041import org.onosproject.net.driver.DriverService;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.flow.CompletedBatchOperation;
Charles M.C. Chan1229eca2015-05-18 06:27:52 +080043import org.onosproject.net.flow.DefaultFlowEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080044import org.onosproject.net.flow.FlowEntry;
45import org.onosproject.net.flow.FlowRule;
Brian O'Connorabafb502014-12-02 22:26:20 -080046import org.onosproject.net.flow.FlowRuleEvent;
47import org.onosproject.net.flow.FlowRuleListener;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080048import org.onosproject.net.flow.FlowRuleOperation;
49import org.onosproject.net.flow.FlowRuleOperations;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080050import org.onosproject.net.flow.FlowRuleProgrammable;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.flow.FlowRuleProvider;
52import org.onosproject.net.flow.FlowRuleProviderRegistry;
53import org.onosproject.net.flow.FlowRuleProviderService;
54import org.onosproject.net.flow.FlowRuleService;
55import org.onosproject.net.flow.FlowRuleStore;
56import org.onosproject.net.flow.FlowRuleStoreDelegate;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070057import org.onosproject.net.flow.TableStatisticsEntry;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070058import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry;
59import org.onosproject.net.flow.oldbatch.FlowRuleBatchEvent;
60import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation;
61import org.onosproject.net.flow.oldbatch.FlowRuleBatchRequest;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080062import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080064import org.onosproject.net.provider.ProviderId;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070065import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070066import org.osgi.service.component.annotations.Activate;
67import org.osgi.service.component.annotations.Component;
68import org.osgi.service.component.annotations.Deactivate;
69import org.osgi.service.component.annotations.Modified;
70import org.osgi.service.component.annotations.Reference;
71import org.osgi.service.component.annotations.ReferenceCardinality;
alshabib57044ba2014-09-16 15:58:01 -070072import org.slf4j.Logger;
73
Brian O'Connord12267c2015-02-17 18:17:08 -080074import java.util.Collections;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070075import java.util.Dictionary;
Sho SHIMIZUb837cb72016-08-30 14:44:50 -070076import java.util.HashSet;
Brian O'Connord12267c2015-02-17 18:17:08 -080077import java.util.List;
78import java.util.Map;
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +000079import java.util.Objects;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080080import java.util.Optional;
pierventre55c6f332022-03-29 15:10:39 +020081import java.util.Random;
Brian O'Connord12267c2015-02-17 18:17:08 -080082import java.util.Set;
83import java.util.concurrent.ConcurrentHashMap;
84import java.util.concurrent.ExecutorService;
85import java.util.concurrent.Executors;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080086
Thomas Vachuska9b2da212014-11-10 19:30:25 -080087import static com.google.common.base.Preconditions.checkNotNull;
Charles Chan0c7c43b2016-01-14 17:39:20 -080088import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080089import static org.onlab.util.Tools.get;
Brian O'Connord12267c2015-02-17 18:17:08 -080090import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070091import static org.onosproject.net.OsgiPropertyConstants.ALLOW_EXTRANEOUS_RULES;
92import static org.onosproject.net.OsgiPropertyConstants.ALLOW_EXTRANEOUS_RULES_DEFAULT;
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +010093import static org.onosproject.net.OsgiPropertyConstants.IMPORT_EXTRANEOUS_RULES;
94import static org.onosproject.net.OsgiPropertyConstants.IMPORT_EXTRANEOUS_RULES_DEFAULT;
Ray Milkeyd04e2272018-10-16 18:20:18 -070095import static org.onosproject.net.OsgiPropertyConstants.POLL_FREQUENCY;
96import static org.onosproject.net.OsgiPropertyConstants.POLL_FREQUENCY_DEFAULT;
97import static org.onosproject.net.OsgiPropertyConstants.PURGE_ON_DISCONNECTION;
98import static org.onosproject.net.OsgiPropertyConstants.PURGE_ON_DISCONNECTION_DEFAULT;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070099import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_ADD_REQUESTED;
100import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVE_REQUESTED;
Changhoon Yoon541ef712015-05-23 17:18:34 +0900101import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800102import static org.onosproject.security.AppPermission.Type.FLOWRULE_READ;
103import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700104import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +0900105
tome4729872014-09-23 00:37:37 -0700106/**
107 * Provides implementation of the flow NB & SB APIs.
108 */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700109@Component(
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100110 immediate = true,
111 service = {
112 FlowRuleService.class,
113 FlowRuleProviderRegistry.class
114 },
115 property = {
116 ALLOW_EXTRANEOUS_RULES + ":Boolean=" + ALLOW_EXTRANEOUS_RULES_DEFAULT,
117 IMPORT_EXTRANEOUS_RULES + ":Boolean=" + IMPORT_EXTRANEOUS_RULES_DEFAULT,
118 PURGE_ON_DISCONNECTION + ":Boolean=" + PURGE_ON_DISCONNECTION_DEFAULT,
119 POLL_FREQUENCY + ":Integer=" + POLL_FREQUENCY_DEFAULT
120 }
Ray Milkeyd04e2272018-10-16 18:20:18 -0700121)
tom202175a2014-09-19 19:00:11 -0700122public class FlowRuleManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700123 extends AbstractListenerProviderRegistry<FlowRuleEvent, FlowRuleListener,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100124 FlowRuleProvider, FlowRuleProviderService>
tom9b4030d2014-10-06 10:39:03 -0700125 implements FlowRuleService, FlowRuleProviderRegistry {
alshabib57044ba2014-09-16 15:58:01 -0700126
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800127 private final Logger log = getLogger(getClass());
128
Thomas Vachuska227943d2018-03-19 09:37:28 -0700129 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
130 private static final String FLOW_RULE_NULL = "FlowRule cannot be null";
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700131
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700132 /** Allow flow rules in switch not installed by ONOS. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700133 private boolean allowExtraneousRules = ALLOW_EXTRANEOUS_RULES_DEFAULT;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700134
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100135 /** Allow to import flow rules in switch not installed by ONOS. */
136 private boolean importExtraneousRules = IMPORT_EXTRANEOUS_RULES_DEFAULT;
137
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700138 /** Purge entries associated with a device when the device goes offline. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700139 private boolean purgeOnDisconnection = PURGE_ON_DISCONNECTION_DEFAULT;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800140
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700141 /** Frequency (in seconds) for polling flow statistics via fallback provider. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700142 private int fallbackFlowPollFrequency = POLL_FREQUENCY_DEFAULT;
alshabib57044ba2014-09-16 15:58:01 -0700143
alshabibbb42cad2014-09-25 11:43:05 -0700144 private final FlowRuleStoreDelegate delegate = new InternalStoreDelegate();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800145 private final DeviceListener deviceListener = new InternalDeviceListener();
tomc78acee2014-09-24 15:16:55 -0700146
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800147 private final FlowRuleDriverProvider driverProvider = new FlowRuleDriverProvider();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800148
pierventre07af21d2022-03-18 10:31:04 +0100149 protected ExecutorService deviceInstallers = Executors.newFixedThreadPool(32,
150 groupedThreads("onos/flowservice", "device-installer-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800151
pierventre07af21d2022-03-18 10:31:04 +0100152 protected ExecutorService operationsService = new PredictableExecutor(32,
153 groupedThreads("onos/flowservice", "operations-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800154
155 private IdGenerator idGenerator;
156
Sho SHIMIZU9f950742016-09-01 09:55:38 -0700157 private final Map<Long, FlowOperationsProcessor> pendingFlowOperations = new ConcurrentHashMap<>();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700158
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000159 private NodeId local;
160
pierventre55c6f332022-03-29 15:10:39 +0200161 private Random randomGenerator = new Random();
162
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700163 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tombe988312014-09-19 18:38:47 -0700164 protected FlowRuleStore store;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700165
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700166 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibeb55524f2014-09-18 09:59:24 -0700167 protected DeviceService deviceService;
alshabib57044ba2014-09-16 15:58:01 -0700168
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700169 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800170 protected CoreService coreService;
171
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700172 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800173 protected MastershipService mastershipService;
174
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700175 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700176 protected ComponentConfigService cfgService;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800177
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700178 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman4f3193a2017-07-11 20:32:49 -0700179 protected DriverService driverService;
180
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000181 @Reference(cardinality = ReferenceCardinality.MANDATORY)
182 protected ClusterService clusterService;
183
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100184 @Reference(cardinality = ReferenceCardinality.MANDATORY)
185 protected NetworkConfigRegistry netCfgService;
186
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700187 @Activate
188 public void activate(ComponentContext context) {
tomc78acee2014-09-24 15:16:55 -0700189 store.setDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700190 eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800191 deviceService.addListener(deviceListener);
192 cfgService.registerProperties(getClass());
piered2a0a42019-04-16 11:48:08 +0200193 modified(context);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800194 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000195 local = clusterService.getLocalNode().id();
alshabib57044ba2014-09-16 15:58:01 -0700196 log.info("Started");
197 }
198
199 @Deactivate
200 public void deactivate() {
Andrea Campanella5a3c09c2017-12-01 13:57:48 +0100201 driverProvider.terminate();
Andrea Campanella3f1c61e2016-04-01 17:30:12 -0700202 deviceService.removeListener(deviceListener);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700203 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800204 deviceInstallers.shutdownNow();
205 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700206 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700207 eventDispatcher.removeSink(FlowRuleEvent.class);
208 log.info("Stopped");
209 }
210
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700211 @Modified
212 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800213 if (context != null) {
214 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700215 }
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800216 driverProvider.init(new InternalFlowRuleProviderService(driverProvider),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100217 deviceService, mastershipService, fallbackFlowPollFrequency);
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800218 }
219
220 @Override
221 protected FlowRuleProvider defaultProvider() {
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800222 return driverProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800223 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700224
Charles Chan0c7c43b2016-01-14 17:39:20 -0800225 /**
226 * Extracts properties from the component configuration context.
227 *
228 * @param context the component context
229 */
230 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700231 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800232 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700233
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700234 flag = Tools.isPropertyEnabled(properties, ALLOW_EXTRANEOUS_RULES);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800235 if (flag == null) {
236 log.info("AllowExtraneousRules is not configured, " +
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100237 "using current value of {}", allowExtraneousRules);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800238 } else {
239 allowExtraneousRules = flag;
240 log.info("Configured. AllowExtraneousRules is {}",
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100241 allowExtraneousRules ? "enabled" : "disabled");
242 }
243
244 flag = Tools.isPropertyEnabled(properties, IMPORT_EXTRANEOUS_RULES);
245 if (flag == null) {
246 log.info("ImportExtraneousRules is not configured, " +
247 "using current value of {}", importExtraneousRules);
248 } else {
249 importExtraneousRules = flag;
250 log.info("Configured. importExtraneousRules is {}",
251 importExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700252 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800253
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700254 flag = Tools.isPropertyEnabled(properties, PURGE_ON_DISCONNECTION);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800255 if (flag == null) {
256 log.info("PurgeOnDisconnection is not configured, " +
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100257 "using current value of {}", purgeOnDisconnection);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800258 } else {
259 purgeOnDisconnection = flag;
260 log.info("Configured. PurgeOnDisconnection is {}",
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100261 purgeOnDisconnection ? "enabled" : "disabled");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800262 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800263
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700264 String s = get(properties, POLL_FREQUENCY);
Carmelo Casconee6a97542018-06-20 16:48:00 +0200265 if (isNullOrEmpty(s)) {
266 log.info("fallbackFlowPollFrequency is not configured, " +
267 "using current value of {} seconds",
268 fallbackFlowPollFrequency);
269 } else {
270 try {
271 fallbackFlowPollFrequency = Integer.parseInt(s);
272 log.info("Configured. FallbackFlowPollFrequency is {} seconds",
273 fallbackFlowPollFrequency);
274 } catch (NumberFormatException e) {
pierventre07af21d2022-03-18 10:31:04 +0100275 log.warn("Configured fallbackFlowPollFrequency value " +
Carmelo Casconee6a97542018-06-20 16:48:00 +0200276 "is not a number, using current value of {} seconds",
277 fallbackFlowPollFrequency);
278 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800279 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800280 }
281
alshabib57044ba2014-09-16 15:58:01 -0700282 @Override
tom9b4030d2014-10-06 10:39:03 -0700283 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900284 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700285 return store.getFlowRuleCount();
286 }
287
288 @Override
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800289 public int getFlowRuleCount(DeviceId deviceId) {
290 checkPermission(FLOWRULE_READ);
Thomas Vachuska227943d2018-03-19 09:37:28 -0700291 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800292 return store.getFlowRuleCount(deviceId);
293 }
294
295 @Override
Jordan Haltermanb81fdc12019-03-04 18:12:20 -0800296 public int getFlowRuleCount(DeviceId deviceId, FlowEntry.FlowEntryState state) {
297 checkPermission(FLOWRULE_READ);
298 checkNotNull(deviceId, "Device ID cannot be null");
299 return store.getFlowRuleCount(deviceId, state);
300 }
301
302 @Override
David Glantz5c7fe3a2021-09-22 14:34:14 -0500303 public FlowEntry getFlowEntry(FlowRule rule) {
304 checkPermission(FLOWRULE_READ);
305 checkNotNull(rule, FLOW_RULE_NULL);
306 return store.getFlowEntry(rule);
307 }
308
309 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700310 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900311 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800312 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700313 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700314 }
315
316 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700317 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900318 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900319
pierventre07af21d2022-03-18 10:31:04 +0100320 apply(buildFlowRuleOperations(true, null, flowRules));
alshabib57044ba2014-09-16 15:58:01 -0700321 }
322
323 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530324 public void purgeFlowRules(DeviceId deviceId) {
325 checkPermission(FLOWRULE_WRITE);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800326 checkNotNull(deviceId, DEVICE_ID_NULL);
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530327 store.purgeFlowRule(deviceId);
328 }
329
330 @Override
Daniele Morocfd77402021-07-15 17:02:59 +0200331 public void purgeFlowRules(DeviceId deviceId, ApplicationId appId) {
332 checkPermission(FLOWRULE_WRITE);
333 checkNotNull(deviceId, DEVICE_ID_NULL);
334 checkNotNull(appId, "Application ID cannot be null!");
335
336 store.purgeFlowRules(deviceId, appId);
337 }
338
339 @Override
alshabib57044ba2014-09-16 15:58:01 -0700340 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900341 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900342
pierventre07af21d2022-03-18 10:31:04 +0100343 apply(buildFlowRuleOperations(false, null, flowRules));
alshabiba68eb962014-09-24 20:34:13 -0700344 }
alshabib57044ba2014-09-16 15:58:01 -0700345
alshabiba68eb962014-09-24 20:34:13 -0700346 @Override
347 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900348 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900349
Madan Jampani6a456162014-10-24 11:36:17 -0700350 Set<FlowRule> flowEntries = Sets.newHashSet();
351 for (Device d : deviceService.getDevices()) {
352 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
353 if (flowEntry.appId() == id.id()) {
354 flowEntries.add(flowEntry);
355 }
356 }
357 }
Ray Milkey4f7e3632019-02-19 15:35:20 -0800358 removeFlowRules(Iterables.toArray(flowEntries, FlowRule.class));
alshabib57044ba2014-09-16 15:58:01 -0700359 }
360
361 @Override
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530362 public Iterable<FlowEntry> getFlowEntriesById(ApplicationId id) {
363 checkPermission(FLOWRULE_READ);
364
365 Set<FlowEntry> flowEntries = Sets.newHashSet();
366 for (Device d : deviceService.getDevices()) {
367 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
368 if (flowEntry.appId() == id.id()) {
369 flowEntries.add(flowEntry);
370 }
371 }
372 }
373 return flowEntries;
374 }
375
376 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800377 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900378 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900379
alshabibaa7e7de2014-11-12 19:20:44 -0800380 Set<FlowRule> matches = Sets.newHashSet();
381 long toLookUp = ((long) appId.id() << 16) | groupId;
382 for (Device d : deviceService.getDevices()) {
383 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
384 if ((flowEntry.id().value() >>> 32) == toLookUp) {
385 matches.add(flowEntry);
386 }
387 }
388 }
389 return matches;
390 }
391
392 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800393 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900394 checkPermission(FLOWRULE_WRITE);
pierventre55c6f332022-03-29 15:10:39 +0200395 if (ops.stripeKey().isEmpty()) {
pierventre07af21d2022-03-18 10:31:04 +0100396 // Null means that we don't care about the in-order processing
397 // this approach maximizes the throughput but it can introduce
398 // consistency issues as the original order between conflictual
399 // writes is not maintained. If conflictual writes can be easily
400 // handled using different stages, this is the approach to use.
401 operationsService.execute(new FlowOperationsProcessor(ops));
402 } else {
403 // Following approach is suggested when it is hard to handle
404 // conflictual writes in the same FlowRuleOperations object. Apps
405 // may know there are conflictual writes but it could be hard to
406 // encapsulate them in the same object using different stages (above
407 // all if they are stimulated by different events). In this case,
408 // the probabilistic accumulation may help but it is brittle and based
409 // on the probability that a given event happens in a specific time.
410 // For this reason we have introduced PredictableFlowOperationsProcessor
411 // which uses the striped key (provided by the apps) to serialize the ops
412 // on the same executor.
413 operationsService.execute(new PredictableFlowOperationsProcessor(ops));
414 }
alshabib902d41b2014-10-07 16:52:05 -0700415 }
416
417 @Override
alshabib57044ba2014-09-16 15:58:01 -0700418 protected FlowRuleProviderService createProviderService(
419 FlowRuleProvider provider) {
420 return new InternalFlowRuleProviderService(provider);
421 }
422
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800423 @Override
424 protected synchronized FlowRuleProvider getProvider(ProviderId pid) {
425 log.warn("should not be calling getProvider(ProviderId)");
426 return super.getProvider(pid);
427 }
428
429 /**
430 * {@inheritDoc}
431 * if the Device does not support {@link FlowRuleProgrammable}.
432 */
433 @Override
434 protected synchronized FlowRuleProvider getProvider(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800435 checkNotNull(deviceId, DEVICE_ID_NULL);
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800436 // if device supports FlowRuleProgrammable,
437 // use FlowRuleProgrammable via FlowRuleDriverProvider
438 return Optional.ofNullable(deviceService.getDevice(deviceId))
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100439 .filter(dev -> dev.is(FlowRuleProgrammable.class))
440 .<FlowRuleProvider>map(x -> driverProvider)
441 .orElseGet(() -> super.getProvider(deviceId));
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800442 }
443
alshabib57044ba2014-09-16 15:58:01 -0700444 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700445 extends AbstractProviderService<FlowRuleProvider>
446 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700447
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700448 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700449 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
450
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700451
alshabib57044ba2014-09-16 15:58:01 -0700452 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
453 super(provider);
454 }
455
456 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700457 public void flowRemoved(FlowEntry flowEntry) {
458 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700459 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700460 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700461 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700462 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700463 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800464 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700465 return;
466 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700467 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
468 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
469 }
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800470 FlowRuleProvider frp = getProvider(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700471 FlowRuleEvent event = null;
472 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700473 case ADDED:
474 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700475 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700476 break;
477 case PENDING_REMOVE:
478 case REMOVED:
479 event = store.removeFlowRule(stored);
480 break;
481 default:
482 break;
alshabib57044ba2014-09-16 15:58:01 -0700483
alshabiba68eb962014-09-24 20:34:13 -0700484 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700485 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700486 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700487 post(event);
488 }
alshabib57044ba2014-09-16 15:58:01 -0700489 }
490
alshabibba5ac482014-10-02 17:15:20 -0700491
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530492 private void flowMissing(FlowEntry flowRule, boolean isFlowOnlyInStore) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700493 checkNotNull(flowRule, FLOW_RULE_NULL);
494 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800495 FlowRuleProvider frp = getProvider(flowRule.deviceId());
alshabibbb42cad2014-09-25 11:43:05 -0700496 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700497 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700498 case PENDING_REMOVE:
499 case REMOVED:
500 event = store.removeFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530501 log.debug("Flow {} removed", flowRule);
tom9b4030d2014-10-06 10:39:03 -0700502 break;
503 case ADDED:
504 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800505 event = store.pendingFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530506 if (isFlowOnlyInStore) {
507 // Publishing RULE_ADD_REQUESTED event facilitates
508 // preparation of statistics for the concerned rule
509 if (event == null) {
510 event = new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADD_REQUESTED, flowRule);
511 }
512 }
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800513 try {
514 frp.applyFlowRule(flowRule);
515 } catch (UnsupportedOperationException e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700516 log.warn("Unsupported operation", e);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800517 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800518 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800519 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
520 }
521 }
tom9b4030d2014-10-06 10:39:03 -0700522 break;
523 default:
524 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700525 }
526
alshabibbb42cad2014-09-25 11:43:05 -0700527 if (event != null) {
alshabibbb42cad2014-09-25 11:43:05 -0700528 post(event);
529 }
alshabib57044ba2014-09-16 15:58:01 -0700530 }
531
alshabibba5ac482014-10-02 17:15:20 -0700532 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700533 checkNotNull(flowRule, FLOW_RULE_NULL);
534 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800535 // getProvider is customized to favor driverProvider
alshabib2374fc92014-10-22 11:03:23 -0700536 FlowRuleProvider frp = getProvider(flowRule.deviceId());
537 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700538 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700539 }
540
Andrea Campanella321f75a2021-12-14 14:48:54 +0100541 private boolean handleExistingFlow(FlowEntry flowEntry) {
alshabib1c319ff2014-10-04 20:29:09 -0700542 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700543 checkValidity();
Andrea Campanella321f75a2021-12-14 14:48:54 +0100544 FlowEntry storedEntry = store.getFlowEntry(flowEntry);
pierventrebb2a72c2022-01-04 19:08:46 +0100545 if (storedEntry != null) {
546 // Flow rule is still valid, let's try to update the stats
547 if (storedEntry.state() != FlowEntry.FlowEntryState.PENDING_REMOVE &&
548 checkRuleLiveness(flowEntry, storedEntry)) {
pierventre2ad220f2022-02-18 15:12:33 -0800549 if (!shouldHandle(flowEntry.deviceId())) {
550 return false;
551 }
pierventrebb2a72c2022-01-04 19:08:46 +0100552 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
pierventre965aa842022-03-21 19:15:40 +0100553 // Something went wrong or there is no master or the device
554 // is not available better check if it is the latter cases
pierventrebb2a72c2022-01-04 19:08:46 +0100555 if (event == null) {
556 log.debug("No flow store event generated for addOrUpdate of {}", flowEntry);
557 return false;
558 } else {
559 log.trace("Flow {} {}", flowEntry, event.type());
560 post(event);
561 }
pierventre965aa842022-03-21 19:15:40 +0100562 } else if (storedEntry.state() == FlowEntry.FlowEntryState.PENDING_REMOVE) {
563 // Store is already in sync, let's re-issue flow removal only
564 log.debug("Removing {} from the device", flowEntry);
565 FlowRuleProvider frp = getProvider(flowEntry.deviceId());
566 frp.removeFlowRule(flowEntry);
567 } else if (!checkRuleLiveness(flowEntry, storedEntry)) {
568 // Update store first as the flow entry is expired. Then,
569 // as consequence of this a flow removal will be sent.
pierventrebb2a72c2022-01-04 19:08:46 +0100570 log.debug("Removing {}", flowEntry);
571 removeFlowRules(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700572 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700573 } else {
pierventre2ad220f2022-02-18 15:12:33 -0800574 // It was already removed or there is no master
575 // better check if it is the latter
pierventrebb2a72c2022-01-04 19:08:46 +0100576 return false;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700577 }
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000578 return true;
alshabib57044ba2014-09-16 15:58:01 -0700579 }
580
alshabib1c319ff2014-10-04 20:29:09 -0700581 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
582 if (storedRule == null) {
583 return false;
584 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700585 if (storedRule.isPermanent()) {
586 return true;
587 }
588
Ray Milkey3717e602018-02-01 13:49:47 -0800589 final long timeout = storedRule.timeout() * 1000L;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700590 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700591
592 // Checking flow with hardTimeout
593 if (storedRule.hardTimeout() != 0) {
594 if (!firstSeen.containsKey(storedRule)) {
595 // First time rule adding
596 firstSeen.put(storedRule, currentTime);
597 } else {
598 Long first = firstSeen.get(storedRule);
Ray Milkey3717e602018-02-01 13:49:47 -0800599 final long hardTimeout = storedRule.hardTimeout() * 1000L;
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700600 if ((currentTime - first) > hardTimeout) {
601 return false;
602 }
603 }
604 }
605
Gamze Abaka8d03f182017-07-20 15:09:24 +0000606 if (storedRule.packets() != swRule.packets() || storedRule.bytes() != swRule.bytes()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700607 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700608 return true;
609 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700610 if (!lastSeen.containsKey(storedRule)) {
611 // checking for the first time
612 lastSeen.put(storedRule, storedRule.lastSeen());
613 // Use following if lastSeen attr. was removed.
614 //lastSeen.put(storedRule, currentTime);
615 }
616 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700617
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800618 // concurrently removed? let the liveness check fail
619 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700620 }
621
alshabib5c370ff2014-09-18 10:12:14 -0700622 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700623 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900624 pushFlowMetricsInternal(deviceId, flowEntries, true);
625 }
626
627 @Override
628 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
629 pushFlowMetricsInternal(deviceId, flowEntries, false);
630 }
631
pierventre2ad220f2022-02-18 15:12:33 -0800632 private boolean shouldHandle(DeviceId deviceId) {
633 NodeId master = mastershipService.getMasterFor(deviceId);
634 return Objects.equals(local, master) && deviceService.isAvailable(deviceId);
635 }
636
ssyoon9030fbcd92015-08-17 10:42:07 +0900637 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
638 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700639 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
640 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000641 NodeId master;
642 boolean done;
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700643
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000644 // Processing flow rules
Saurav Dasfa2fa932015-03-03 11:29:48 -0800645 for (FlowEntry rule : flowEntries) {
646 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700647 FlowEntry storedRule = storedRules.remove(rule);
648 if (storedRule != null) {
649 if (storedRule.exactMatch(rule)) {
650 // we both have the rule, let's update some info then.
Andrea Campanella321f75a2021-12-14 14:48:54 +0100651 done = handleExistingFlow(rule);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000652 if (!done) {
653 // Mastership change can occur during this iteration
pierventre2ad220f2022-02-18 15:12:33 -0800654 if (!shouldHandle(deviceId)) {
655 log.warn("Tried to update the flow stats while the node was not the master" +
656 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000657 return;
658 }
659 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700660 } else {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000661 // Mastership change can occur during this iteration
pierventre2ad220f2022-02-18 15:12:33 -0800662 if (!shouldHandle(deviceId)) {
663 log.warn("Tried to update the flows while the node was not the master" +
664 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000665 return;
666 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700667 // the two rules are not an exact match - remove the
668 // switch's rule and install our rule
669 extraneousFlow(rule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530670 flowMissing(storedRule, false);
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700671 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800672 } else {
673 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700674 if (!allowExtraneousRules) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000675 // Mastership change can occur during this iteration
pierventre2ad220f2022-02-18 15:12:33 -0800676 if (!shouldHandle(deviceId)) {
677 log.warn("Tried to remove flows while the node was not the master" +
678 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000679 return;
680 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700681 extraneousFlow(rule);
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100682 } else if (importExtraneousRules) { // Stores the rule, if so is indicated
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000683 FlowRuleEvent flowRuleEvent = store.addOrUpdateFlowRule(rule);
684 if (flowRuleEvent == null) {
685 // Mastership change can occur during this iteration
pierventre2ad220f2022-02-18 15:12:33 -0800686 if (!shouldHandle(deviceId)) {
687 log.warn("Tried to import flows while the node was not the master" +
688 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000689 return;
690 }
691 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700692 }
alshabib93cb57f2015-02-12 17:43:26 -0800693 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700694 } catch (Exception e) {
Jon Hall274cecb2017-08-09 12:15:48 -0700695 log.warn("Can't process added or extra rule {} for device {}:{}",
696 rule, deviceId, e);
alshabib93cb57f2015-02-12 17:43:26 -0800697 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800698 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900699
700 // DO NOT reinstall
701 if (useMissingFlow) {
702 for (FlowEntry rule : storedRules.keySet()) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000703 // Mastership change can occur during this iteration
pierventre2ad220f2022-02-18 15:12:33 -0800704 if (!shouldHandle(deviceId)) {
705 log.warn("Tried to install missing rules while the node was not the master" +
706 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000707 return;
708 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900709 try {
710 // there are rules in the store that aren't on the switch
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530711 log.debug("Adding the rule that is present in store but not on switch : {}", rule);
712 flowMissing(rule, true);
ssyoon9030fbcd92015-08-17 10:42:07 +0900713 } catch (Exception e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700714 log.warn("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900715 }
alshabib93cb57f2015-02-12 17:43:26 -0800716 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800717 }
alshabib5c370ff2014-09-18 10:12:14 -0700718 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800719
720 @Override
721 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
722 store.batchOperationComplete(FlowRuleBatchEvent.completed(
723 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
724 operation
725 ));
726 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700727
728 @Override
729 public void pushTableStatistics(DeviceId deviceId,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100730 List<TableStatisticsEntry> tableStats) {
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700731 store.updateTableStatistics(deviceId, tableStats);
732 }
alshabib57044ba2014-09-16 15:58:01 -0700733 }
734
tomc78acee2014-09-24 15:16:55 -0700735 // Store delegate to re-post events emitted from the store.
736 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800737
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800738
Madan Jampani117aaae2014-10-23 10:04:05 -0700739 // TODO: Right now we only dispatch events at individual flowEntry level.
740 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700741 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700742 public void notify(FlowRuleBatchEvent event) {
743 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700744 switch (event.type()) {
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100745 case BATCH_OPERATION_REQUESTED:
746 // Request has been forwarded to MASTER Node, and was
747 request.ops().forEach(
748 op -> {
749 switch (op.operator()) {
750 case ADD:
751 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
752 break;
753 case REMOVE:
754 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
755 break;
756 case MODIFY:
757 //TODO: do something here when the time comes.
758 break;
759 default:
760 log.warn("Unknown flow operation operator: {}", op.operator());
761 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800762 }
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100763 );
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800764
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100765 DeviceId deviceId = event.deviceId();
766 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
767 // getProvider is customized to favor driverProvider
768 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
769 if (flowRuleProvider != null) {
770 log.trace("Sending {} flow rules to {}", batchOperation.size(), deviceId);
771 flowRuleProvider.executeBatch(batchOperation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800772 }
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800773
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100774 break;
775
776 case BATCH_OPERATION_COMPLETED:
777 // Operation completed, let's retrieve the processor and trigger the callback
778 FlowOperationsProcessor fops = pendingFlowOperations.remove(
779 event.subject().batchId());
780 if (fops != null) {
781 if (event.result().isSuccess()) {
782 fops.satisfy(event.deviceId());
783 } else {
784 fops.fail(event.deviceId(), event.result().failedItems());
785 }
786 } else {
787 log.warn("Unable to find flow operations processor for batch: {}", event.subject().batchId());
788 }
789 break;
790
791 default:
792 break;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700793 }
tomc78acee2014-09-24 15:16:55 -0700794 }
795 }
alshabib902d41b2014-10-07 16:52:05 -0700796
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700797 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
798 switch (input) {
799 case ADD:
800 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
801 case MODIFY:
802 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
803 case REMOVE:
804 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
805 default:
806 throw new UnsupportedOperationException("Unknown flow rule type " + input);
807 }
808 }
809
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800810 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700811 // Immutable
pierventre07af21d2022-03-18 10:31:04 +0100812 protected final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700813
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700814 // Mutable
pierventre07af21d2022-03-18 10:31:04 +0100815 protected final List<Set<FlowRuleOperation>> stages;
816 protected final Set<DeviceId> pendingDevices = new HashSet<>();
817 protected boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700818
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700819 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800820 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800821 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700822 }
823
824 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700825 public synchronized void run() {
Jon Hallcbd1b392017-01-18 20:15:44 -0800826 if (!stages.isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800827 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700828 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700829 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700830 }
831 }
832
pierventre07af21d2022-03-18 10:31:04 +0100833 protected void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700834 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800835
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700836 for (FlowRuleOperation op : ops) {
837 perDeviceBatches.put(op.rule().deviceId(),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100838 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800839 }
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000840 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800841
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800842 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700843 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800844 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100845 deviceId, id);
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000846 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700847 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700848 }
849 }
850
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700851 synchronized void satisfy(DeviceId devId) {
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000852 pendingDevices.remove(devId);
853 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700854 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700855 }
alshabib193525b2014-10-08 18:58:03 -0700856 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800857
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700858 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZUb9e0ab72016-09-14 16:54:13 -0700859 hasFailed = true;
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000860 pendingDevices.remove(devId);
861 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700862 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800863 }
864
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700865 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
866 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800867
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700868 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800869 }
alshabib902d41b2014-10-07 16:52:05 -0700870 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700871
pierventre07af21d2022-03-18 10:31:04 +0100872 // Provides in-order processing in the local instance. The main difference with its
873 // ancestor is that the runnable ends when all the stages have been processed. Instead,
874 // its ancestor ends as soon as one stage has been processed and cannot guarantee in-order
875 // processing between subsequent stages and a new FlowRuleOperation (having the same key).
876 private class PredictableFlowOperationsProcessor extends FlowOperationsProcessor implements PickyRunnable {
877
878 private static final int WAIT_TIMEOUT = 5000;
879 private static final int WAIT_ATTEMPTS = 3;
880
881 PredictableFlowOperationsProcessor(FlowRuleOperations ops) {
882 super(ops);
883 }
884
885 @Override
886 public void run() {
887 try {
888 while (!stages.isEmpty()) {
889 process(stages.remove(0));
890 synchronized (this) {
891 // Batch in flights - let's wait
892 int attempts = 0;
893 while (!pendingDevices.isEmpty() && attempts < WAIT_ATTEMPTS) {
894 this.wait(WAIT_TIMEOUT);
895 attempts++;
896 }
897 // Something wrong, we cannot block all the pipeline
898 if (attempts == WAIT_ATTEMPTS) {
899 break;
900 }
901 }
902 }
903 } catch (InterruptedException e) {
904 // Interrupted case
905 if (log.isTraceEnabled()) {
906 log.trace("Interrupted while waiting for {} stages to be completed",
907 stages.size());
908 }
909 }
910
911 synchronized (this) {
912 if (stages.isEmpty() && !hasFailed && pendingDevices.isEmpty()) {
913 // No error and it is done, signal success to the apps
914 fops.callback().onSuccess(fops);
915 } else {
916 // It was interrupted or there is a failure - signal error.
917 // This may introduce a duplicate error in some cases but
918 // better than nothing and keeping the apps blocked forever.
919 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
920 if (!stages.isEmpty()) {
921 stages.remove(0).forEach(flowRuleOperation -> failedOpsBuilder.add(
922 flowRuleOperation.rule()));
923 }
924 fops.callback().onError(failedOpsBuilder.build());
925 }
926 }
927 }
928
929 @Override
930 synchronized void satisfy(DeviceId devId) {
931 pendingDevices.remove(devId);
932 if (pendingDevices.isEmpty()) {
933 this.notifyAll();
934 }
935 }
936
937 @Override
938 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
939 hasFailed = true;
940 pendingDevices.remove(devId);
941 if (pendingDevices.isEmpty()) {
942 this.notifyAll();
943 }
944
945 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
946 failures.forEach(failedOpsBuilder::add);
947
948 fops.callback().onError(failedOpsBuilder.build());
949 }
950
951 @Override
952 public int hint() {
pierventre55c6f332022-03-29 15:10:39 +0200953 return fops.stripeKey().orElse(randomGenerator.nextInt());
pierventre07af21d2022-03-18 10:31:04 +0100954 }
955 }
956
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700957 @Override
958 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
959 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800960 checkNotNull(deviceId, DEVICE_ID_NULL);
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700961 return store.getTableStatistics(deviceId);
962 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800963
Patryk Konopka7e40c012017-06-06 13:38:06 +0200964 @Override
965 public long getActiveFlowRuleCount(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800966 checkNotNull(deviceId, DEVICE_ID_NULL);
Patryk Konopka7e40c012017-06-06 13:38:06 +0200967 return store.getActiveFlowRuleCount(deviceId);
968 }
969
pierventre07af21d2022-03-18 10:31:04 +0100970 @Override
971 public void applyFlowRules(int key, FlowRule... flowRules) {
972 checkPermission(FLOWRULE_WRITE);
973
974 apply(buildFlowRuleOperations(true, key, flowRules));
975 }
976
977 @Override
978 public void removeFlowRules(int key, FlowRule... flowRules) {
979 checkPermission(FLOWRULE_WRITE);
980
981 apply(buildFlowRuleOperations(false, key, flowRules));
982 }
983
984 private FlowRuleOperations buildFlowRuleOperations(boolean add, Integer key, FlowRule... flowRules) {
985 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
986 for (FlowRule flowRule : flowRules) {
987 if (add) {
988 builder.add(flowRule);
989 } else {
990 builder.remove(flowRule);
991 }
992 }
993 if (key != null) {
994 builder.striped(key);
995 }
996 return builder.build();
997 }
998
Charles Chan0c7c43b2016-01-14 17:39:20 -0800999 private class InternalDeviceListener implements DeviceListener {
1000 @Override
1001 public void event(DeviceEvent event) {
1002 switch (event.type()) {
1003 case DEVICE_REMOVED:
1004 case DEVICE_AVAILABILITY_CHANGED:
1005 DeviceId deviceId = event.subject().id();
1006 if (!deviceService.isAvailable(deviceId)) {
Andrea Campanella32a9c0b2020-03-27 12:53:46 +01001007 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
pierventre07af21d2022-03-18 10:31:04 +01001008 // if purgeOnDisconnection is set for the device or it's a global configuration
Andrea Campanella32a9c0b2020-03-27 12:53:46 +01001009 // lets remove the flows. Priority is given to the per device flag
1010 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
1011 cfg.purgeOnDisconnection() : purgeOnDisconnection;
1012 if (purge) {
1013 log.info("PurgeOnDisconnection is requested for device {}, " +
1014 "removing flows", deviceId);
Charles Chan0c7c43b2016-01-14 17:39:20 -08001015 store.purgeFlowRule(deviceId);
1016 }
1017 }
1018 break;
1019 default:
1020 break;
1021 }
1022 }
1023 }
alshabib57044ba2014-09-16 15:58:01 -07001024}