blob: ac97636c75fee008b93890ae2d73896299642b42 [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
alshabib1c319ff2014-10-04 20:29:09 -0700298 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900299 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800300 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700301 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700302 }
303
304 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700305 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900306 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900307
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800308 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800309 for (FlowRule flowRule : flowRules) {
310 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700311 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800312 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700313 }
314
315 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530316 public void purgeFlowRules(DeviceId deviceId) {
317 checkPermission(FLOWRULE_WRITE);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800318 checkNotNull(deviceId, DEVICE_ID_NULL);
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530319 store.purgeFlowRule(deviceId);
320 }
321
322 @Override
Daniele Moro43ac2892021-07-15 17:02:59 +0200323 public void purgeFlowRules(DeviceId deviceId, ApplicationId appId) {
324 checkPermission(FLOWRULE_WRITE);
325 checkNotNull(deviceId, DEVICE_ID_NULL);
326 checkNotNull(appId, "Application ID cannot be null!");
327
328 store.purgeFlowRules(deviceId, appId);
329 }
330
331 @Override
alshabib57044ba2014-09-16 15:58:01 -0700332 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900333 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900334
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800335 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800336 for (FlowRule flowRule : flowRules) {
337 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700338 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800339 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700340 }
alshabib57044ba2014-09-16 15:58:01 -0700341
alshabiba68eb962014-09-24 20:34:13 -0700342 @Override
343 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900344 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900345
Madan Jampani6a456162014-10-24 11:36:17 -0700346 Set<FlowRule> flowEntries = Sets.newHashSet();
347 for (Device d : deviceService.getDevices()) {
348 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
349 if (flowEntry.appId() == id.id()) {
350 flowEntries.add(flowEntry);
351 }
352 }
353 }
Ray Milkey4f7e3632019-02-19 15:35:20 -0800354 removeFlowRules(Iterables.toArray(flowEntries, FlowRule.class));
alshabib57044ba2014-09-16 15:58:01 -0700355 }
356
357 @Override
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530358 public Iterable<FlowEntry> getFlowEntriesById(ApplicationId id) {
359 checkPermission(FLOWRULE_READ);
360
361 Set<FlowEntry> flowEntries = Sets.newHashSet();
362 for (Device d : deviceService.getDevices()) {
363 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
364 if (flowEntry.appId() == id.id()) {
365 flowEntries.add(flowEntry);
366 }
367 }
368 }
369 return flowEntries;
370 }
371
372 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800373 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900374 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900375
alshabibaa7e7de2014-11-12 19:20:44 -0800376 Set<FlowRule> matches = Sets.newHashSet();
377 long toLookUp = ((long) appId.id() << 16) | groupId;
378 for (Device d : deviceService.getDevices()) {
379 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
380 if ((flowEntry.id().value() >>> 32) == toLookUp) {
381 matches.add(flowEntry);
382 }
383 }
384 }
385 return matches;
386 }
387
388 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800389 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900390 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700391 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700392 }
393
394 @Override
alshabib57044ba2014-09-16 15:58:01 -0700395 protected FlowRuleProviderService createProviderService(
396 FlowRuleProvider provider) {
397 return new InternalFlowRuleProviderService(provider);
398 }
399
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800400 @Override
401 protected synchronized FlowRuleProvider getProvider(ProviderId pid) {
402 log.warn("should not be calling getProvider(ProviderId)");
403 return super.getProvider(pid);
404 }
405
406 /**
407 * {@inheritDoc}
408 * if the Device does not support {@link FlowRuleProgrammable}.
409 */
410 @Override
411 protected synchronized FlowRuleProvider getProvider(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800412 checkNotNull(deviceId, DEVICE_ID_NULL);
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800413 // if device supports FlowRuleProgrammable,
414 // use FlowRuleProgrammable via FlowRuleDriverProvider
415 return Optional.ofNullable(deviceService.getDevice(deviceId))
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100416 .filter(dev -> dev.is(FlowRuleProgrammable.class))
417 .<FlowRuleProvider>map(x -> driverProvider)
418 .orElseGet(() -> super.getProvider(deviceId));
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800419 }
420
alshabib57044ba2014-09-16 15:58:01 -0700421 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700422 extends AbstractProviderService<FlowRuleProvider>
423 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700424
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700425 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700426 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
427
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700428
alshabib57044ba2014-09-16 15:58:01 -0700429 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
430 super(provider);
431 }
432
433 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700434 public void flowRemoved(FlowEntry flowEntry) {
435 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700436 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700437 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700438 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700439 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700440 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800441 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700442 return;
443 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700444 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
445 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
446 }
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800447 FlowRuleProvider frp = getProvider(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700448 FlowRuleEvent event = null;
449 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700450 case ADDED:
451 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700452 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700453 break;
454 case PENDING_REMOVE:
455 case REMOVED:
456 event = store.removeFlowRule(stored);
457 break;
458 default:
459 break;
alshabib57044ba2014-09-16 15:58:01 -0700460
alshabiba68eb962014-09-24 20:34:13 -0700461 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700462 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700463 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700464 post(event);
465 }
alshabib57044ba2014-09-16 15:58:01 -0700466 }
467
alshabibba5ac482014-10-02 17:15:20 -0700468
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530469 private void flowMissing(FlowEntry flowRule, boolean isFlowOnlyInStore) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700470 checkNotNull(flowRule, FLOW_RULE_NULL);
471 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800472 FlowRuleProvider frp = getProvider(flowRule.deviceId());
alshabibbb42cad2014-09-25 11:43:05 -0700473 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700474 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700475 case PENDING_REMOVE:
476 case REMOVED:
477 event = store.removeFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530478 log.debug("Flow {} removed", flowRule);
tom9b4030d2014-10-06 10:39:03 -0700479 break;
480 case ADDED:
481 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800482 event = store.pendingFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530483 if (isFlowOnlyInStore) {
484 // Publishing RULE_ADD_REQUESTED event facilitates
485 // preparation of statistics for the concerned rule
486 if (event == null) {
487 event = new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADD_REQUESTED, flowRule);
488 }
489 }
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800490 try {
491 frp.applyFlowRule(flowRule);
492 } catch (UnsupportedOperationException e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700493 log.warn("Unsupported operation", e);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800494 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800495 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800496 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
497 }
498 }
tom9b4030d2014-10-06 10:39:03 -0700499 break;
500 default:
501 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700502 }
503
alshabibbb42cad2014-09-25 11:43:05 -0700504 if (event != null) {
alshabibbb42cad2014-09-25 11:43:05 -0700505 post(event);
506 }
alshabib57044ba2014-09-16 15:58:01 -0700507 }
508
alshabibba5ac482014-10-02 17:15:20 -0700509 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700510 checkNotNull(flowRule, FLOW_RULE_NULL);
511 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800512 // getProvider is customized to favor driverProvider
alshabib2374fc92014-10-22 11:03:23 -0700513 FlowRuleProvider frp = getProvider(flowRule.deviceId());
514 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700515 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700516 }
517
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000518 private boolean flowAdded(FlowEntry flowEntry) {
alshabib1c319ff2014-10-04 20:29:09 -0700519 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700520 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700521
alshabib1c319ff2014-10-04 20:29:09 -0700522 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700523 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700524 if (event == null) {
525 log.debug("No flow store event generated.");
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000526 return false;
alshabibba5ac482014-10-02 17:15:20 -0700527 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800528 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700529 post(event);
530 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700531 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800532 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700533 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700534 }
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000535 return true;
alshabib57044ba2014-09-16 15:58:01 -0700536 }
537
alshabib1c319ff2014-10-04 20:29:09 -0700538 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
539 if (storedRule == null) {
540 return false;
541 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700542 if (storedRule.isPermanent()) {
543 return true;
544 }
545
Ray Milkey3717e602018-02-01 13:49:47 -0800546 final long timeout = storedRule.timeout() * 1000L;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700547 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700548
549 // Checking flow with hardTimeout
550 if (storedRule.hardTimeout() != 0) {
551 if (!firstSeen.containsKey(storedRule)) {
552 // First time rule adding
553 firstSeen.put(storedRule, currentTime);
554 } else {
555 Long first = firstSeen.get(storedRule);
Ray Milkey3717e602018-02-01 13:49:47 -0800556 final long hardTimeout = storedRule.hardTimeout() * 1000L;
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700557 if ((currentTime - first) > hardTimeout) {
558 return false;
559 }
560 }
561 }
562
Gamze Abaka8d03f182017-07-20 15:09:24 +0000563 if (storedRule.packets() != swRule.packets() || storedRule.bytes() != swRule.bytes()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700564 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700565 return true;
566 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700567 if (!lastSeen.containsKey(storedRule)) {
568 // checking for the first time
569 lastSeen.put(storedRule, storedRule.lastSeen());
570 // Use following if lastSeen attr. was removed.
571 //lastSeen.put(storedRule, currentTime);
572 }
573 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700574
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800575 // concurrently removed? let the liveness check fail
576 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700577 }
578
alshabib5c370ff2014-09-18 10:12:14 -0700579 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700580 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900581 pushFlowMetricsInternal(deviceId, flowEntries, true);
582 }
583
584 @Override
585 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
586 pushFlowMetricsInternal(deviceId, flowEntries, false);
587 }
588
589 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
590 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700591 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
592 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000593 NodeId master;
594 boolean done;
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700595
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000596 // Processing flow rules
Saurav Dasfa2fa932015-03-03 11:29:48 -0800597 for (FlowEntry rule : flowEntries) {
598 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700599 FlowEntry storedRule = storedRules.remove(rule);
600 if (storedRule != null) {
601 if (storedRule.exactMatch(rule)) {
602 // we both have the rule, let's update some info then.
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000603 done = flowAdded(rule);
604 if (!done) {
605 // Mastership change can occur during this iteration
606 master = mastershipService.getMasterFor(deviceId);
607 if (!Objects.equals(local, master)) {
608 log.warn("Tried to update the flow stats while the node was not the master");
609 return;
610 }
611 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700612 } else {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000613 // Mastership change can occur during this iteration
614 master = mastershipService.getMasterFor(deviceId);
615 if (!Objects.equals(local, master)) {
616 log.warn("Tried to update the flows while the node was not the master");
617 return;
618 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700619 // the two rules are not an exact match - remove the
620 // switch's rule and install our rule
621 extraneousFlow(rule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530622 flowMissing(storedRule, false);
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700623 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800624 } else {
625 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700626 if (!allowExtraneousRules) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000627 // Mastership change can occur during this iteration
628 master = mastershipService.getMasterFor(deviceId);
629 if (!Objects.equals(local, master)) {
630 log.warn("Tried to remove flows while the node was not the master");
631 return;
632 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700633 extraneousFlow(rule);
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100634 } else if (importExtraneousRules) { // Stores the rule, if so is indicated
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000635 FlowRuleEvent flowRuleEvent = store.addOrUpdateFlowRule(rule);
636 if (flowRuleEvent == null) {
637 // Mastership change can occur during this iteration
638 master = mastershipService.getMasterFor(deviceId);
639 if (!Objects.equals(local, master)) {
640 log.warn("Tried to import flows while the node was not the master");
641 return;
642 }
643 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700644 }
alshabib93cb57f2015-02-12 17:43:26 -0800645 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700646 } catch (Exception e) {
Jon Hall274cecb2017-08-09 12:15:48 -0700647 log.warn("Can't process added or extra rule {} for device {}:{}",
648 rule, deviceId, e);
alshabib93cb57f2015-02-12 17:43:26 -0800649 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800650 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900651
652 // DO NOT reinstall
653 if (useMissingFlow) {
654 for (FlowEntry rule : storedRules.keySet()) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000655 // Mastership change can occur during this iteration
656 master = mastershipService.getMasterFor(deviceId);
657 if (!Objects.equals(local, master)) {
658 log.warn("Tried to install missing rules while the node was not the master");
659 return;
660 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900661 try {
662 // there are rules in the store that aren't on the switch
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530663 log.debug("Adding the rule that is present in store but not on switch : {}", rule);
664 flowMissing(rule, true);
ssyoon9030fbcd92015-08-17 10:42:07 +0900665 } catch (Exception e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700666 log.warn("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900667 }
alshabib93cb57f2015-02-12 17:43:26 -0800668 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800669 }
alshabib5c370ff2014-09-18 10:12:14 -0700670 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800671
672 @Override
673 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
674 store.batchOperationComplete(FlowRuleBatchEvent.completed(
675 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
676 operation
677 ));
678 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700679
680 @Override
681 public void pushTableStatistics(DeviceId deviceId,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100682 List<TableStatisticsEntry> tableStats) {
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700683 store.updateTableStatistics(deviceId, tableStats);
684 }
alshabib57044ba2014-09-16 15:58:01 -0700685 }
686
tomc78acee2014-09-24 15:16:55 -0700687 // Store delegate to re-post events emitted from the store.
688 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800689
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800690
Madan Jampani117aaae2014-10-23 10:04:05 -0700691 // TODO: Right now we only dispatch events at individual flowEntry level.
692 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700693 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700694 public void notify(FlowRuleBatchEvent event) {
695 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700696 switch (event.type()) {
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100697 case BATCH_OPERATION_REQUESTED:
698 // Request has been forwarded to MASTER Node, and was
699 request.ops().forEach(
700 op -> {
701 switch (op.operator()) {
702 case ADD:
703 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
704 break;
705 case REMOVE:
706 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
707 break;
708 case MODIFY:
709 //TODO: do something here when the time comes.
710 break;
711 default:
712 log.warn("Unknown flow operation operator: {}", op.operator());
713 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800714 }
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100715 );
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800716
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100717 DeviceId deviceId = event.deviceId();
718 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
719 // getProvider is customized to favor driverProvider
720 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
721 if (flowRuleProvider != null) {
722 log.trace("Sending {} flow rules to {}", batchOperation.size(), deviceId);
723 flowRuleProvider.executeBatch(batchOperation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800724 }
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800725
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100726 break;
727
728 case BATCH_OPERATION_COMPLETED:
729 // Operation completed, let's retrieve the processor and trigger the callback
730 FlowOperationsProcessor fops = pendingFlowOperations.remove(
731 event.subject().batchId());
732 if (fops != null) {
733 if (event.result().isSuccess()) {
734 fops.satisfy(event.deviceId());
735 } else {
736 fops.fail(event.deviceId(), event.result().failedItems());
737 }
738 } else {
739 log.warn("Unable to find flow operations processor for batch: {}", event.subject().batchId());
740 }
741 break;
742
743 default:
744 break;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700745 }
tomc78acee2014-09-24 15:16:55 -0700746 }
747 }
alshabib902d41b2014-10-07 16:52:05 -0700748
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700749 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
750 switch (input) {
751 case ADD:
752 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
753 case MODIFY:
754 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
755 case REMOVE:
756 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
757 default:
758 throw new UnsupportedOperationException("Unknown flow rule type " + input);
759 }
760 }
761
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800762 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700763 // Immutable
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800764 private final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700765
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700766 // Mutable
767 private final List<Set<FlowRuleOperation>> stages;
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700768 private final Set<DeviceId> pendingDevices = new HashSet<>();
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700769 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700770
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700771 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800772 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800773 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700774 }
775
776 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700777 public synchronized void run() {
Jon Hallcbd1b392017-01-18 20:15:44 -0800778 if (!stages.isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800779 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700780 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700781 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700782 }
783 }
784
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800785 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700786 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800787
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700788 for (FlowRuleOperation op : ops) {
789 perDeviceBatches.put(op.rule().deviceId(),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100790 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800791 }
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000792 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800793
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800794 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700795 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800796 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100797 deviceId, id);
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000798 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700799 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700800 }
801 }
802
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700803 synchronized void satisfy(DeviceId devId) {
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000804 pendingDevices.remove(devId);
805 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700806 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700807 }
alshabib193525b2014-10-08 18:58:03 -0700808 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800809
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700810 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZUb9e0ab72016-09-14 16:54:13 -0700811 hasFailed = true;
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000812 pendingDevices.remove(devId);
813 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700814 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800815 }
816
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700817 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
818 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800819
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700820 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800821 }
alshabib902d41b2014-10-07 16:52:05 -0700822 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700823
824 @Override
825 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
826 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800827 checkNotNull(deviceId, DEVICE_ID_NULL);
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700828 return store.getTableStatistics(deviceId);
829 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800830
Patryk Konopka7e40c012017-06-06 13:38:06 +0200831 @Override
832 public long getActiveFlowRuleCount(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800833 checkNotNull(deviceId, DEVICE_ID_NULL);
Patryk Konopka7e40c012017-06-06 13:38:06 +0200834 return store.getActiveFlowRuleCount(deviceId);
835 }
836
Charles Chan0c7c43b2016-01-14 17:39:20 -0800837 private class InternalDeviceListener implements DeviceListener {
838 @Override
839 public void event(DeviceEvent event) {
840 switch (event.type()) {
841 case DEVICE_REMOVED:
842 case DEVICE_AVAILABILITY_CHANGED:
843 DeviceId deviceId = event.subject().id();
844 if (!deviceService.isAvailable(deviceId)) {
Andrea Campanella32a9c0b2020-03-27 12:53:46 +0100845 BasicDeviceConfig cfg = netCfgService.getConfig(deviceId, BasicDeviceConfig.class);
846 //if purgeOnDisconnection is set for the device or it's a global configuration
847 // lets remove the flows. Priority is given to the per device flag
848 boolean purge = cfg != null && cfg.isPurgeOnDisconnectionConfigured() ?
849 cfg.purgeOnDisconnection() : purgeOnDisconnection;
850 if (purge) {
851 log.info("PurgeOnDisconnection is requested for device {}, " +
852 "removing flows", deviceId);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800853 store.purgeFlowRule(deviceId);
854 }
855 }
856 break;
857 default:
858 break;
859 }
860 }
861 }
alshabib57044ba2014-09-16 15:58:01 -0700862}