blob: 9dc92d157762e868ef62a6a299e114a1ca0ed384 [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;
Jian Lid9b5f552016-03-11 18:15:31 -080024import org.onlab.util.Tools;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070025import org.onosproject.cfg.ComponentConfigService;
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +000026import org.onosproject.cluster.ClusterService;
27import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080028import org.onosproject.core.ApplicationId;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080029import org.onosproject.core.CoreService;
30import org.onosproject.core.IdGenerator;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080031import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080032import org.onosproject.net.Device;
33import org.onosproject.net.DeviceId;
Andrea Campanella32a9c0b2020-03-27 12:53:46 +010034import org.onosproject.net.config.NetworkConfigRegistry;
35import org.onosproject.net.config.basics.BasicDeviceConfig;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080036import org.onosproject.net.device.DeviceEvent;
37import org.onosproject.net.device.DeviceListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.device.DeviceService;
Jordan Halterman4f3193a2017-07-11 20:32:49 -070039import org.onosproject.net.driver.DriverService;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.flow.CompletedBatchOperation;
Charles M.C. Chan1229eca2015-05-18 06:27:52 +080041import org.onosproject.net.flow.DefaultFlowEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.flow.FlowEntry;
43import org.onosproject.net.flow.FlowRule;
Brian O'Connorabafb502014-12-02 22:26:20 -080044import org.onosproject.net.flow.FlowRuleEvent;
45import org.onosproject.net.flow.FlowRuleListener;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080046import org.onosproject.net.flow.FlowRuleOperation;
47import org.onosproject.net.flow.FlowRuleOperations;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080048import org.onosproject.net.flow.FlowRuleProgrammable;
Brian O'Connorabafb502014-12-02 22:26:20 -080049import org.onosproject.net.flow.FlowRuleProvider;
50import org.onosproject.net.flow.FlowRuleProviderRegistry;
51import org.onosproject.net.flow.FlowRuleProviderService;
52import org.onosproject.net.flow.FlowRuleService;
53import org.onosproject.net.flow.FlowRuleStore;
54import org.onosproject.net.flow.FlowRuleStoreDelegate;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070055import org.onosproject.net.flow.TableStatisticsEntry;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070056import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry;
57import org.onosproject.net.flow.oldbatch.FlowRuleBatchEvent;
58import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation;
59import org.onosproject.net.flow.oldbatch.FlowRuleBatchRequest;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080060import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080061import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080062import org.onosproject.net.provider.ProviderId;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070063import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070064import org.osgi.service.component.annotations.Activate;
65import org.osgi.service.component.annotations.Component;
66import org.osgi.service.component.annotations.Deactivate;
67import org.osgi.service.component.annotations.Modified;
68import org.osgi.service.component.annotations.Reference;
69import org.osgi.service.component.annotations.ReferenceCardinality;
alshabib57044ba2014-09-16 15:58:01 -070070import org.slf4j.Logger;
71
Brian O'Connord12267c2015-02-17 18:17:08 -080072import java.util.Collections;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070073import java.util.Dictionary;
Sho SHIMIZUb837cb72016-08-30 14:44:50 -070074import java.util.HashSet;
Brian O'Connord12267c2015-02-17 18:17:08 -080075import java.util.List;
76import java.util.Map;
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +000077import java.util.Objects;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080078import java.util.Optional;
Brian O'Connord12267c2015-02-17 18:17:08 -080079import java.util.Set;
80import java.util.concurrent.ConcurrentHashMap;
81import java.util.concurrent.ExecutorService;
82import java.util.concurrent.Executors;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080083
Thomas Vachuska9b2da212014-11-10 19:30:25 -080084import static com.google.common.base.Preconditions.checkNotNull;
Charles Chan0c7c43b2016-01-14 17:39:20 -080085import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080086import static org.onlab.util.Tools.get;
Brian O'Connord12267c2015-02-17 18:17:08 -080087import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070088import static org.onosproject.net.OsgiPropertyConstants.ALLOW_EXTRANEOUS_RULES;
89import static org.onosproject.net.OsgiPropertyConstants.ALLOW_EXTRANEOUS_RULES_DEFAULT;
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +010090import static org.onosproject.net.OsgiPropertyConstants.IMPORT_EXTRANEOUS_RULES;
91import static org.onosproject.net.OsgiPropertyConstants.IMPORT_EXTRANEOUS_RULES_DEFAULT;
Ray Milkeyd04e2272018-10-16 18:20:18 -070092import static org.onosproject.net.OsgiPropertyConstants.POLL_FREQUENCY;
93import static org.onosproject.net.OsgiPropertyConstants.POLL_FREQUENCY_DEFAULT;
94import static org.onosproject.net.OsgiPropertyConstants.PURGE_ON_DISCONNECTION;
95import static org.onosproject.net.OsgiPropertyConstants.PURGE_ON_DISCONNECTION_DEFAULT;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070096import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_ADD_REQUESTED;
97import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVE_REQUESTED;
Changhoon Yoon541ef712015-05-23 17:18:34 +090098import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080099import static org.onosproject.security.AppPermission.Type.FLOWRULE_READ;
100import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700101import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +0900102
tome4729872014-09-23 00:37:37 -0700103/**
104 * Provides implementation of the flow NB & SB APIs.
105 */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700106@Component(
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100107 immediate = true,
108 service = {
109 FlowRuleService.class,
110 FlowRuleProviderRegistry.class
111 },
112 property = {
113 ALLOW_EXTRANEOUS_RULES + ":Boolean=" + ALLOW_EXTRANEOUS_RULES_DEFAULT,
114 IMPORT_EXTRANEOUS_RULES + ":Boolean=" + IMPORT_EXTRANEOUS_RULES_DEFAULT,
115 PURGE_ON_DISCONNECTION + ":Boolean=" + PURGE_ON_DISCONNECTION_DEFAULT,
116 POLL_FREQUENCY + ":Integer=" + POLL_FREQUENCY_DEFAULT
117 }
Ray Milkeyd04e2272018-10-16 18:20:18 -0700118)
tom202175a2014-09-19 19:00:11 -0700119public class FlowRuleManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700120 extends AbstractListenerProviderRegistry<FlowRuleEvent, FlowRuleListener,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100121 FlowRuleProvider, FlowRuleProviderService>
tom9b4030d2014-10-06 10:39:03 -0700122 implements FlowRuleService, FlowRuleProviderRegistry {
alshabib57044ba2014-09-16 15:58:01 -0700123
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800124 private final Logger log = getLogger(getClass());
125
Thomas Vachuska227943d2018-03-19 09:37:28 -0700126 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
127 private static final String FLOW_RULE_NULL = "FlowRule cannot be null";
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700128
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700129 /** Allow flow rules in switch not installed by ONOS. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700130 private boolean allowExtraneousRules = ALLOW_EXTRANEOUS_RULES_DEFAULT;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700131
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100132 /** Allow to import flow rules in switch not installed by ONOS. */
133 private boolean importExtraneousRules = IMPORT_EXTRANEOUS_RULES_DEFAULT;
134
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700135 /** Purge entries associated with a device when the device goes offline. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700136 private boolean purgeOnDisconnection = PURGE_ON_DISCONNECTION_DEFAULT;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800137
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700138 /** Frequency (in seconds) for polling flow statistics via fallback provider. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700139 private int fallbackFlowPollFrequency = POLL_FREQUENCY_DEFAULT;
alshabib57044ba2014-09-16 15:58:01 -0700140
alshabibbb42cad2014-09-25 11:43:05 -0700141 private final FlowRuleStoreDelegate delegate = new InternalStoreDelegate();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800142 private final DeviceListener deviceListener = new InternalDeviceListener();
tomc78acee2014-09-24 15:16:55 -0700143
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800144 private final FlowRuleDriverProvider driverProvider = new FlowRuleDriverProvider();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800145
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800146 protected ExecutorService deviceInstallers =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800147 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "device-installer-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800148
149 protected ExecutorService operationsService =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700150 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "operations-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800151
152 private IdGenerator idGenerator;
153
Sho SHIMIZU9f950742016-09-01 09:55:38 -0700154 private final Map<Long, FlowOperationsProcessor> pendingFlowOperations = new ConcurrentHashMap<>();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700155
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000156 private NodeId local;
157
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tombe988312014-09-19 18:38:47 -0700159 protected FlowRuleStore store;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700160
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700161 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibeb55524f2014-09-18 09:59:24 -0700162 protected DeviceService deviceService;
alshabib57044ba2014-09-16 15:58:01 -0700163
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800165 protected CoreService coreService;
166
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700167 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800168 protected MastershipService mastershipService;
169
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700170 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700171 protected ComponentConfigService cfgService;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800172
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700173 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman4f3193a2017-07-11 20:32:49 -0700174 protected DriverService driverService;
175
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000176 @Reference(cardinality = ReferenceCardinality.MANDATORY)
177 protected ClusterService clusterService;
178
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100179 @Reference(cardinality = ReferenceCardinality.MANDATORY)
180 protected NetworkConfigRegistry netCfgService;
181
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700182 @Activate
183 public void activate(ComponentContext context) {
tomc78acee2014-09-24 15:16:55 -0700184 store.setDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700185 eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800186 deviceService.addListener(deviceListener);
187 cfgService.registerProperties(getClass());
piered2a0a42019-04-16 11:48:08 +0200188 modified(context);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800189 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000190 local = clusterService.getLocalNode().id();
alshabib57044ba2014-09-16 15:58:01 -0700191 log.info("Started");
192 }
193
194 @Deactivate
195 public void deactivate() {
Andrea Campanella5a3c09c2017-12-01 13:57:48 +0100196 driverProvider.terminate();
Andrea Campanella3f1c61e2016-04-01 17:30:12 -0700197 deviceService.removeListener(deviceListener);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700198 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800199 deviceInstallers.shutdownNow();
200 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700201 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700202 eventDispatcher.removeSink(FlowRuleEvent.class);
203 log.info("Stopped");
204 }
205
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700206 @Modified
207 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800208 if (context != null) {
209 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700210 }
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800211 driverProvider.init(new InternalFlowRuleProviderService(driverProvider),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100212 deviceService, mastershipService, fallbackFlowPollFrequency);
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800213 }
214
215 @Override
216 protected FlowRuleProvider defaultProvider() {
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800217 return driverProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800218 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700219
Charles Chan0c7c43b2016-01-14 17:39:20 -0800220 /**
221 * Extracts properties from the component configuration context.
222 *
223 * @param context the component context
224 */
225 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700226 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800227 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700228
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700229 flag = Tools.isPropertyEnabled(properties, ALLOW_EXTRANEOUS_RULES);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800230 if (flag == null) {
231 log.info("AllowExtraneousRules is not configured, " +
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100232 "using current value of {}", allowExtraneousRules);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800233 } else {
234 allowExtraneousRules = flag;
235 log.info("Configured. AllowExtraneousRules is {}",
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100236 allowExtraneousRules ? "enabled" : "disabled");
237 }
238
239 flag = Tools.isPropertyEnabled(properties, IMPORT_EXTRANEOUS_RULES);
240 if (flag == null) {
241 log.info("ImportExtraneousRules is not configured, " +
242 "using current value of {}", importExtraneousRules);
243 } else {
244 importExtraneousRules = flag;
245 log.info("Configured. importExtraneousRules is {}",
246 importExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700247 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800248
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700249 flag = Tools.isPropertyEnabled(properties, PURGE_ON_DISCONNECTION);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800250 if (flag == null) {
251 log.info("PurgeOnDisconnection is not configured, " +
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100252 "using current value of {}", purgeOnDisconnection);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800253 } else {
254 purgeOnDisconnection = flag;
255 log.info("Configured. PurgeOnDisconnection is {}",
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100256 purgeOnDisconnection ? "enabled" : "disabled");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800257 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800258
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700259 String s = get(properties, POLL_FREQUENCY);
Carmelo Casconee6a97542018-06-20 16:48:00 +0200260 if (isNullOrEmpty(s)) {
261 log.info("fallbackFlowPollFrequency is not configured, " +
262 "using current value of {} seconds",
263 fallbackFlowPollFrequency);
264 } else {
265 try {
266 fallbackFlowPollFrequency = Integer.parseInt(s);
267 log.info("Configured. FallbackFlowPollFrequency is {} seconds",
268 fallbackFlowPollFrequency);
269 } catch (NumberFormatException e) {
270 log.warn("Configured fallbackFlowPollFrequency value '{}' " +
271 "is not a number, using current value of {} seconds",
272 fallbackFlowPollFrequency);
273 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800274 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800275 }
276
alshabib57044ba2014-09-16 15:58:01 -0700277 @Override
tom9b4030d2014-10-06 10:39:03 -0700278 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900279 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700280 return store.getFlowRuleCount();
281 }
282
283 @Override
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800284 public int getFlowRuleCount(DeviceId deviceId) {
285 checkPermission(FLOWRULE_READ);
Thomas Vachuska227943d2018-03-19 09:37:28 -0700286 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800287 return store.getFlowRuleCount(deviceId);
288 }
289
290 @Override
Jordan Haltermanb81fdc12019-03-04 18:12:20 -0800291 public int getFlowRuleCount(DeviceId deviceId, FlowEntry.FlowEntryState state) {
292 checkPermission(FLOWRULE_READ);
293 checkNotNull(deviceId, "Device ID cannot be null");
294 return store.getFlowRuleCount(deviceId, state);
295 }
296
297 @Override
David Glantz0a5779c2021-09-22 14:34:14 -0500298 public FlowEntry getFlowEntry(FlowRule rule) {
299 checkPermission(FLOWRULE_READ);
300 checkNotNull(rule, FLOW_RULE_NULL);
301 return store.getFlowEntry(rule);
302 }
303
304 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700305 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900306 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800307 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700308 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700309 }
310
311 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700312 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900313 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900314
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800315 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800316 for (FlowRule flowRule : flowRules) {
317 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700318 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800319 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700320 }
321
322 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530323 public void purgeFlowRules(DeviceId deviceId) {
324 checkPermission(FLOWRULE_WRITE);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800325 checkNotNull(deviceId, DEVICE_ID_NULL);
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530326 store.purgeFlowRule(deviceId);
327 }
328
329 @Override
Daniele Moro43ac2892021-07-15 17:02:59 +0200330 public void purgeFlowRules(DeviceId deviceId, ApplicationId appId) {
331 checkPermission(FLOWRULE_WRITE);
332 checkNotNull(deviceId, DEVICE_ID_NULL);
333 checkNotNull(appId, "Application ID cannot be null!");
334
335 store.purgeFlowRules(deviceId, appId);
336 }
337
338 @Override
alshabib57044ba2014-09-16 15:58:01 -0700339 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900340 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900341
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800342 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800343 for (FlowRule flowRule : flowRules) {
344 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700345 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800346 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700347 }
alshabib57044ba2014-09-16 15:58:01 -0700348
alshabiba68eb962014-09-24 20:34:13 -0700349 @Override
350 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900351 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900352
Madan Jampani6a456162014-10-24 11:36:17 -0700353 Set<FlowRule> flowEntries = Sets.newHashSet();
354 for (Device d : deviceService.getDevices()) {
355 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
356 if (flowEntry.appId() == id.id()) {
357 flowEntries.add(flowEntry);
358 }
359 }
360 }
Ray Milkey4f7e3632019-02-19 15:35:20 -0800361 removeFlowRules(Iterables.toArray(flowEntries, FlowRule.class));
alshabib57044ba2014-09-16 15:58:01 -0700362 }
363
364 @Override
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530365 public Iterable<FlowEntry> getFlowEntriesById(ApplicationId id) {
366 checkPermission(FLOWRULE_READ);
367
368 Set<FlowEntry> flowEntries = Sets.newHashSet();
369 for (Device d : deviceService.getDevices()) {
370 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
371 if (flowEntry.appId() == id.id()) {
372 flowEntries.add(flowEntry);
373 }
374 }
375 }
376 return flowEntries;
377 }
378
379 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800380 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900381 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900382
alshabibaa7e7de2014-11-12 19:20:44 -0800383 Set<FlowRule> matches = Sets.newHashSet();
384 long toLookUp = ((long) appId.id() << 16) | groupId;
385 for (Device d : deviceService.getDevices()) {
386 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
387 if ((flowEntry.id().value() >>> 32) == toLookUp) {
388 matches.add(flowEntry);
389 }
390 }
391 }
392 return matches;
393 }
394
395 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800396 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900397 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700398 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700399 }
400
401 @Override
alshabib57044ba2014-09-16 15:58:01 -0700402 protected FlowRuleProviderService createProviderService(
403 FlowRuleProvider provider) {
404 return new InternalFlowRuleProviderService(provider);
405 }
406
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800407 @Override
408 protected synchronized FlowRuleProvider getProvider(ProviderId pid) {
409 log.warn("should not be calling getProvider(ProviderId)");
410 return super.getProvider(pid);
411 }
412
413 /**
414 * {@inheritDoc}
415 * if the Device does not support {@link FlowRuleProgrammable}.
416 */
417 @Override
418 protected synchronized FlowRuleProvider getProvider(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800419 checkNotNull(deviceId, DEVICE_ID_NULL);
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800420 // if device supports FlowRuleProgrammable,
421 // use FlowRuleProgrammable via FlowRuleDriverProvider
422 return Optional.ofNullable(deviceService.getDevice(deviceId))
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100423 .filter(dev -> dev.is(FlowRuleProgrammable.class))
424 .<FlowRuleProvider>map(x -> driverProvider)
425 .orElseGet(() -> super.getProvider(deviceId));
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800426 }
427
alshabib57044ba2014-09-16 15:58:01 -0700428 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700429 extends AbstractProviderService<FlowRuleProvider>
430 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700431
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700432 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700433 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
434
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700435
alshabib57044ba2014-09-16 15:58:01 -0700436 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
437 super(provider);
438 }
439
440 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700441 public void flowRemoved(FlowEntry flowEntry) {
442 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700443 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700444 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700445 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700446 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700447 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800448 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700449 return;
450 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700451 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
452 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
453 }
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800454 FlowRuleProvider frp = getProvider(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700455 FlowRuleEvent event = null;
456 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700457 case ADDED:
458 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700459 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700460 break;
461 case PENDING_REMOVE:
462 case REMOVED:
463 event = store.removeFlowRule(stored);
464 break;
465 default:
466 break;
alshabib57044ba2014-09-16 15:58:01 -0700467
alshabiba68eb962014-09-24 20:34:13 -0700468 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700469 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700470 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700471 post(event);
472 }
alshabib57044ba2014-09-16 15:58:01 -0700473 }
474
alshabibba5ac482014-10-02 17:15:20 -0700475
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530476 private void flowMissing(FlowEntry flowRule, boolean isFlowOnlyInStore) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700477 checkNotNull(flowRule, FLOW_RULE_NULL);
478 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800479 FlowRuleProvider frp = getProvider(flowRule.deviceId());
alshabibbb42cad2014-09-25 11:43:05 -0700480 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700481 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700482 case PENDING_REMOVE:
483 case REMOVED:
484 event = store.removeFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530485 log.debug("Flow {} removed", flowRule);
tom9b4030d2014-10-06 10:39:03 -0700486 break;
487 case ADDED:
488 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800489 event = store.pendingFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530490 if (isFlowOnlyInStore) {
491 // Publishing RULE_ADD_REQUESTED event facilitates
492 // preparation of statistics for the concerned rule
493 if (event == null) {
494 event = new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADD_REQUESTED, flowRule);
495 }
496 }
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800497 try {
498 frp.applyFlowRule(flowRule);
499 } catch (UnsupportedOperationException e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700500 log.warn("Unsupported operation", e);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800501 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800502 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800503 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
504 }
505 }
tom9b4030d2014-10-06 10:39:03 -0700506 break;
507 default:
508 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700509 }
510
alshabibbb42cad2014-09-25 11:43:05 -0700511 if (event != null) {
alshabibbb42cad2014-09-25 11:43:05 -0700512 post(event);
513 }
alshabib57044ba2014-09-16 15:58:01 -0700514 }
515
alshabibba5ac482014-10-02 17:15:20 -0700516 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700517 checkNotNull(flowRule, FLOW_RULE_NULL);
518 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800519 // getProvider is customized to favor driverProvider
alshabib2374fc92014-10-22 11:03:23 -0700520 FlowRuleProvider frp = getProvider(flowRule.deviceId());
521 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700522 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700523 }
524
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000525 private boolean flowAdded(FlowEntry flowEntry) {
alshabib1c319ff2014-10-04 20:29:09 -0700526 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700527 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700528
alshabib1c319ff2014-10-04 20:29:09 -0700529 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700530 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700531 if (event == null) {
532 log.debug("No flow store event generated.");
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000533 return false;
alshabibba5ac482014-10-02 17:15:20 -0700534 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800535 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700536 post(event);
537 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700538 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800539 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700540 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700541 }
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000542 return true;
alshabib57044ba2014-09-16 15:58:01 -0700543 }
544
alshabib1c319ff2014-10-04 20:29:09 -0700545 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
546 if (storedRule == null) {
547 return false;
548 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700549 if (storedRule.isPermanent()) {
550 return true;
551 }
552
Ray Milkey3717e602018-02-01 13:49:47 -0800553 final long timeout = storedRule.timeout() * 1000L;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700554 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700555
556 // Checking flow with hardTimeout
557 if (storedRule.hardTimeout() != 0) {
558 if (!firstSeen.containsKey(storedRule)) {
559 // First time rule adding
560 firstSeen.put(storedRule, currentTime);
561 } else {
562 Long first = firstSeen.get(storedRule);
Ray Milkey3717e602018-02-01 13:49:47 -0800563 final long hardTimeout = storedRule.hardTimeout() * 1000L;
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700564 if ((currentTime - first) > hardTimeout) {
565 return false;
566 }
567 }
568 }
569
Gamze Abaka8d03f182017-07-20 15:09:24 +0000570 if (storedRule.packets() != swRule.packets() || storedRule.bytes() != swRule.bytes()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700571 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700572 return true;
573 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700574 if (!lastSeen.containsKey(storedRule)) {
575 // checking for the first time
576 lastSeen.put(storedRule, storedRule.lastSeen());
577 // Use following if lastSeen attr. was removed.
578 //lastSeen.put(storedRule, currentTime);
579 }
580 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700581
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800582 // concurrently removed? let the liveness check fail
583 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700584 }
585
alshabib5c370ff2014-09-18 10:12:14 -0700586 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700587 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900588 pushFlowMetricsInternal(deviceId, flowEntries, true);
589 }
590
591 @Override
592 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
593 pushFlowMetricsInternal(deviceId, flowEntries, false);
594 }
595
596 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
597 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700598 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
599 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000600 NodeId master;
601 boolean done;
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700602
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000603 // Processing flow rules
Saurav Dasfa2fa932015-03-03 11:29:48 -0800604 for (FlowEntry rule : flowEntries) {
605 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700606 FlowEntry storedRule = storedRules.remove(rule);
607 if (storedRule != null) {
608 if (storedRule.exactMatch(rule)) {
609 // we both have the rule, let's update some info then.
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000610 done = flowAdded(rule);
611 if (!done) {
612 // Mastership change can occur during this iteration
613 master = mastershipService.getMasterFor(deviceId);
614 if (!Objects.equals(local, master)) {
615 log.warn("Tried to update the flow stats while the node was not the master");
616 return;
617 }
618 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700619 } else {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000620 // Mastership change can occur during this iteration
621 master = mastershipService.getMasterFor(deviceId);
622 if (!Objects.equals(local, master)) {
623 log.warn("Tried to update the flows while the node was not the master");
624 return;
625 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700626 // the two rules are not an exact match - remove the
627 // switch's rule and install our rule
628 extraneousFlow(rule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530629 flowMissing(storedRule, false);
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700630 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800631 } else {
632 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700633 if (!allowExtraneousRules) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000634 // Mastership change can occur during this iteration
635 master = mastershipService.getMasterFor(deviceId);
636 if (!Objects.equals(local, master)) {
637 log.warn("Tried to remove flows while the node was not the master");
638 return;
639 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700640 extraneousFlow(rule);
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100641 } else if (importExtraneousRules) { // Stores the rule, if so is indicated
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000642 FlowRuleEvent flowRuleEvent = store.addOrUpdateFlowRule(rule);
643 if (flowRuleEvent == null) {
644 // Mastership change can occur during this iteration
645 master = mastershipService.getMasterFor(deviceId);
646 if (!Objects.equals(local, master)) {
647 log.warn("Tried to import flows while the node was not the master");
648 return;
649 }
650 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700651 }
alshabib93cb57f2015-02-12 17:43:26 -0800652 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700653 } catch (Exception e) {
Jon Hall274cecb2017-08-09 12:15:48 -0700654 log.warn("Can't process added or extra rule {} for device {}:{}",
655 rule, deviceId, e);
alshabib93cb57f2015-02-12 17:43:26 -0800656 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800657 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900658
659 // DO NOT reinstall
660 if (useMissingFlow) {
661 for (FlowEntry rule : storedRules.keySet()) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000662 // Mastership change can occur during this iteration
663 master = mastershipService.getMasterFor(deviceId);
664 if (!Objects.equals(local, master)) {
665 log.warn("Tried to install missing rules while the node was not the master");
666 return;
667 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900668 try {
669 // there are rules in the store that aren't on the switch
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530670 log.debug("Adding the rule that is present in store but not on switch : {}", rule);
671 flowMissing(rule, true);
ssyoon9030fbcd92015-08-17 10:42:07 +0900672 } catch (Exception e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700673 log.warn("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900674 }
alshabib93cb57f2015-02-12 17:43:26 -0800675 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800676 }
alshabib5c370ff2014-09-18 10:12:14 -0700677 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800678
679 @Override
680 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
681 store.batchOperationComplete(FlowRuleBatchEvent.completed(
682 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
683 operation
684 ));
685 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700686
687 @Override
688 public void pushTableStatistics(DeviceId deviceId,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100689 List<TableStatisticsEntry> tableStats) {
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700690 store.updateTableStatistics(deviceId, tableStats);
691 }
alshabib57044ba2014-09-16 15:58:01 -0700692 }
693
tomc78acee2014-09-24 15:16:55 -0700694 // Store delegate to re-post events emitted from the store.
695 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800696
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800697
Madan Jampani117aaae2014-10-23 10:04:05 -0700698 // TODO: Right now we only dispatch events at individual flowEntry level.
699 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700700 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700701 public void notify(FlowRuleBatchEvent event) {
702 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700703 switch (event.type()) {
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100704 case BATCH_OPERATION_REQUESTED:
705 // Request has been forwarded to MASTER Node, and was
706 request.ops().forEach(
707 op -> {
708 switch (op.operator()) {
709 case ADD:
710 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
711 break;
712 case REMOVE:
713 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
714 break;
715 case MODIFY:
716 //TODO: do something here when the time comes.
717 break;
718 default:
719 log.warn("Unknown flow operation operator: {}", op.operator());
720 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800721 }
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100722 );
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800723
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100724 DeviceId deviceId = event.deviceId();
725 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
726 // getProvider is customized to favor driverProvider
727 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
728 if (flowRuleProvider != null) {
729 log.trace("Sending {} flow rules to {}", batchOperation.size(), deviceId);
730 flowRuleProvider.executeBatch(batchOperation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800731 }
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800732
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100733 break;
734
735 case BATCH_OPERATION_COMPLETED:
736 // Operation completed, let's retrieve the processor and trigger the callback
737 FlowOperationsProcessor fops = pendingFlowOperations.remove(
738 event.subject().batchId());
739 if (fops != null) {
740 if (event.result().isSuccess()) {
741 fops.satisfy(event.deviceId());
742 } else {
743 fops.fail(event.deviceId(), event.result().failedItems());
744 }
745 } else {
746 log.warn("Unable to find flow operations processor for batch: {}", event.subject().batchId());
747 }
748 break;
749
750 default:
751 break;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700752 }
tomc78acee2014-09-24 15:16:55 -0700753 }
754 }
alshabib902d41b2014-10-07 16:52:05 -0700755
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700756 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
757 switch (input) {
758 case ADD:
759 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
760 case MODIFY:
761 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
762 case REMOVE:
763 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
764 default:
765 throw new UnsupportedOperationException("Unknown flow rule type " + input);
766 }
767 }
768
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800769 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700770 // Immutable
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800771 private final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700772
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700773 // Mutable
774 private final List<Set<FlowRuleOperation>> stages;
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700775 private final Set<DeviceId> pendingDevices = new HashSet<>();
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700776 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700777
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700778 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800779 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800780 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700781 }
782
783 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700784 public synchronized void run() {
Jon Hallcbd1b392017-01-18 20:15:44 -0800785 if (!stages.isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800786 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700787 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700788 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700789 }
790 }
791
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800792 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700793 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800794
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700795 for (FlowRuleOperation op : ops) {
796 perDeviceBatches.put(op.rule().deviceId(),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100797 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800798 }
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000799 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800800
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800801 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700802 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800803 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100804 deviceId, id);
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000805 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700806 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700807 }
808 }
809
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700810 synchronized void satisfy(DeviceId devId) {
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000811 pendingDevices.remove(devId);
812 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700813 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700814 }
alshabib193525b2014-10-08 18:58:03 -0700815 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800816
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700817 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZUb9e0ab72016-09-14 16:54:13 -0700818 hasFailed = true;
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000819 pendingDevices.remove(devId);
820 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700821 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800822 }
823
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700824 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
825 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800826
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700827 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800828 }
alshabib902d41b2014-10-07 16:52:05 -0700829 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700830
831 @Override
832 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
833 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800834 checkNotNull(deviceId, DEVICE_ID_NULL);
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700835 return store.getTableStatistics(deviceId);
836 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800837
Patryk Konopka7e40c012017-06-06 13:38:06 +0200838 @Override
839 public long getActiveFlowRuleCount(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800840 checkNotNull(deviceId, DEVICE_ID_NULL);
Patryk Konopka7e40c012017-06-06 13:38:06 +0200841 return store.getActiveFlowRuleCount(deviceId);
842 }
843
Charles Chan0c7c43b2016-01-14 17:39:20 -0800844 private class InternalDeviceListener implements DeviceListener {
845 @Override
846 public void event(DeviceEvent event) {
847 switch (event.type()) {
848 case DEVICE_REMOVED:
849 case DEVICE_AVAILABILITY_CHANGED:
850 DeviceId deviceId = event.subject().id();
851 if (!deviceService.isAvailable(deviceId)) {
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100852 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
853 //if purgeOnDisconnection is set for the device or it's a global configuration
854 // lets remove the flows. Priority is given to the per device flag
855 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
856 cfg.purgeOnDisconnection() : purgeOnDisconnection;
857 if (purge) {
858 log.info("PurgeOnDisconnection is requested for device {}, " +
859 "removing flows", deviceId);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800860 store.purgeFlowRule(deviceId);
861 }
862 }
863 break;
864 default:
865 break;
866 }
867 }
868 }
alshabib57044ba2014-09-16 15:58:01 -0700869}