blob: d593e4588789c7bd8a92a004769c64a9920699a5 [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
Andrea Campanella6a3ee342021-12-14 14:48:54 +0100525 private boolean handleExistingFlow(FlowEntry flowEntry) {
alshabib1c319ff2014-10-04 20:29:09 -0700526 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700527 checkValidity();
Andrea Campanella6a3ee342021-12-14 14:48:54 +0100528 FlowEntry storedEntry = store.getFlowEntry(flowEntry);
pierventre7768d7f2022-01-04 19:08:46 +0100529 if (storedEntry != null) {
530 // Flow rule is still valid, let's try to update the stats
531 if (storedEntry.state() != FlowEntry.FlowEntryState.PENDING_REMOVE &&
532 checkRuleLiveness(flowEntry, storedEntry)) {
533 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
534 /* Something went wrong or there is no master
535 better check if it is the latter */
536 if (event == null) {
537 log.debug("No flow store event generated for addOrUpdate of {}", flowEntry);
538 return false;
539 } else {
540 log.trace("Flow {} {}", flowEntry, event.type());
541 post(event);
542 }
alshabibba5ac482014-10-02 17:15:20 -0700543 } else {
pierventre7768d7f2022-01-04 19:08:46 +0100544 log.debug("Removing {}", flowEntry);
545 removeFlowRules(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700546 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700547 } else {
pierventre7768d7f2022-01-04 19:08:46 +0100548 /* It was already removed or there is no master
549 better check if it is the latter */
550 return false;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700551 }
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000552 return true;
alshabib57044ba2014-09-16 15:58:01 -0700553 }
554
alshabib1c319ff2014-10-04 20:29:09 -0700555 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
556 if (storedRule == null) {
557 return false;
558 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700559 if (storedRule.isPermanent()) {
560 return true;
561 }
562
Ray Milkey3717e602018-02-01 13:49:47 -0800563 final long timeout = storedRule.timeout() * 1000L;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700564 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700565
566 // Checking flow with hardTimeout
567 if (storedRule.hardTimeout() != 0) {
568 if (!firstSeen.containsKey(storedRule)) {
569 // First time rule adding
570 firstSeen.put(storedRule, currentTime);
571 } else {
572 Long first = firstSeen.get(storedRule);
Ray Milkey3717e602018-02-01 13:49:47 -0800573 final long hardTimeout = storedRule.hardTimeout() * 1000L;
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700574 if ((currentTime - first) > hardTimeout) {
575 return false;
576 }
577 }
578 }
579
Gamze Abaka8d03f182017-07-20 15:09:24 +0000580 if (storedRule.packets() != swRule.packets() || storedRule.bytes() != swRule.bytes()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700581 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700582 return true;
583 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700584 if (!lastSeen.containsKey(storedRule)) {
585 // checking for the first time
586 lastSeen.put(storedRule, storedRule.lastSeen());
587 // Use following if lastSeen attr. was removed.
588 //lastSeen.put(storedRule, currentTime);
589 }
590 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700591
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800592 // concurrently removed? let the liveness check fail
593 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700594 }
595
alshabib5c370ff2014-09-18 10:12:14 -0700596 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700597 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900598 pushFlowMetricsInternal(deviceId, flowEntries, true);
599 }
600
601 @Override
602 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
603 pushFlowMetricsInternal(deviceId, flowEntries, false);
604 }
605
606 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
607 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700608 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
609 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000610 NodeId master;
611 boolean done;
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700612
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000613 // Processing flow rules
Saurav Dasfa2fa932015-03-03 11:29:48 -0800614 for (FlowEntry rule : flowEntries) {
615 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700616 FlowEntry storedRule = storedRules.remove(rule);
617 if (storedRule != null) {
618 if (storedRule.exactMatch(rule)) {
619 // we both have the rule, let's update some info then.
Andrea Campanella6a3ee342021-12-14 14:48:54 +0100620 done = handleExistingFlow(rule);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000621 if (!done) {
622 // Mastership change can occur during this iteration
623 master = mastershipService.getMasterFor(deviceId);
624 if (!Objects.equals(local, master)) {
625 log.warn("Tried to update the flow stats while the node was not the master");
626 return;
627 }
628 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700629 } else {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000630 // Mastership change can occur during this iteration
631 master = mastershipService.getMasterFor(deviceId);
632 if (!Objects.equals(local, master)) {
633 log.warn("Tried to update the flows while the node was not the master");
634 return;
635 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700636 // the two rules are not an exact match - remove the
637 // switch's rule and install our rule
638 extraneousFlow(rule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530639 flowMissing(storedRule, false);
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700640 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800641 } else {
642 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700643 if (!allowExtraneousRules) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000644 // Mastership change can occur during this iteration
645 master = mastershipService.getMasterFor(deviceId);
646 if (!Objects.equals(local, master)) {
647 log.warn("Tried to remove flows while the node was not the master");
648 return;
649 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700650 extraneousFlow(rule);
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100651 } else if (importExtraneousRules) { // Stores the rule, if so is indicated
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000652 FlowRuleEvent flowRuleEvent = store.addOrUpdateFlowRule(rule);
653 if (flowRuleEvent == null) {
654 // Mastership change can occur during this iteration
655 master = mastershipService.getMasterFor(deviceId);
656 if (!Objects.equals(local, master)) {
657 log.warn("Tried to import flows while the node was not the master");
658 return;
659 }
660 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700661 }
alshabib93cb57f2015-02-12 17:43:26 -0800662 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700663 } catch (Exception e) {
Jon Hall274cecb2017-08-09 12:15:48 -0700664 log.warn("Can't process added or extra rule {} for device {}:{}",
665 rule, deviceId, e);
alshabib93cb57f2015-02-12 17:43:26 -0800666 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800667 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900668
669 // DO NOT reinstall
670 if (useMissingFlow) {
671 for (FlowEntry rule : storedRules.keySet()) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000672 // Mastership change can occur during this iteration
673 master = mastershipService.getMasterFor(deviceId);
674 if (!Objects.equals(local, master)) {
675 log.warn("Tried to install missing rules while the node was not the master");
676 return;
677 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900678 try {
679 // there are rules in the store that aren't on the switch
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530680 log.debug("Adding the rule that is present in store but not on switch : {}", rule);
681 flowMissing(rule, true);
ssyoon9030fbcd92015-08-17 10:42:07 +0900682 } catch (Exception e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700683 log.warn("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900684 }
alshabib93cb57f2015-02-12 17:43:26 -0800685 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800686 }
alshabib5c370ff2014-09-18 10:12:14 -0700687 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800688
689 @Override
690 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
691 store.batchOperationComplete(FlowRuleBatchEvent.completed(
692 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
693 operation
694 ));
695 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700696
697 @Override
698 public void pushTableStatistics(DeviceId deviceId,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100699 List<TableStatisticsEntry> tableStats) {
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700700 store.updateTableStatistics(deviceId, tableStats);
701 }
alshabib57044ba2014-09-16 15:58:01 -0700702 }
703
tomc78acee2014-09-24 15:16:55 -0700704 // Store delegate to re-post events emitted from the store.
705 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800706
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800707
Madan Jampani117aaae2014-10-23 10:04:05 -0700708 // TODO: Right now we only dispatch events at individual flowEntry level.
709 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700710 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700711 public void notify(FlowRuleBatchEvent event) {
712 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700713 switch (event.type()) {
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100714 case BATCH_OPERATION_REQUESTED:
715 // Request has been forwarded to MASTER Node, and was
716 request.ops().forEach(
717 op -> {
718 switch (op.operator()) {
719 case ADD:
720 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
721 break;
722 case REMOVE:
723 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
724 break;
725 case MODIFY:
726 //TODO: do something here when the time comes.
727 break;
728 default:
729 log.warn("Unknown flow operation operator: {}", op.operator());
730 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800731 }
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100732 );
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800733
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100734 DeviceId deviceId = event.deviceId();
735 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
736 // getProvider is customized to favor driverProvider
737 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
738 if (flowRuleProvider != null) {
739 log.trace("Sending {} flow rules to {}", batchOperation.size(), deviceId);
740 flowRuleProvider.executeBatch(batchOperation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800741 }
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800742
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100743 break;
744
745 case BATCH_OPERATION_COMPLETED:
746 // Operation completed, let's retrieve the processor and trigger the callback
747 FlowOperationsProcessor fops = pendingFlowOperations.remove(
748 event.subject().batchId());
749 if (fops != null) {
750 if (event.result().isSuccess()) {
751 fops.satisfy(event.deviceId());
752 } else {
753 fops.fail(event.deviceId(), event.result().failedItems());
754 }
755 } else {
756 log.warn("Unable to find flow operations processor for batch: {}", event.subject().batchId());
757 }
758 break;
759
760 default:
761 break;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700762 }
tomc78acee2014-09-24 15:16:55 -0700763 }
764 }
alshabib902d41b2014-10-07 16:52:05 -0700765
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700766 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
767 switch (input) {
768 case ADD:
769 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
770 case MODIFY:
771 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
772 case REMOVE:
773 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
774 default:
775 throw new UnsupportedOperationException("Unknown flow rule type " + input);
776 }
777 }
778
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800779 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700780 // Immutable
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800781 private final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700782
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700783 // Mutable
784 private final List<Set<FlowRuleOperation>> stages;
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700785 private final Set<DeviceId> pendingDevices = new HashSet<>();
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700786 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700787
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700788 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800789 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800790 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700791 }
792
793 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700794 public synchronized void run() {
Jon Hallcbd1b392017-01-18 20:15:44 -0800795 if (!stages.isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800796 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700797 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700798 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700799 }
800 }
801
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800802 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700803 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800804
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700805 for (FlowRuleOperation op : ops) {
806 perDeviceBatches.put(op.rule().deviceId(),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100807 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800808 }
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000809 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800810
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800811 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700812 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800813 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100814 deviceId, id);
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000815 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700816 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700817 }
818 }
819
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700820 synchronized void satisfy(DeviceId devId) {
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000821 pendingDevices.remove(devId);
822 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700823 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700824 }
alshabib193525b2014-10-08 18:58:03 -0700825 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800826
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700827 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZUb9e0ab72016-09-14 16:54:13 -0700828 hasFailed = true;
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000829 pendingDevices.remove(devId);
830 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700831 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800832 }
833
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700834 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
835 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800836
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700837 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800838 }
alshabib902d41b2014-10-07 16:52:05 -0700839 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700840
841 @Override
842 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
843 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800844 checkNotNull(deviceId, DEVICE_ID_NULL);
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700845 return store.getTableStatistics(deviceId);
846 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800847
Patryk Konopka7e40c012017-06-06 13:38:06 +0200848 @Override
849 public long getActiveFlowRuleCount(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800850 checkNotNull(deviceId, DEVICE_ID_NULL);
Patryk Konopka7e40c012017-06-06 13:38:06 +0200851 return store.getActiveFlowRuleCount(deviceId);
852 }
853
Charles Chan0c7c43b2016-01-14 17:39:20 -0800854 private class InternalDeviceListener implements DeviceListener {
855 @Override
856 public void event(DeviceEvent event) {
857 switch (event.type()) {
858 case DEVICE_REMOVED:
859 case DEVICE_AVAILABILITY_CHANGED:
860 DeviceId deviceId = event.subject().id();
861 if (!deviceService.isAvailable(deviceId)) {
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100862 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
863 //if purgeOnDisconnection is set for the device or it's a global configuration
864 // lets remove the flows. Priority is given to the per device flag
865 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
866 cfg.purgeOnDisconnection() : purgeOnDisconnection;
867 if (purge) {
868 log.info("PurgeOnDisconnection is requested for device {}, " +
869 "removing flows", deviceId);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800870 store.purgeFlowRule(deviceId);
871 }
872 }
873 break;
874 default:
875 break;
876 }
877 }
878 }
alshabib57044ba2014-09-16 15:58:01 -0700879}