blob: 9bc5abc8ef47090b0a77059b85694d385d028053 [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)) {
pierventred8d40252022-02-18 15:12:33 -0800533 if (!shouldHandle(flowEntry.deviceId())) {
534 return false;
535 }
pierventre7768d7f2022-01-04 19:08:46 +0100536 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
pierventred8d40252022-02-18 15:12:33 -0800537 // Something went wrong or there is no master or
538 // the device is not available better check if it
539 // is the latter cases
pierventre7768d7f2022-01-04 19:08:46 +0100540 if (event == null) {
541 log.debug("No flow store event generated for addOrUpdate of {}", flowEntry);
542 return false;
543 } else {
544 log.trace("Flow {} {}", flowEntry, event.type());
545 post(event);
546 }
alshabibba5ac482014-10-02 17:15:20 -0700547 } else {
pierventre7768d7f2022-01-04 19:08:46 +0100548 log.debug("Removing {}", flowEntry);
549 removeFlowRules(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700550 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700551 } else {
pierventred8d40252022-02-18 15:12:33 -0800552 // It was already removed or there is no master
553 // better check if it is the latter
pierventre7768d7f2022-01-04 19:08:46 +0100554 return false;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700555 }
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000556 return true;
alshabib57044ba2014-09-16 15:58:01 -0700557 }
558
alshabib1c319ff2014-10-04 20:29:09 -0700559 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
560 if (storedRule == null) {
561 return false;
562 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700563 if (storedRule.isPermanent()) {
564 return true;
565 }
566
Ray Milkey3717e602018-02-01 13:49:47 -0800567 final long timeout = storedRule.timeout() * 1000L;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700568 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700569
570 // Checking flow with hardTimeout
571 if (storedRule.hardTimeout() != 0) {
572 if (!firstSeen.containsKey(storedRule)) {
573 // First time rule adding
574 firstSeen.put(storedRule, currentTime);
575 } else {
576 Long first = firstSeen.get(storedRule);
Ray Milkey3717e602018-02-01 13:49:47 -0800577 final long hardTimeout = storedRule.hardTimeout() * 1000L;
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700578 if ((currentTime - first) > hardTimeout) {
579 return false;
580 }
581 }
582 }
583
Gamze Abaka8d03f182017-07-20 15:09:24 +0000584 if (storedRule.packets() != swRule.packets() || storedRule.bytes() != swRule.bytes()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700585 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700586 return true;
587 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700588 if (!lastSeen.containsKey(storedRule)) {
589 // checking for the first time
590 lastSeen.put(storedRule, storedRule.lastSeen());
591 // Use following if lastSeen attr. was removed.
592 //lastSeen.put(storedRule, currentTime);
593 }
594 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700595
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800596 // concurrently removed? let the liveness check fail
597 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700598 }
599
alshabib5c370ff2014-09-18 10:12:14 -0700600 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700601 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900602 pushFlowMetricsInternal(deviceId, flowEntries, true);
603 }
604
605 @Override
606 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
607 pushFlowMetricsInternal(deviceId, flowEntries, false);
608 }
609
pierventred8d40252022-02-18 15:12:33 -0800610 private boolean shouldHandle(DeviceId deviceId) {
611 NodeId master = mastershipService.getMasterFor(deviceId);
612 return Objects.equals(local, master) && deviceService.isAvailable(deviceId);
613 }
614
ssyoon9030fbcd92015-08-17 10:42:07 +0900615 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
616 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700617 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
618 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000619 NodeId master;
620 boolean done;
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700621
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000622 // Processing flow rules
Saurav Dasfa2fa932015-03-03 11:29:48 -0800623 for (FlowEntry rule : flowEntries) {
624 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700625 FlowEntry storedRule = storedRules.remove(rule);
626 if (storedRule != null) {
627 if (storedRule.exactMatch(rule)) {
628 // we both have the rule, let's update some info then.
Andrea Campanella6a3ee342021-12-14 14:48:54 +0100629 done = handleExistingFlow(rule);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000630 if (!done) {
631 // Mastership change can occur during this iteration
pierventred8d40252022-02-18 15:12:33 -0800632 if (!shouldHandle(deviceId)) {
633 log.warn("Tried to update the flow stats while the node was not the master" +
634 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000635 return;
636 }
637 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700638 } else {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000639 // Mastership change can occur during this iteration
pierventred8d40252022-02-18 15:12:33 -0800640 if (!shouldHandle(deviceId)) {
641 log.warn("Tried to update the flows while the node was not the master" +
642 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000643 return;
644 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700645 // the two rules are not an exact match - remove the
646 // switch's rule and install our rule
647 extraneousFlow(rule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530648 flowMissing(storedRule, false);
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700649 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800650 } else {
651 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700652 if (!allowExtraneousRules) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000653 // Mastership change can occur during this iteration
pierventred8d40252022-02-18 15:12:33 -0800654 if (!shouldHandle(deviceId)) {
655 log.warn("Tried to remove flows while the node was not the master" +
656 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000657 return;
658 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700659 extraneousFlow(rule);
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100660 } else if (importExtraneousRules) { // Stores the rule, if so is indicated
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000661 FlowRuleEvent flowRuleEvent = store.addOrUpdateFlowRule(rule);
662 if (flowRuleEvent == null) {
663 // Mastership change can occur during this iteration
pierventred8d40252022-02-18 15:12:33 -0800664 if (!shouldHandle(deviceId)) {
665 log.warn("Tried to import flows while the node was not the master" +
666 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000667 return;
668 }
669 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700670 }
alshabib93cb57f2015-02-12 17:43:26 -0800671 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700672 } catch (Exception e) {
Jon Hall274cecb2017-08-09 12:15:48 -0700673 log.warn("Can't process added or extra rule {} for device {}:{}",
674 rule, deviceId, e);
alshabib93cb57f2015-02-12 17:43:26 -0800675 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800676 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900677
678 // DO NOT reinstall
679 if (useMissingFlow) {
680 for (FlowEntry rule : storedRules.keySet()) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000681 // Mastership change can occur during this iteration
pierventred8d40252022-02-18 15:12:33 -0800682 if (!shouldHandle(deviceId)) {
683 log.warn("Tried to install missing rules while the node was not the master" +
684 " or the device {} was not available", deviceId);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000685 return;
686 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900687 try {
688 // there are rules in the store that aren't on the switch
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530689 log.debug("Adding the rule that is present in store but not on switch : {}", rule);
690 flowMissing(rule, true);
ssyoon9030fbcd92015-08-17 10:42:07 +0900691 } catch (Exception e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700692 log.warn("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900693 }
alshabib93cb57f2015-02-12 17:43:26 -0800694 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800695 }
alshabib5c370ff2014-09-18 10:12:14 -0700696 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800697
698 @Override
699 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
700 store.batchOperationComplete(FlowRuleBatchEvent.completed(
701 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
702 operation
703 ));
704 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700705
706 @Override
707 public void pushTableStatistics(DeviceId deviceId,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100708 List<TableStatisticsEntry> tableStats) {
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700709 store.updateTableStatistics(deviceId, tableStats);
710 }
alshabib57044ba2014-09-16 15:58:01 -0700711 }
712
tomc78acee2014-09-24 15:16:55 -0700713 // Store delegate to re-post events emitted from the store.
714 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800715
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800716
Madan Jampani117aaae2014-10-23 10:04:05 -0700717 // TODO: Right now we only dispatch events at individual flowEntry level.
718 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700719 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700720 public void notify(FlowRuleBatchEvent event) {
721 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700722 switch (event.type()) {
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100723 case BATCH_OPERATION_REQUESTED:
724 // Request has been forwarded to MASTER Node, and was
725 request.ops().forEach(
726 op -> {
727 switch (op.operator()) {
728 case ADD:
729 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
730 break;
731 case REMOVE:
732 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
733 break;
734 case MODIFY:
735 //TODO: do something here when the time comes.
736 break;
737 default:
738 log.warn("Unknown flow operation operator: {}", op.operator());
739 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800740 }
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100741 );
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800742
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100743 DeviceId deviceId = event.deviceId();
744 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
745 // getProvider is customized to favor driverProvider
746 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
747 if (flowRuleProvider != null) {
748 log.trace("Sending {} flow rules to {}", batchOperation.size(), deviceId);
749 flowRuleProvider.executeBatch(batchOperation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800750 }
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800751
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100752 break;
753
754 case BATCH_OPERATION_COMPLETED:
755 // Operation completed, let's retrieve the processor and trigger the callback
756 FlowOperationsProcessor fops = pendingFlowOperations.remove(
757 event.subject().batchId());
758 if (fops != null) {
759 if (event.result().isSuccess()) {
760 fops.satisfy(event.deviceId());
761 } else {
762 fops.fail(event.deviceId(), event.result().failedItems());
763 }
764 } else {
765 log.warn("Unable to find flow operations processor for batch: {}", event.subject().batchId());
766 }
767 break;
768
769 default:
770 break;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700771 }
tomc78acee2014-09-24 15:16:55 -0700772 }
773 }
alshabib902d41b2014-10-07 16:52:05 -0700774
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700775 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
776 switch (input) {
777 case ADD:
778 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
779 case MODIFY:
780 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
781 case REMOVE:
782 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
783 default:
784 throw new UnsupportedOperationException("Unknown flow rule type " + input);
785 }
786 }
787
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800788 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700789 // Immutable
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800790 private final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700791
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700792 // Mutable
793 private final List<Set<FlowRuleOperation>> stages;
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700794 private final Set<DeviceId> pendingDevices = new HashSet<>();
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700795 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700796
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700797 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800798 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800799 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700800 }
801
802 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700803 public synchronized void run() {
Jon Hallcbd1b392017-01-18 20:15:44 -0800804 if (!stages.isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800805 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700806 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700807 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700808 }
809 }
810
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800811 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700812 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800813
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700814 for (FlowRuleOperation op : ops) {
815 perDeviceBatches.put(op.rule().deviceId(),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100816 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800817 }
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000818 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800819
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800820 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700821 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800822 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100823 deviceId, id);
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000824 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700825 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700826 }
827 }
828
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700829 synchronized void satisfy(DeviceId devId) {
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000830 pendingDevices.remove(devId);
831 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700832 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700833 }
alshabib193525b2014-10-08 18:58:03 -0700834 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800835
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700836 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZUb9e0ab72016-09-14 16:54:13 -0700837 hasFailed = true;
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000838 pendingDevices.remove(devId);
839 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700840 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800841 }
842
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700843 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
844 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800845
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700846 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800847 }
alshabib902d41b2014-10-07 16:52:05 -0700848 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700849
850 @Override
851 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
852 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800853 checkNotNull(deviceId, DEVICE_ID_NULL);
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700854 return store.getTableStatistics(deviceId);
855 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800856
Patryk Konopka7e40c012017-06-06 13:38:06 +0200857 @Override
858 public long getActiveFlowRuleCount(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800859 checkNotNull(deviceId, DEVICE_ID_NULL);
Patryk Konopka7e40c012017-06-06 13:38:06 +0200860 return store.getActiveFlowRuleCount(deviceId);
861 }
862
Charles Chan0c7c43b2016-01-14 17:39:20 -0800863 private class InternalDeviceListener implements DeviceListener {
864 @Override
865 public void event(DeviceEvent event) {
866 switch (event.type()) {
867 case DEVICE_REMOVED:
868 case DEVICE_AVAILABILITY_CHANGED:
869 DeviceId deviceId = event.subject().id();
870 if (!deviceService.isAvailable(deviceId)) {
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100871 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
872 //if purgeOnDisconnection is set for the device or it's a global configuration
873 // lets remove the flows. Priority is given to the per device flag
874 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
875 cfg.purgeOnDisconnection() : purgeOnDisconnection;
876 if (purge) {
877 log.info("PurgeOnDisconnection is requested for device {}, " +
878 "removing flows", deviceId);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800879 store.purgeFlowRule(deviceId);
880 }
881 }
882 break;
883 default:
884 break;
885 }
886 }
887 }
alshabib57044ba2014-09-16 15:58:01 -0700888}