blob: d601d8de4498fc162ebbb5eaf2fc53b0bd20a35f [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;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080034import org.onosproject.net.device.DeviceEvent;
35import org.onosproject.net.device.DeviceListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080036import org.onosproject.net.device.DeviceService;
Jordan Halterman4f3193a2017-07-11 20:32:49 -070037import org.onosproject.net.driver.DriverService;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.flow.CompletedBatchOperation;
Charles M.C. Chan1229eca2015-05-18 06:27:52 +080039import org.onosproject.net.flow.DefaultFlowEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.flow.FlowEntry;
41import org.onosproject.net.flow.FlowRule;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.flow.FlowRuleEvent;
43import org.onosproject.net.flow.FlowRuleListener;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080044import org.onosproject.net.flow.FlowRuleOperation;
45import org.onosproject.net.flow.FlowRuleOperations;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080046import org.onosproject.net.flow.FlowRuleProgrammable;
Brian O'Connorabafb502014-12-02 22:26:20 -080047import org.onosproject.net.flow.FlowRuleProvider;
48import org.onosproject.net.flow.FlowRuleProviderRegistry;
49import org.onosproject.net.flow.FlowRuleProviderService;
50import org.onosproject.net.flow.FlowRuleService;
51import org.onosproject.net.flow.FlowRuleStore;
52import org.onosproject.net.flow.FlowRuleStoreDelegate;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070053import org.onosproject.net.flow.TableStatisticsEntry;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070054import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry;
55import org.onosproject.net.flow.oldbatch.FlowRuleBatchEvent;
56import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation;
57import org.onosproject.net.flow.oldbatch.FlowRuleBatchRequest;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080058import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080059import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080060import org.onosproject.net.provider.ProviderId;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070061import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070062import org.osgi.service.component.annotations.Activate;
63import org.osgi.service.component.annotations.Component;
64import org.osgi.service.component.annotations.Deactivate;
65import org.osgi.service.component.annotations.Modified;
66import org.osgi.service.component.annotations.Reference;
67import org.osgi.service.component.annotations.ReferenceCardinality;
alshabib57044ba2014-09-16 15:58:01 -070068import org.slf4j.Logger;
69
Brian O'Connord12267c2015-02-17 18:17:08 -080070import java.util.Collections;
Marc De Leenheerde47caa2015-04-24 11:27:44 -070071import java.util.Dictionary;
Sho SHIMIZUb837cb72016-08-30 14:44:50 -070072import java.util.HashSet;
Brian O'Connord12267c2015-02-17 18:17:08 -080073import java.util.List;
74import java.util.Map;
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +000075import java.util.Objects;
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -080076import java.util.Optional;
Brian O'Connord12267c2015-02-17 18:17:08 -080077import java.util.Set;
78import java.util.concurrent.ConcurrentHashMap;
79import java.util.concurrent.ExecutorService;
80import java.util.concurrent.Executors;
Brian O'Connor72cb19a2015-01-16 16:14:41 -080081
Thomas Vachuska9b2da212014-11-10 19:30:25 -080082import static com.google.common.base.Preconditions.checkNotNull;
Charles Chan0c7c43b2016-01-14 17:39:20 -080083import static com.google.common.base.Strings.isNullOrEmpty;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080084import static org.onlab.util.Tools.get;
Brian O'Connord12267c2015-02-17 18:17:08 -080085import static org.onlab.util.Tools.groupedThreads;
Ray Milkeyd04e2272018-10-16 18:20:18 -070086import static org.onosproject.net.OsgiPropertyConstants.ALLOW_EXTRANEOUS_RULES;
87import static org.onosproject.net.OsgiPropertyConstants.ALLOW_EXTRANEOUS_RULES_DEFAULT;
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +010088import static org.onosproject.net.OsgiPropertyConstants.IMPORT_EXTRANEOUS_RULES;
89import static org.onosproject.net.OsgiPropertyConstants.IMPORT_EXTRANEOUS_RULES_DEFAULT;
Ray Milkeyd04e2272018-10-16 18:20:18 -070090import static org.onosproject.net.OsgiPropertyConstants.POLL_FREQUENCY;
91import static org.onosproject.net.OsgiPropertyConstants.POLL_FREQUENCY_DEFAULT;
92import static org.onosproject.net.OsgiPropertyConstants.PURGE_ON_DISCONNECTION;
93import static org.onosproject.net.OsgiPropertyConstants.PURGE_ON_DISCONNECTION_DEFAULT;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070094import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_ADD_REQUESTED;
95import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVE_REQUESTED;
Changhoon Yoon541ef712015-05-23 17:18:34 +090096import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuskac4ee7372016-02-02 16:10:09 -080097import static org.onosproject.security.AppPermission.Type.FLOWRULE_READ;
98import static org.onosproject.security.AppPermission.Type.FLOWRULE_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070099import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +0900100
tome4729872014-09-23 00:37:37 -0700101/**
102 * Provides implementation of the flow NB & SB APIs.
103 */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700104@Component(
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100105 immediate = true,
106 service = {
107 FlowRuleService.class,
108 FlowRuleProviderRegistry.class
109 },
110 property = {
111 ALLOW_EXTRANEOUS_RULES + ":Boolean=" + ALLOW_EXTRANEOUS_RULES_DEFAULT,
112 IMPORT_EXTRANEOUS_RULES + ":Boolean=" + IMPORT_EXTRANEOUS_RULES_DEFAULT,
113 PURGE_ON_DISCONNECTION + ":Boolean=" + PURGE_ON_DISCONNECTION_DEFAULT,
114 POLL_FREQUENCY + ":Integer=" + POLL_FREQUENCY_DEFAULT
115 }
Ray Milkeyd04e2272018-10-16 18:20:18 -0700116)
tom202175a2014-09-19 19:00:11 -0700117public class FlowRuleManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700118 extends AbstractListenerProviderRegistry<FlowRuleEvent, FlowRuleListener,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100119 FlowRuleProvider, FlowRuleProviderService>
tom9b4030d2014-10-06 10:39:03 -0700120 implements FlowRuleService, FlowRuleProviderRegistry {
alshabib57044ba2014-09-16 15:58:01 -0700121
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800122 private final Logger log = getLogger(getClass());
123
Thomas Vachuska227943d2018-03-19 09:37:28 -0700124 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
125 private static final String FLOW_RULE_NULL = "FlowRule cannot be null";
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700126
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700127 /** Allow flow rules in switch not installed by ONOS. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700128 private boolean allowExtraneousRules = ALLOW_EXTRANEOUS_RULES_DEFAULT;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700129
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100130 /** Allow to import flow rules in switch not installed by ONOS. */
131 private boolean importExtraneousRules = IMPORT_EXTRANEOUS_RULES_DEFAULT;
132
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700133 /** Purge entries associated with a device when the device goes offline. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700134 private boolean purgeOnDisconnection = PURGE_ON_DISCONNECTION_DEFAULT;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800135
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700136 /** Frequency (in seconds) for polling flow statistics via fallback provider. */
Ray Milkeyd04e2272018-10-16 18:20:18 -0700137 private int fallbackFlowPollFrequency = POLL_FREQUENCY_DEFAULT;
alshabib57044ba2014-09-16 15:58:01 -0700138
alshabibbb42cad2014-09-25 11:43:05 -0700139 private final FlowRuleStoreDelegate delegate = new InternalStoreDelegate();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800140 private final DeviceListener deviceListener = new InternalDeviceListener();
tomc78acee2014-09-24 15:16:55 -0700141
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800142 private final FlowRuleDriverProvider driverProvider = new FlowRuleDriverProvider();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800143
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800144 protected ExecutorService deviceInstallers =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800145 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "device-installer-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800146
147 protected ExecutorService operationsService =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700148 Executors.newFixedThreadPool(32, groupedThreads("onos/flowservice", "operations-%d", log));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800149
150 private IdGenerator idGenerator;
151
Sho SHIMIZU9f950742016-09-01 09:55:38 -0700152 private final Map<Long, FlowOperationsProcessor> pendingFlowOperations = new ConcurrentHashMap<>();
Yuta HIGUCHI9def0472014-10-23 15:51:10 -0700153
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000154 private NodeId local;
155
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700156 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tombe988312014-09-19 18:38:47 -0700157 protected FlowRuleStore store;
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700158
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibeb55524f2014-09-18 09:59:24 -0700160 protected DeviceService deviceService;
alshabib57044ba2014-09-16 15:58:01 -0700161
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800163 protected CoreService coreService;
164
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800166 protected MastershipService mastershipService;
167
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700168 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700169 protected ComponentConfigService cfgService;
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800170
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700171 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman4f3193a2017-07-11 20:32:49 -0700172 protected DriverService driverService;
173
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000174 @Reference(cardinality = ReferenceCardinality.MANDATORY)
175 protected ClusterService clusterService;
176
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700177 @Activate
178 public void activate(ComponentContext context) {
tomc78acee2014-09-24 15:16:55 -0700179 store.setDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700180 eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800181 deviceService.addListener(deviceListener);
182 cfgService.registerProperties(getClass());
piered2a0a42019-04-16 11:48:08 +0200183 modified(context);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800184 idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000185 local = clusterService.getLocalNode().id();
alshabib57044ba2014-09-16 15:58:01 -0700186 log.info("Started");
187 }
188
189 @Deactivate
190 public void deactivate() {
Andrea Campanella5a3c09c2017-12-01 13:57:48 +0100191 driverProvider.terminate();
Andrea Campanella3f1c61e2016-04-01 17:30:12 -0700192 deviceService.removeListener(deviceListener);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700193 cfgService.unregisterProperties(getClass(), false);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800194 deviceInstallers.shutdownNow();
195 operationsService.shutdownNow();
tomc78acee2014-09-24 15:16:55 -0700196 store.unsetDelegate(delegate);
alshabib57044ba2014-09-16 15:58:01 -0700197 eventDispatcher.removeSink(FlowRuleEvent.class);
198 log.info("Stopped");
199 }
200
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700201 @Modified
202 public void modified(ComponentContext context) {
Charles Chan0c7c43b2016-01-14 17:39:20 -0800203 if (context != null) {
204 readComponentConfiguration(context);
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700205 }
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800206 driverProvider.init(new InternalFlowRuleProviderService(driverProvider),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100207 deviceService, mastershipService, fallbackFlowPollFrequency);
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800208 }
209
210 @Override
211 protected FlowRuleProvider defaultProvider() {
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800212 return driverProvider;
Charles Chan0c7c43b2016-01-14 17:39:20 -0800213 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700214
Charles Chan0c7c43b2016-01-14 17:39:20 -0800215 /**
216 * Extracts properties from the component configuration context.
217 *
218 * @param context the component context
219 */
220 private void readComponentConfiguration(ComponentContext context) {
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700221 Dictionary<?, ?> properties = context.getProperties();
Charles Chan0c7c43b2016-01-14 17:39:20 -0800222 Boolean flag;
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700223
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700224 flag = Tools.isPropertyEnabled(properties, ALLOW_EXTRANEOUS_RULES);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800225 if (flag == null) {
226 log.info("AllowExtraneousRules is not configured, " +
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100227 "using current value of {}", allowExtraneousRules);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800228 } else {
229 allowExtraneousRules = flag;
230 log.info("Configured. AllowExtraneousRules is {}",
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100231 allowExtraneousRules ? "enabled" : "disabled");
232 }
233
234 flag = Tools.isPropertyEnabled(properties, IMPORT_EXTRANEOUS_RULES);
235 if (flag == null) {
236 log.info("ImportExtraneousRules is not configured, " +
237 "using current value of {}", importExtraneousRules);
238 } else {
239 importExtraneousRules = flag;
240 log.info("Configured. importExtraneousRules is {}",
241 importExtraneousRules ? "enabled" : "disabled");
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700242 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800243
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700244 flag = Tools.isPropertyEnabled(properties, PURGE_ON_DISCONNECTION);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800245 if (flag == null) {
246 log.info("PurgeOnDisconnection is not configured, " +
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100247 "using current value of {}", purgeOnDisconnection);
Charles Chan0c7c43b2016-01-14 17:39:20 -0800248 } else {
249 purgeOnDisconnection = flag;
250 log.info("Configured. PurgeOnDisconnection is {}",
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100251 purgeOnDisconnection ? "enabled" : "disabled");
Charles Chan0c7c43b2016-01-14 17:39:20 -0800252 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800253
Thomas Vachuskaf566fa22018-10-30 14:03:36 -0700254 String s = get(properties, POLL_FREQUENCY);
Carmelo Casconee6a97542018-06-20 16:48:00 +0200255 if (isNullOrEmpty(s)) {
256 log.info("fallbackFlowPollFrequency is not configured, " +
257 "using current value of {} seconds",
258 fallbackFlowPollFrequency);
259 } else {
260 try {
261 fallbackFlowPollFrequency = Integer.parseInt(s);
262 log.info("Configured. FallbackFlowPollFrequency is {} seconds",
263 fallbackFlowPollFrequency);
264 } catch (NumberFormatException e) {
265 log.warn("Configured fallbackFlowPollFrequency value '{}' " +
266 "is not a number, using current value of {} seconds",
267 fallbackFlowPollFrequency);
268 }
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800269 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800270 }
271
alshabib57044ba2014-09-16 15:58:01 -0700272 @Override
tom9b4030d2014-10-06 10:39:03 -0700273 public int getFlowRuleCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900274 checkPermission(FLOWRULE_READ);
tom9b4030d2014-10-06 10:39:03 -0700275 return store.getFlowRuleCount();
276 }
277
278 @Override
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800279 public int getFlowRuleCount(DeviceId deviceId) {
280 checkPermission(FLOWRULE_READ);
Thomas Vachuska227943d2018-03-19 09:37:28 -0700281 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800282 return store.getFlowRuleCount(deviceId);
283 }
284
285 @Override
Jordan Haltermanb81fdc12019-03-04 18:12:20 -0800286 public int getFlowRuleCount(DeviceId deviceId, FlowEntry.FlowEntryState state) {
287 checkPermission(FLOWRULE_READ);
288 checkNotNull(deviceId, "Device ID cannot be null");
289 return store.getFlowRuleCount(deviceId, state);
290 }
291
292 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700293 public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900294 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800295 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700296 return store.getFlowEntries(deviceId);
alshabib57044ba2014-09-16 15:58:01 -0700297 }
298
299 @Override
alshabib219ebaa2014-09-22 15:41:24 -0700300 public void applyFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900301 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900302
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800303 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800304 for (FlowRule flowRule : flowRules) {
305 builder.add(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700306 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800307 apply(builder.build());
alshabib57044ba2014-09-16 15:58:01 -0700308 }
309
310 @Override
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530311 public void purgeFlowRules(DeviceId deviceId) {
312 checkPermission(FLOWRULE_WRITE);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800313 checkNotNull(deviceId, DEVICE_ID_NULL);
Kavitha Alagesanc69c66a2016-06-15 14:26:04 +0530314 store.purgeFlowRule(deviceId);
315 }
316
317 @Override
alshabib57044ba2014-09-16 15:58:01 -0700318 public void removeFlowRules(FlowRule... flowRules) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900319 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900320
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800321 FlowRuleOperations.Builder builder = FlowRuleOperations.builder();
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800322 for (FlowRule flowRule : flowRules) {
323 builder.remove(flowRule);
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700324 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800325 apply(builder.build());
alshabiba68eb962014-09-24 20:34:13 -0700326 }
alshabib57044ba2014-09-16 15:58:01 -0700327
alshabiba68eb962014-09-24 20:34:13 -0700328 @Override
329 public void removeFlowRulesById(ApplicationId id) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900330 checkPermission(FLOWRULE_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900331
Madan Jampani6a456162014-10-24 11:36:17 -0700332 Set<FlowRule> flowEntries = Sets.newHashSet();
333 for (Device d : deviceService.getDevices()) {
334 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
335 if (flowEntry.appId() == id.id()) {
336 flowEntries.add(flowEntry);
337 }
338 }
339 }
Ray Milkey4f7e3632019-02-19 15:35:20 -0800340 removeFlowRules(Iterables.toArray(flowEntries, FlowRule.class));
alshabib57044ba2014-09-16 15:58:01 -0700341 }
342
343 @Override
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530344 public Iterable<FlowEntry> getFlowEntriesById(ApplicationId id) {
345 checkPermission(FLOWRULE_READ);
346
347 Set<FlowEntry> flowEntries = Sets.newHashSet();
348 for (Device d : deviceService.getDevices()) {
349 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
350 if (flowEntry.appId() == id.id()) {
351 flowEntries.add(flowEntry);
352 }
353 }
354 }
355 return flowEntries;
356 }
357
358 @Override
alshabibaa7e7de2014-11-12 19:20:44 -0800359 public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900360 checkPermission(FLOWRULE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900361
alshabibaa7e7de2014-11-12 19:20:44 -0800362 Set<FlowRule> matches = Sets.newHashSet();
363 long toLookUp = ((long) appId.id() << 16) | groupId;
364 for (Device d : deviceService.getDevices()) {
365 for (FlowEntry flowEntry : store.getFlowEntries(d.id())) {
366 if ((flowEntry.id().value() >>> 32) == toLookUp) {
367 matches.add(flowEntry);
368 }
369 }
370 }
371 return matches;
372 }
373
374 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800375 public void apply(FlowRuleOperations ops) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900376 checkPermission(FLOWRULE_WRITE);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700377 operationsService.execute(new FlowOperationsProcessor(ops));
alshabib902d41b2014-10-07 16:52:05 -0700378 }
379
380 @Override
alshabib57044ba2014-09-16 15:58:01 -0700381 protected FlowRuleProviderService createProviderService(
382 FlowRuleProvider provider) {
383 return new InternalFlowRuleProviderService(provider);
384 }
385
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800386 @Override
387 protected synchronized FlowRuleProvider getProvider(ProviderId pid) {
388 log.warn("should not be calling getProvider(ProviderId)");
389 return super.getProvider(pid);
390 }
391
392 /**
393 * {@inheritDoc}
394 * if the Device does not support {@link FlowRuleProgrammable}.
395 */
396 @Override
397 protected synchronized FlowRuleProvider getProvider(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800398 checkNotNull(deviceId, DEVICE_ID_NULL);
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800399 // if device supports FlowRuleProgrammable,
400 // use FlowRuleProgrammable via FlowRuleDriverProvider
401 return Optional.ofNullable(deviceService.getDevice(deviceId))
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100402 .filter(dev -> dev.is(FlowRuleProgrammable.class))
403 .<FlowRuleProvider>map(x -> driverProvider)
404 .orElseGet(() -> super.getProvider(deviceId));
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800405 }
406
alshabib57044ba2014-09-16 15:58:01 -0700407 private class InternalFlowRuleProviderService
tom9b4030d2014-10-06 10:39:03 -0700408 extends AbstractProviderService<FlowRuleProvider>
409 implements FlowRuleProviderService {
alshabib57044ba2014-09-16 15:58:01 -0700410
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700411 final Map<FlowEntry, Long> firstSeen = Maps.newConcurrentMap();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700412 final Map<FlowEntry, Long> lastSeen = Maps.newConcurrentMap();
413
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700414
alshabib57044ba2014-09-16 15:58:01 -0700415 protected InternalFlowRuleProviderService(FlowRuleProvider provider) {
416 super(provider);
417 }
418
419 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700420 public void flowRemoved(FlowEntry flowEntry) {
421 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700422 checkValidity();
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700423 lastSeen.remove(flowEntry);
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700424 firstSeen.remove(flowEntry);
alshabib1c319ff2014-10-04 20:29:09 -0700425 FlowEntry stored = store.getFlowEntry(flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700426 if (stored == null) {
Yuta HIGUCHI82e53262014-11-27 10:28:51 -0800427 log.debug("Rule already evicted from store: {}", flowEntry);
alshabiba68eb962014-09-24 20:34:13 -0700428 return;
429 }
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700430 if (flowEntry.reason() == FlowEntry.FlowRemoveReason.HARD_TIMEOUT) {
431 ((DefaultFlowEntry) stored).setState(FlowEntry.FlowEntryState.REMOVED);
432 }
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800433 FlowRuleProvider frp = getProvider(flowEntry.deviceId());
alshabiba68eb962014-09-24 20:34:13 -0700434 FlowRuleEvent event = null;
435 switch (stored.state()) {
tom9b4030d2014-10-06 10:39:03 -0700436 case ADDED:
437 case PENDING_ADD:
alshabib6eb438a2014-10-01 16:39:37 -0700438 frp.applyFlowRule(stored);
tom9b4030d2014-10-06 10:39:03 -0700439 break;
440 case PENDING_REMOVE:
441 case REMOVED:
442 event = store.removeFlowRule(stored);
443 break;
444 default:
445 break;
alshabib57044ba2014-09-16 15:58:01 -0700446
alshabiba68eb962014-09-24 20:34:13 -0700447 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700448 if (event != null) {
alshabib1c319ff2014-10-04 20:29:09 -0700449 log.debug("Flow {} removed", flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700450 post(event);
451 }
alshabib57044ba2014-09-16 15:58:01 -0700452 }
453
alshabibba5ac482014-10-02 17:15:20 -0700454
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530455 private void flowMissing(FlowEntry flowRule, boolean isFlowOnlyInStore) {
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700456 checkNotNull(flowRule, FLOW_RULE_NULL);
457 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800458 FlowRuleProvider frp = getProvider(flowRule.deviceId());
alshabibbb42cad2014-09-25 11:43:05 -0700459 FlowRuleEvent event = null;
alshabiba68eb962014-09-24 20:34:13 -0700460 switch (flowRule.state()) {
tom9b4030d2014-10-06 10:39:03 -0700461 case PENDING_REMOVE:
462 case REMOVED:
463 event = store.removeFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530464 log.debug("Flow {} removed", flowRule);
tom9b4030d2014-10-06 10:39:03 -0700465 break;
466 case ADDED:
467 case PENDING_ADD:
Charles Chan93fa7272016-01-26 22:27:02 -0800468 event = store.pendingFlowRule(flowRule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530469 if (isFlowOnlyInStore) {
470 // Publishing RULE_ADD_REQUESTED event facilitates
471 // preparation of statistics for the concerned rule
472 if (event == null) {
473 event = new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADD_REQUESTED, flowRule);
474 }
475 }
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800476 try {
477 frp.applyFlowRule(flowRule);
478 } catch (UnsupportedOperationException e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700479 log.warn("Unsupported operation", e);
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800480 if (flowRule instanceof DefaultFlowEntry) {
Brian O'Connora3e5cd52015-12-05 15:59:19 -0800481 //FIXME modification of "stored" flow entry outside of store
Charles M.C. Chan1229eca2015-05-18 06:27:52 +0800482 ((DefaultFlowEntry) flowRule).setState(FlowEntry.FlowEntryState.FAILED);
483 }
484 }
tom9b4030d2014-10-06 10:39:03 -0700485 break;
486 default:
487 log.debug("Flow {} has not been installed.", flowRule);
alshabiba68eb962014-09-24 20:34:13 -0700488 }
489
alshabibbb42cad2014-09-25 11:43:05 -0700490 if (event != null) {
alshabibbb42cad2014-09-25 11:43:05 -0700491 post(event);
492 }
alshabib57044ba2014-09-16 15:58:01 -0700493 }
494
alshabibba5ac482014-10-02 17:15:20 -0700495 private void extraneousFlow(FlowRule flowRule) {
alshabib219ebaa2014-09-22 15:41:24 -0700496 checkNotNull(flowRule, FLOW_RULE_NULL);
497 checkValidity();
Yuta HIGUCHI48dcd372017-02-27 22:55:53 -0800498 // getProvider is customized to favor driverProvider
alshabib2374fc92014-10-22 11:03:23 -0700499 FlowRuleProvider frp = getProvider(flowRule.deviceId());
500 frp.removeFlowRule(flowRule);
alshabib54ce5892014-09-23 17:50:51 -0700501 log.debug("Flow {} is on switch but not in store.", flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700502 }
503
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000504 private boolean flowAdded(FlowEntry flowEntry) {
alshabib1c319ff2014-10-04 20:29:09 -0700505 checkNotNull(flowEntry, FLOW_RULE_NULL);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700506 checkValidity();
alshabib57044ba2014-09-16 15:58:01 -0700507
alshabib1c319ff2014-10-04 20:29:09 -0700508 if (checkRuleLiveness(flowEntry, store.getFlowEntry(flowEntry))) {
alshabib1c319ff2014-10-04 20:29:09 -0700509 FlowRuleEvent event = store.addOrUpdateFlowRule(flowEntry);
alshabibba5ac482014-10-02 17:15:20 -0700510 if (event == null) {
511 log.debug("No flow store event generated.");
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000512 return false;
alshabibba5ac482014-10-02 17:15:20 -0700513 } else {
Jonathan Hart58682dd2014-11-24 20:11:16 -0800514 log.trace("Flow {} {}", flowEntry, event.type());
alshabibba5ac482014-10-02 17:15:20 -0700515 post(event);
516 }
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700517 } else {
Thomas Vachuska4830d392014-11-09 17:09:56 -0800518 log.debug("Removing flow rules....");
alshabib1c319ff2014-10-04 20:29:09 -0700519 removeFlowRules(flowEntry);
Ayaka Koshibe08eabaa2014-09-17 14:59:25 -0700520 }
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000521 return true;
alshabib57044ba2014-09-16 15:58:01 -0700522 }
523
alshabib1c319ff2014-10-04 20:29:09 -0700524 private boolean checkRuleLiveness(FlowEntry swRule, FlowEntry storedRule) {
525 if (storedRule == null) {
526 return false;
527 }
Jonathan Hartbc4a7932014-10-21 11:46:00 -0700528 if (storedRule.isPermanent()) {
529 return true;
530 }
531
Ray Milkey3717e602018-02-01 13:49:47 -0800532 final long timeout = storedRule.timeout() * 1000L;
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700533 final long currentTime = System.currentTimeMillis();
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700534
535 // Checking flow with hardTimeout
536 if (storedRule.hardTimeout() != 0) {
537 if (!firstSeen.containsKey(storedRule)) {
538 // First time rule adding
539 firstSeen.put(storedRule, currentTime);
540 } else {
541 Long first = firstSeen.get(storedRule);
Ray Milkey3717e602018-02-01 13:49:47 -0800542 final long hardTimeout = storedRule.hardTimeout() * 1000L;
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700543 if ((currentTime - first) > hardTimeout) {
544 return false;
545 }
546 }
547 }
548
Gamze Abaka8d03f182017-07-20 15:09:24 +0000549 if (storedRule.packets() != swRule.packets() || storedRule.bytes() != swRule.bytes()) {
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700550 lastSeen.put(storedRule, currentTime);
alshabib85c41972014-10-03 13:48:39 -0700551 return true;
552 }
Yuta HIGUCHIf6f50a62014-10-19 15:58:49 -0700553 if (!lastSeen.containsKey(storedRule)) {
554 // checking for the first time
555 lastSeen.put(storedRule, storedRule.lastSeen());
556 // Use following if lastSeen attr. was removed.
557 //lastSeen.put(storedRule, currentTime);
558 }
559 Long last = lastSeen.get(storedRule);
alshabib85c41972014-10-03 13:48:39 -0700560
Thomas Vachuskac4ee7372016-02-02 16:10:09 -0800561 // concurrently removed? let the liveness check fail
562 return last != null && (currentTime - last) <= timeout;
alshabibba5ac482014-10-02 17:15:20 -0700563 }
564
alshabib5c370ff2014-09-18 10:12:14 -0700565 @Override
alshabib1c319ff2014-10-04 20:29:09 -0700566 public void pushFlowMetrics(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900567 pushFlowMetricsInternal(deviceId, flowEntries, true);
568 }
569
570 @Override
571 public void pushFlowMetricsWithoutFlowMissing(DeviceId deviceId, Iterable<FlowEntry> flowEntries) {
572 pushFlowMetricsInternal(deviceId, flowEntries, false);
573 }
574
575 private void pushFlowMetricsInternal(DeviceId deviceId, Iterable<FlowEntry> flowEntries,
576 boolean useMissingFlow) {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700577 Map<FlowEntry, FlowEntry> storedRules = Maps.newHashMap();
578 store.getFlowEntries(deviceId).forEach(f -> storedRules.put(f, f));
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000579 NodeId master;
580 boolean done;
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700581
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000582 // Processing flow rules
Saurav Dasfa2fa932015-03-03 11:29:48 -0800583 for (FlowEntry rule : flowEntries) {
584 try {
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700585 FlowEntry storedRule = storedRules.remove(rule);
586 if (storedRule != null) {
587 if (storedRule.exactMatch(rule)) {
588 // we both have the rule, let's update some info then.
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000589 done = flowAdded(rule);
590 if (!done) {
591 // Mastership change can occur during this iteration
592 master = mastershipService.getMasterFor(deviceId);
593 if (!Objects.equals(local, master)) {
594 log.warn("Tried to update the flow stats while the node was not the master");
595 return;
596 }
597 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700598 } else {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000599 // Mastership change can occur during this iteration
600 master = mastershipService.getMasterFor(deviceId);
601 if (!Objects.equals(local, master)) {
602 log.warn("Tried to update the flows while the node was not the master");
603 return;
604 }
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700605 // the two rules are not an exact match - remove the
606 // switch's rule and install our rule
607 extraneousFlow(rule);
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530608 flowMissing(storedRule, false);
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700609 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800610 } else {
611 // the device has a rule the store does not have
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700612 if (!allowExtraneousRules) {
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 remove flows while the node was not the master");
617 return;
618 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700619 extraneousFlow(rule);
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100620 } else if (importExtraneousRules) { // Stores the rule, if so is indicated
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000621 FlowRuleEvent flowRuleEvent = store.addOrUpdateFlowRule(rule);
622 if (flowRuleEvent == null) {
623 // Mastership change can occur during this iteration
624 master = mastershipService.getMasterFor(deviceId);
625 if (!Objects.equals(local, master)) {
626 log.warn("Tried to import flows while the node was not the master");
627 return;
628 }
629 }
Marc De Leenheerde47caa2015-04-24 11:27:44 -0700630 }
alshabib93cb57f2015-02-12 17:43:26 -0800631 }
Sho SHIMIZU24a00d92015-05-05 11:11:13 -0700632 } catch (Exception e) {
Jon Hall274cecb2017-08-09 12:15:48 -0700633 log.warn("Can't process added or extra rule {} for device {}:{}",
634 rule, deviceId, e);
alshabib93cb57f2015-02-12 17:43:26 -0800635 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800636 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900637
638 // DO NOT reinstall
639 if (useMissingFlow) {
640 for (FlowEntry rule : storedRules.keySet()) {
Pier Luigi Ventred8a923c2020-02-20 11:25:31 +0000641 // Mastership change can occur during this iteration
642 master = mastershipService.getMasterFor(deviceId);
643 if (!Objects.equals(local, master)) {
644 log.warn("Tried to install missing rules while the node was not the master");
645 return;
646 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900647 try {
648 // there are rules in the store that aren't on the switch
Sivachidambaram Subramanian605104e2017-06-21 07:40:04 +0530649 log.debug("Adding the rule that is present in store but not on switch : {}", rule);
650 flowMissing(rule, true);
ssyoon9030fbcd92015-08-17 10:42:07 +0900651 } catch (Exception e) {
Yuta HIGUCHIf76f6d52017-05-15 18:02:09 -0700652 log.warn("Can't add missing flow rule:", e);
ssyoon9030fbcd92015-08-17 10:42:07 +0900653 }
alshabib93cb57f2015-02-12 17:43:26 -0800654 }
Saurav Dasfa2fa932015-03-03 11:29:48 -0800655 }
alshabib5c370ff2014-09-18 10:12:14 -0700656 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800657
658 @Override
659 public void batchOperationCompleted(long batchId, CompletedBatchOperation operation) {
660 store.batchOperationComplete(FlowRuleBatchEvent.completed(
661 new FlowRuleBatchRequest(batchId, Collections.emptySet()),
662 operation
663 ));
664 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700665
666 @Override
667 public void pushTableStatistics(DeviceId deviceId,
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100668 List<TableStatisticsEntry> tableStats) {
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700669 store.updateTableStatistics(deviceId, tableStats);
670 }
alshabib57044ba2014-09-16 15:58:01 -0700671 }
672
tomc78acee2014-09-24 15:16:55 -0700673 // Store delegate to re-post events emitted from the store.
674 private class InternalStoreDelegate implements FlowRuleStoreDelegate {
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800675
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800676
Madan Jampani117aaae2014-10-23 10:04:05 -0700677 // TODO: Right now we only dispatch events at individual flowEntry level.
678 // It may be more efficient for also dispatch events as a batch.
tomc78acee2014-09-24 15:16:55 -0700679 @Override
Madan Jampani117aaae2014-10-23 10:04:05 -0700680 public void notify(FlowRuleBatchEvent event) {
681 final FlowRuleBatchRequest request = event.subject();
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700682 switch (event.type()) {
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100683 case BATCH_OPERATION_REQUESTED:
684 // Request has been forwarded to MASTER Node, and was
685 request.ops().forEach(
686 op -> {
687 switch (op.operator()) {
688 case ADD:
689 post(new FlowRuleEvent(RULE_ADD_REQUESTED, op.target()));
690 break;
691 case REMOVE:
692 post(new FlowRuleEvent(RULE_REMOVE_REQUESTED, op.target()));
693 break;
694 case MODIFY:
695 //TODO: do something here when the time comes.
696 break;
697 default:
698 log.warn("Unknown flow operation operator: {}", op.operator());
699 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800700 }
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100701 );
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800702
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100703 DeviceId deviceId = event.deviceId();
704 FlowRuleBatchOperation batchOperation = request.asBatchOperation(deviceId);
705 // getProvider is customized to favor driverProvider
706 FlowRuleProvider flowRuleProvider = getProvider(deviceId);
707 if (flowRuleProvider != null) {
708 log.trace("Sending {} flow rules to {}", batchOperation.size(), deviceId);
709 flowRuleProvider.executeBatch(batchOperation);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800710 }
Yuta HIGUCHI2fcb40c2014-11-03 14:39:10 -0800711
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100712 break;
713
714 case BATCH_OPERATION_COMPLETED:
715 // Operation completed, let's retrieve the processor and trigger the callback
716 FlowOperationsProcessor fops = pendingFlowOperations.remove(
717 event.subject().batchId());
718 if (fops != null) {
719 if (event.result().isSuccess()) {
720 fops.satisfy(event.deviceId());
721 } else {
722 fops.fail(event.deviceId(), event.result().failedItems());
723 }
724 } else {
725 log.warn("Unable to find flow operations processor for batch: {}", event.subject().batchId());
726 }
727 break;
728
729 default:
730 break;
Yuta HIGUCHIf3d51bd2014-10-21 01:05:33 -0700731 }
tomc78acee2014-09-24 15:16:55 -0700732 }
733 }
alshabib902d41b2014-10-07 16:52:05 -0700734
Sho SHIMIZU5711ce12016-08-31 13:57:12 -0700735 private static FlowRuleBatchEntry.FlowRuleOperation mapOperationType(FlowRuleOperation.Type input) {
736 switch (input) {
737 case ADD:
738 return FlowRuleBatchEntry.FlowRuleOperation.ADD;
739 case MODIFY:
740 return FlowRuleBatchEntry.FlowRuleOperation.MODIFY;
741 case REMOVE:
742 return FlowRuleBatchEntry.FlowRuleOperation.REMOVE;
743 default:
744 throw new UnsupportedOperationException("Unknown flow rule type " + input);
745 }
746 }
747
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800748 private class FlowOperationsProcessor implements Runnable {
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700749 // Immutable
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800750 private final FlowRuleOperations fops;
alshabib902d41b2014-10-07 16:52:05 -0700751
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700752 // Mutable
753 private final List<Set<FlowRuleOperation>> stages;
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700754 private final Set<DeviceId> pendingDevices = new HashSet<>();
Sho SHIMIZU5f709422016-09-07 09:54:46 -0700755 private boolean hasFailed = false;
alshabib902d41b2014-10-07 16:52:05 -0700756
Sho SHIMIZU7c9b73a2016-08-30 14:08:28 -0700757 FlowOperationsProcessor(FlowRuleOperations ops) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800758 this.stages = Lists.newArrayList(ops.stages());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800759 this.fops = ops;
alshabib902d41b2014-10-07 16:52:05 -0700760 }
761
762 @Override
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700763 public synchronized void run() {
Jon Hallcbd1b392017-01-18 20:15:44 -0800764 if (!stages.isEmpty()) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800765 process(stages.remove(0));
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700766 } else if (!hasFailed) {
Sho SHIMIZUc9e4bb02016-09-01 12:43:39 -0700767 fops.callback().onSuccess(fops);
alshabib193525b2014-10-08 18:58:03 -0700768 }
769 }
770
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800771 private void process(Set<FlowRuleOperation> ops) {
Sho SHIMIZU8efc8962016-08-31 15:17:44 -0700772 Multimap<DeviceId, FlowRuleBatchEntry> perDeviceBatches = ArrayListMultimap.create();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800773
Sho SHIMIZUf4fd3de2016-08-31 15:47:56 -0700774 for (FlowRuleOperation op : ops) {
775 perDeviceBatches.put(op.rule().deviceId(),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100776 new FlowRuleBatchEntry(mapOperationType(op.type()), op.rule()));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800777 }
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000778 pendingDevices.addAll(perDeviceBatches.keySet());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800779
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800780 for (DeviceId deviceId : perDeviceBatches.keySet()) {
Sho SHIMIZU3a704312015-05-27 13:36:01 -0700781 long id = idGenerator.getNewId();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800782 final FlowRuleBatchOperation b = new FlowRuleBatchOperation(perDeviceBatches.get(deviceId),
Ivan Eroshkin3f56eb12019-11-25 10:38:56 +0100783 deviceId, id);
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000784 pendingFlowOperations.put(id, this);
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700785 deviceInstallers.execute(() -> store.storeBatch(b));
alshabib193525b2014-10-08 18:58:03 -0700786 }
787 }
788
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700789 synchronized void satisfy(DeviceId devId) {
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000790 pendingDevices.remove(devId);
791 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700792 operationsService.execute(this);
alshabib193525b2014-10-08 18:58:03 -0700793 }
alshabib193525b2014-10-08 18:58:03 -0700794 }
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800795
Sho SHIMIZU2d7c5392016-08-30 14:14:39 -0700796 synchronized void fail(DeviceId devId, Set<? extends FlowRule> failures) {
Sho SHIMIZUb9e0ab72016-09-14 16:54:13 -0700797 hasFailed = true;
Brian O'Connorc9b64dc2016-09-13 23:01:07 +0000798 pendingDevices.remove(devId);
799 if (pendingDevices.isEmpty()) {
Sho SHIMIZUc0bfe7c2016-09-14 16:54:30 -0700800 operationsService.execute(this);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800801 }
802
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700803 FlowRuleOperations.Builder failedOpsBuilder = FlowRuleOperations.builder();
804 failures.forEach(failedOpsBuilder::add);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800805
Sho SHIMIZUad4f2cd2016-09-01 13:05:56 -0700806 fops.callback().onError(failedOpsBuilder.build());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800807 }
alshabib902d41b2014-10-07 16:52:05 -0700808 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700809
810 @Override
811 public Iterable<TableStatisticsEntry> getFlowTableStatistics(DeviceId deviceId) {
812 checkPermission(FLOWRULE_READ);
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800813 checkNotNull(deviceId, DEVICE_ID_NULL);
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700814 return store.getTableStatistics(deviceId);
815 }
Charles Chan0c7c43b2016-01-14 17:39:20 -0800816
Patryk Konopka7e40c012017-06-06 13:38:06 +0200817 @Override
818 public long getActiveFlowRuleCount(DeviceId deviceId) {
Thomas Vachuskaa8e74772018-02-26 11:33:35 -0800819 checkNotNull(deviceId, DEVICE_ID_NULL);
Patryk Konopka7e40c012017-06-06 13:38:06 +0200820 return store.getActiveFlowRuleCount(deviceId);
821 }
822
Charles Chan0c7c43b2016-01-14 17:39:20 -0800823 private class InternalDeviceListener implements DeviceListener {
824 @Override
825 public void event(DeviceEvent event) {
826 switch (event.type()) {
827 case DEVICE_REMOVED:
828 case DEVICE_AVAILABILITY_CHANGED:
829 DeviceId deviceId = event.subject().id();
830 if (!deviceService.isAvailable(deviceId)) {
831 if (purgeOnDisconnection) {
832 store.purgeFlowRule(deviceId);
833 }
834 }
835 break;
836 default:
837 break;
838 }
839 }
840 }
alshabib57044ba2014-09-16 15:58:01 -0700841}