blob: 07be6c9d42af548866b9aef2871acdac36784081 [file] [log] [blame]
Thomas Vachuska781d18b2014-10-27 10:31:25 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska781d18b2014-10-27 10:31:25 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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
Thomas Vachuska781d18b2014-10-27 10:31:25 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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.
Thomas Vachuska781d18b2014-10-27 10:31:25 -070015 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.provider.of.flow.impl;
alshabib1cc04f72014-09-16 16:09:58 -070017
Thomas Vachuska75aaa672015-04-29 12:24:43 -070018import com.google.common.cache.Cache;
19import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.RemovalCause;
21import com.google.common.cache.RemovalNotification;
Madan Jampani84382b92016-06-22 08:26:49 -070022import com.google.common.collect.ImmutableSet;
23import com.google.common.collect.Lists;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070024import com.google.common.collect.Maps;
25import com.google.common.collect.Sets;
Madan Jampani84382b92016-06-22 08:26:49 -070026
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -070027import io.netty.buffer.ByteBuf;
28import io.netty.buffer.Unpooled;
alshabib1cc04f72014-09-16 16:09:58 -070029import org.apache.felix.scr.annotations.Activate;
30import org.apache.felix.scr.annotations.Component;
31import org.apache.felix.scr.annotations.Deactivate;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070032import org.apache.felix.scr.annotations.Modified;
33import org.apache.felix.scr.annotations.Property;
alshabib1cc04f72014-09-16 16:09:58 -070034import org.apache.felix.scr.annotations.Reference;
35import org.apache.felix.scr.annotations.ReferenceCardinality;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070036import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080037import org.onosproject.core.ApplicationId;
38import org.onosproject.net.DeviceId;
Rodrigo Duarte Sousae37d1292017-08-29 17:01:24 -030039import org.onosproject.net.driver.DefaultDriverData;
40import org.onosproject.net.driver.DefaultDriverHandler;
41import org.onosproject.net.driver.Driver;
42import org.onosproject.net.driver.DriverHandler;
Jonathan Hart3c259162015-10-21 21:31:19 -070043import org.onosproject.net.driver.DriverService;
Brian O'Connorabafb502014-12-02 22:26:20 -080044import org.onosproject.net.flow.CompletedBatchOperation;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070045import org.onosproject.net.flow.DefaultTableStatisticsEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080046import org.onosproject.net.flow.FlowEntry;
47import org.onosproject.net.flow.FlowRule;
Ray Milkey7bf273c2017-09-27 16:15:15 -070048import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry;
49import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation;
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -070050import org.onosproject.net.flow.FlowRuleExtPayLoad;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.flow.FlowRuleProvider;
52import org.onosproject.net.flow.FlowRuleProviderRegistry;
53import org.onosproject.net.flow.FlowRuleProviderService;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070054import org.onosproject.net.flow.TableStatisticsEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.provider.AbstractProvider;
56import org.onosproject.net.provider.ProviderId;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070057import org.onosproject.net.statistic.DefaultLoad;
Brian O'Connorabafb502014-12-02 22:26:20 -080058import org.onosproject.openflow.controller.Dpid;
59import org.onosproject.openflow.controller.OpenFlowController;
60import org.onosproject.openflow.controller.OpenFlowEventListener;
61import org.onosproject.openflow.controller.OpenFlowSwitch;
62import org.onosproject.openflow.controller.OpenFlowSwitchListener;
63import org.onosproject.openflow.controller.RoleState;
jcc3d4e14a2015-04-21 11:32:05 +080064import org.onosproject.openflow.controller.ThirdPartyMessage;
Thomas Vachuska95caba32016-04-04 10:42:05 -070065import org.onosproject.provider.of.flow.util.FlowEntryBuilder;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070066import org.osgi.service.component.ComponentContext;
Thomas Vachuska3358af22015-05-19 18:40:34 -070067import org.projectfloodlight.openflow.protocol.OFBadRequestCode;
alshabib902d41b2014-10-07 16:52:05 -070068import org.projectfloodlight.openflow.protocol.OFBarrierRequest;
Laszlo Pappedadbe22017-12-14 20:05:49 +000069import org.projectfloodlight.openflow.protocol.OFCapabilities;
alshabib902d41b2014-10-07 16:52:05 -070070import org.projectfloodlight.openflow.protocol.OFErrorMsg;
Cem Türker3baff672017-10-12 15:09:01 +030071import org.projectfloodlight.openflow.protocol.OFFlowLightweightStatsReply;
alshabib193525b2014-10-08 18:58:03 -070072import org.projectfloodlight.openflow.protocol.OFFlowMod;
alshabib8f1cf4a2014-09-17 14:44:48 -070073import org.projectfloodlight.openflow.protocol.OFFlowRemoved;
alshabib5c370ff2014-09-18 10:12:14 -070074import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
alshabib8f1cf4a2014-09-17 14:44:48 -070075import org.projectfloodlight.openflow.protocol.OFMessage;
76import org.projectfloodlight.openflow.protocol.OFPortStatus;
alshabib5c370ff2014-09-18 10:12:14 -070077import org.projectfloodlight.openflow.protocol.OFStatsReply;
sangho89bf6fb2015-02-09 09:33:13 -080078import org.projectfloodlight.openflow.protocol.OFStatsType;
Jonathan Hart3c259162015-10-21 21:31:19 -070079import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
80import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
Prince Pereira141ed812016-09-02 19:03:18 +053081import org.projectfloodlight.openflow.protocol.OFType;
82import org.projectfloodlight.openflow.protocol.OFVersion;
Prince Pereira788797e2016-08-10 11:24:14 +053083import org.projectfloodlight.openflow.protocol.errormsg.OFBadActionErrorMsg;
84import org.projectfloodlight.openflow.protocol.errormsg.OFBadInstructionErrorMsg;
85import org.projectfloodlight.openflow.protocol.errormsg.OFBadMatchErrorMsg;
Thomas Vachuska3358af22015-05-19 18:40:34 -070086import org.projectfloodlight.openflow.protocol.errormsg.OFBadRequestErrorMsg;
alshabib193525b2014-10-08 18:58:03 -070087import org.projectfloodlight.openflow.protocol.errormsg.OFFlowModFailedErrorMsg;
Prince Pereira141ed812016-09-02 19:03:18 +053088import org.projectfloodlight.openflow.types.U16;
89import org.projectfloodlight.openflow.types.U64;
alshabib1cc04f72014-09-16 16:09:58 -070090import org.slf4j.Logger;
91
Thomas Vachuska75aaa672015-04-29 12:24:43 -070092import java.util.Collections;
93import java.util.Dictionary;
94import java.util.List;
95import java.util.Map;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070096import java.util.Objects;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070097import java.util.Optional;
98import java.util.Set;
99import java.util.Timer;
100import java.util.concurrent.TimeUnit;
101import java.util.stream.Collectors;
102
ssyoon9030fbcd92015-08-17 10:42:07 +0900103import static com.google.common.base.Preconditions.checkNotNull;
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700104import static com.google.common.base.Strings.isNullOrEmpty;
105import static org.onlab.util.Tools.get;
106import static org.slf4j.LoggerFactory.getLogger;
alshabibeec3a062014-09-17 18:01:26 -0700107
alshabib1cc04f72014-09-16 16:09:58 -0700108/**
jcc3d4e14a2015-04-21 11:32:05 +0800109 * Provider which uses an OpenFlow controller to detect network end-station
110 * hosts.
alshabib1cc04f72014-09-16 16:09:58 -0700111 */
112@Component(immediate = true)
jcc3d4e14a2015-04-21 11:32:05 +0800113public class OpenFlowRuleProvider extends AbstractProvider
114 implements FlowRuleProvider {
alshabib1cc04f72014-09-16 16:09:58 -0700115
116 private final Logger log = getLogger(getClass());
117
118 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
119 protected FlowRuleProviderRegistry providerRegistry;
120
121 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
122 protected OpenFlowController controller;
123
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
125 protected ComponentConfigService cfgService;
126
Jonathan Hart3c259162015-10-21 21:31:19 -0700127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
128 protected DriverService driverService;
129
ssyoon9030fbcd92015-08-17 10:42:07 +0900130 private static final int DEFAULT_POLL_FREQUENCY = 5;
Prince Pereira141ed812016-09-02 19:03:18 +0530131 private static final int MIN_EXPECTED_BYTE_LEN = 56;
132 private static final int SKIP_BYTES = 4;
133 private static final boolean DEFAULT_ADAPTIVE_FLOW_SAMPLING = false;
134
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700135 @Property(name = "flowPollFrequency", intValue = DEFAULT_POLL_FREQUENCY,
136 label = "Frequency (in seconds) for polling flow statistics")
137 private int flowPollFrequency = DEFAULT_POLL_FREQUENCY;
138
ssyoon9030fbcd92015-08-17 10:42:07 +0900139 @Property(name = "adaptiveFlowSampling", boolValue = DEFAULT_ADAPTIVE_FLOW_SAMPLING,
140 label = "Adaptive Flow Sampling is on or off")
141 private boolean adaptiveFlowSampling = DEFAULT_ADAPTIVE_FLOW_SAMPLING;
142
alshabib1cc04f72014-09-16 16:09:58 -0700143 private FlowRuleProviderService providerService;
144
alshabibeec3a062014-09-17 18:01:26 -0700145 private final InternalFlowProvider listener = new InternalFlowProvider();
146
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800147 private Cache<Long, InternalCacheEntry> pendingBatches;
alshabib193525b2014-10-08 18:58:03 -0700148
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900149 private final Timer timer = new Timer("onos-openflow-collector");
150
Cem Türker3baff672017-10-12 15:09:01 +0300151
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900152 // Old simple collector set
Madan Jampani6b266102016-06-23 00:56:36 -0700153 private final Map<Dpid, FlowStatsCollector> simpleCollectors = Maps.newConcurrentMap();
ssyoon9030fbcd92015-08-17 10:42:07 +0900154
155 // NewAdaptiveFlowStatsCollector Set
Madan Jampani6b266102016-06-23 00:56:36 -0700156 private final Map<Dpid, NewAdaptiveFlowStatsCollector> afsCollectors = Maps.newConcurrentMap();
157 private final Map<Dpid, TableStatisticsCollector> tableStatsCollectors = Maps.newConcurrentMap();
alshabib3d643ec2014-10-22 18:33:00 -0700158
alshabib1cc04f72014-09-16 16:09:58 -0700159 /**
160 * Creates an OpenFlow host provider.
161 */
162 public OpenFlowRuleProvider() {
Brian O'Connorabafb502014-12-02 22:26:20 -0800163 super(new ProviderId("of", "org.onosproject.provider.openflow"));
alshabib1cc04f72014-09-16 16:09:58 -0700164 }
165
166 @Activate
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700167 protected void activate(ComponentContext context) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700168 cfgService.registerProperties(getClass());
alshabib1cc04f72014-09-16 16:09:58 -0700169 providerService = providerRegistry.register(this);
alshabibeec3a062014-09-17 18:01:26 -0700170 controller.addListener(listener);
171 controller.addEventListener(listener);
alshabib3d643ec2014-10-22 18:33:00 -0700172
Antonio Marsico1c5ae1f2015-12-15 15:31:56 +0100173 modified(context);
174
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700175 pendingBatches = createBatchCache();
ssyoon9030fbcd92015-08-17 10:42:07 +0900176
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700177 createCollectors();
alshabib3d643ec2014-10-22 18:33:00 -0700178
ssyoon9030fbcd92015-08-17 10:42:07 +0900179 log.info("Started with flowPollFrequency = {}, adaptiveFlowSampling = {}",
180 flowPollFrequency, adaptiveFlowSampling);
alshabib1cc04f72014-09-16 16:09:58 -0700181 }
182
183 @Deactivate
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700184 protected void deactivate(ComponentContext context) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700185 cfgService.unregisterProperties(getClass(), false);
186 stopCollectors();
alshabib1cc04f72014-09-16 16:09:58 -0700187 providerRegistry.unregister(this);
188 providerService = null;
189
190 log.info("Stopped");
191 }
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800192
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700193 @Modified
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700194 protected void modified(ComponentContext context) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700195 Dictionary<?, ?> properties = context.getProperties();
196 int newFlowPollFrequency;
197 try {
198 String s = get(properties, "flowPollFrequency");
199 newFlowPollFrequency = isNullOrEmpty(s) ? flowPollFrequency : Integer.parseInt(s.trim());
200
201 } catch (NumberFormatException | ClassCastException e) {
202 newFlowPollFrequency = flowPollFrequency;
203 }
204
205 if (newFlowPollFrequency != flowPollFrequency) {
206 flowPollFrequency = newFlowPollFrequency;
207 adjustRate();
208 }
209
210 log.info("Settings: flowPollFrequency={}", flowPollFrequency);
ssyoon9030fbcd92015-08-17 10:42:07 +0900211
212 boolean newAdaptiveFlowSampling;
213 String s = get(properties, "adaptiveFlowSampling");
214 newAdaptiveFlowSampling = isNullOrEmpty(s) ? adaptiveFlowSampling : Boolean.parseBoolean(s.trim());
215
216 if (newAdaptiveFlowSampling != adaptiveFlowSampling) {
217 // stop previous collector
218 stopCollectors();
219 adaptiveFlowSampling = newAdaptiveFlowSampling;
220 // create new collectors
221 createCollectors();
222 }
223
224 log.info("Settings: adaptiveFlowSampling={}", adaptiveFlowSampling);
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700225 }
226
227 private Cache<Long, InternalCacheEntry> createBatchCache() {
228 return CacheBuilder.newBuilder()
229 .expireAfterWrite(10, TimeUnit.SECONDS)
230 .removalListener((RemovalNotification<Long, InternalCacheEntry> notification) -> {
231 if (notification.getCause() == RemovalCause.EXPIRED) {
232 providerService.batchOperationCompleted(notification.getKey(),
233 notification.getValue().failedCompletion());
234 }
235 }).build();
236 }
237
238 private void createCollectors() {
239 controller.getSwitches().forEach(this::createCollector);
240 }
241
242 private void createCollector(OpenFlowSwitch sw) {
Kavitha Alagesan6704df32016-08-18 15:15:31 +0530243 if (sw == null) {
244 return;
245 }
Laszlo Papp58174812018-01-16 13:29:47 +0000246 if (sw.features().getCapabilities().contains(OFCapabilities.FLOW_STATS)) {
247 if (adaptiveFlowSampling) {
248 // NewAdaptiveFlowStatsCollector Constructor
249 NewAdaptiveFlowStatsCollector fsc =
250 new NewAdaptiveFlowStatsCollector(driverService, sw, flowPollFrequency);
251 stopCollectorIfNeeded(afsCollectors.put(new Dpid(sw.getId()), fsc));
252 fsc.start();
253 } else {
254 FlowStatsCollector fsc = new FlowStatsCollector(timer, sw, flowPollFrequency);
255 stopCollectorIfNeeded(simpleCollectors.put(new Dpid(sw.getId()), fsc));
256 fsc.start();
257 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900258 }
Laszlo Pappedadbe22017-12-14 20:05:49 +0000259 if (sw.features().getCapabilities().contains(OFCapabilities.TABLE_STATS)) {
260 TableStatisticsCollector tsc = new TableStatisticsCollector(timer, sw, flowPollFrequency);
261 stopCollectorIfNeeded(tableStatsCollectors.put(new Dpid(sw.getId()), tsc));
262 tsc.start();
263 }
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700264 }
265
266 private void stopCollectorIfNeeded(SwitchDataCollector collector) {
267 if (collector != null) {
268 collector.stop();
269 }
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700270 }
271
272 private void stopCollectors() {
ssyoon9030fbcd92015-08-17 10:42:07 +0900273 if (adaptiveFlowSampling) {
274 // NewAdaptiveFlowStatsCollector Destructor
275 afsCollectors.values().forEach(NewAdaptiveFlowStatsCollector::stop);
276 afsCollectors.clear();
277 } else {
278 simpleCollectors.values().forEach(FlowStatsCollector::stop);
279 simpleCollectors.clear();
280 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700281 tableStatsCollectors.values().forEach(TableStatisticsCollector::stop);
282 tableStatsCollectors.clear();
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700283 }
284
285 private void adjustRate() {
286 DefaultLoad.setPollInterval(flowPollFrequency);
ssyoon9030fbcd92015-08-17 10:42:07 +0900287 if (adaptiveFlowSampling) {
288 // NewAdaptiveFlowStatsCollector calAndPollInterval
289 afsCollectors.values().forEach(fsc -> fsc.adjustCalAndPollInterval(flowPollFrequency));
290 } else {
291 simpleCollectors.values().forEach(fsc -> fsc.adjustPollInterval(flowPollFrequency));
292 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700293 tableStatsCollectors.values().forEach(tsc -> tsc.adjustPollInterval(flowPollFrequency));
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700294 }
295
Jordan Halterman6de47ff2019-03-05 18:44:03 -0800296 private void resetEvents(Dpid dpid) {
297 SwitchDataCollector collector;
298 if (adaptiveFlowSampling) {
299 collector = afsCollectors.get(dpid);
300 } else {
301 collector = simpleCollectors.get(dpid);
302 }
303 if (collector != null) {
304 collector.resetEvents();
305 }
306 }
307
308 private void recordEvent(Dpid dpid) {
309 recordEvents(dpid, 1);
310 }
311
312 private void recordEvents(Dpid dpid, int events) {
313 SwitchDataCollector collector;
314 if (adaptiveFlowSampling) {
315 collector = afsCollectors.get(dpid);
316 } else {
317 collector = simpleCollectors.get(dpid);
318 }
319 if (collector != null) {
320 collector.recordEvents(events);
321 }
322 }
323
alshabib1cc04f72014-09-16 16:09:58 -0700324 @Override
325 public void applyFlowRule(FlowRule... flowRules) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800326 for (FlowRule flowRule : flowRules) {
327 applyRule(flowRule);
alshabib35edb1a2014-09-16 17:44:44 -0700328 }
alshabib1cc04f72014-09-16 16:09:58 -0700329 }
330
alshabib35edb1a2014-09-16 17:44:44 -0700331 private void applyRule(FlowRule flowRule) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900332 Dpid dpid = Dpid.dpid(flowRule.deviceId().uri());
333 OpenFlowSwitch sw = controller.getSwitch(dpid);
334
Ray Milkey0ae473d2016-04-04 10:56:47 -0700335 if (sw == null) {
336 return;
337 }
338
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700339 FlowRuleExtPayLoad flowRuleExtPayLoad = flowRule.payLoad();
340 if (hasPayload(flowRuleExtPayLoad)) {
341 OFMessage msg = new ThirdPartyMessage(flowRuleExtPayLoad.payLoad());
jcc3d4e14a2015-04-21 11:32:05 +0800342 sw.sendMsg(msg);
343 return;
344 }
alshabibbdcbb102015-04-22 14:16:38 -0700345 sw.sendMsg(FlowModBuilder.builder(flowRule, sw.factory(),
Jonathan Hart3c259162015-10-21 21:31:19 -0700346 Optional.empty(), Optional.of(driverService)).buildFlowAdd());
Jordan Halterman6de47ff2019-03-05 18:44:03 -0800347
348 recordEvent(dpid);
alshabib35edb1a2014-09-16 17:44:44 -0700349 }
350
alshabib1cc04f72014-09-16 16:09:58 -0700351 @Override
352 public void removeFlowRule(FlowRule... flowRules) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800353 for (FlowRule flowRule : flowRules) {
354 removeRule(flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700355 }
alshabib1cc04f72014-09-16 16:09:58 -0700356 }
357
alshabib219ebaa2014-09-22 15:41:24 -0700358 private void removeRule(FlowRule flowRule) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900359 Dpid dpid = Dpid.dpid(flowRule.deviceId().uri());
360 OpenFlowSwitch sw = controller.getSwitch(dpid);
361
Ray Milkey0ae473d2016-04-04 10:56:47 -0700362 if (sw == null) {
363 return;
364 }
365
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700366 FlowRuleExtPayLoad flowRuleExtPayLoad = flowRule.payLoad();
367 if (hasPayload(flowRuleExtPayLoad)) {
368 OFMessage msg = new ThirdPartyMessage(flowRuleExtPayLoad.payLoad());
jcc3d4e14a2015-04-21 11:32:05 +0800369 sw.sendMsg(msg);
370 return;
371 }
alshabibbdcbb102015-04-22 14:16:38 -0700372 sw.sendMsg(FlowModBuilder.builder(flowRule, sw.factory(),
Jonathan Hart3c259162015-10-21 21:31:19 -0700373 Optional.empty(), Optional.of(driverService)).buildFlowDel());
Jordan Halterman6de47ff2019-03-05 18:44:03 -0800374
375 recordEvent(dpid);
alshabib219ebaa2014-09-22 15:41:24 -0700376 }
377
alshabiba68eb962014-09-24 20:34:13 -0700378 @Override
379 public void removeRulesById(ApplicationId id, FlowRule... flowRules) {
380 // TODO: optimize using the ApplicationId
381 removeFlowRule(flowRules);
382 }
383
alshabib193525b2014-10-08 18:58:03 -0700384 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800385 public void executeBatch(FlowRuleBatchOperation batch) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900386 checkNotNull(batch);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800387
ssyoon9030fbcd92015-08-17 10:42:07 +0900388 Dpid dpid = Dpid.dpid(batch.deviceId().uri());
389 OpenFlowSwitch sw = controller.getSwitch(dpid);
Madan Jampani84382b92016-06-22 08:26:49 -0700390
391 // If switch no longer exists, simply return.
392 if (sw == null) {
393 Set<FlowRule> failures = ImmutableSet.copyOf(Lists.transform(batch.getOperations(), e -> e.target()));
394 providerService.batchOperationCompleted(batch.id(),
395 new CompletedBatchOperation(false, failures, batch.deviceId()));
396 return;
397 }
398 pendingBatches.put(batch.id(), new InternalCacheEntry(batch));
pierb673adc2019-10-24 13:56:58 +0200399 // Build a batch of flow mods - to reduce the number i/o asked to the SO
400 Set<OFFlowMod> mods = Sets.newHashSet();
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800401 OFFlowMod mod;
alshabib193525b2014-10-08 18:58:03 -0700402 for (FlowRuleBatchEntry fbe : batch.getOperations()) {
jcc3d4e14a2015-04-21 11:32:05 +0800403 // flow is the third party privacy flow
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700404 FlowRuleExtPayLoad flowRuleExtPayLoad = fbe.target().payLoad();
405 if (hasPayload(flowRuleExtPayLoad)) {
406 OFMessage msg = new ThirdPartyMessage(flowRuleExtPayLoad.payLoad());
jcc3d4e14a2015-04-21 11:32:05 +0800407 sw.sendMsg(msg);
408 continue;
409 }
Thomas Vachuskad07c0922015-10-06 14:48:06 -0700410 FlowModBuilder builder =
Jonathan Hart3c259162015-10-21 21:31:19 -0700411 FlowModBuilder.builder(fbe.target(), sw.factory(),
412 Optional.of(batch.id()), Optional.of(driverService));
Sho SHIMIZUaba9d002015-01-29 14:51:04 -0800413 switch (fbe.operator()) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700414 case ADD:
415 mod = builder.buildFlowAdd();
416 break;
417 case REMOVE:
418 mod = builder.buildFlowDel();
419 break;
420 case MODIFY:
421 mod = builder.buildFlowMod();
422 break;
423 default:
424 log.error("Unsupported batch operation {}; skipping flowmod {}",
ssyoon9030fbcd92015-08-17 10:42:07 +0900425 fbe.operator(), fbe);
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700426 continue;
jcc3d4e14a2015-04-21 11:32:05 +0800427 }
pierb673adc2019-10-24 13:56:58 +0200428 mods.add(mod);
alshabib193525b2014-10-08 18:58:03 -0700429 }
pierb673adc2019-10-24 13:56:58 +0200430 // Build a list to mantain the order
431 List<OFMessage> modsTosend = Lists.newArrayList(mods);
jcc3d4e14a2015-04-21 11:32:05 +0800432 OFBarrierRequest.Builder builder = sw.factory().buildBarrierRequest()
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800433 .setXid(batch.id());
pierb673adc2019-10-24 13:56:58 +0200434 // Adds finally the barrier request
435 modsTosend.add(builder.build());
436 sw.sendMsg(modsTosend);
437 // Take into account also the barrier request
438 recordEvents(dpid, (batch.getOperations().size() + 1));
alshabib193525b2014-10-08 18:58:03 -0700439 }
440
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700441 private boolean hasPayload(FlowRuleExtPayLoad flowRuleExtPayLoad) {
442 return flowRuleExtPayLoad != null &&
443 flowRuleExtPayLoad.payLoad() != null &&
444 flowRuleExtPayLoad.payLoad().length > 0;
445 }
446
alshabib8f1cf4a2014-09-17 14:44:48 -0700447 private class InternalFlowProvider
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800448 implements OpenFlowSwitchListener, OpenFlowEventListener {
alshabib8f1cf4a2014-09-17 14:44:48 -0700449
alshabib8f1cf4a2014-09-17 14:44:48 -0700450 @Override
451 public void switchAdded(Dpid dpid) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700452 createCollector(controller.getSwitch(dpid));
alshabib8f1cf4a2014-09-17 14:44:48 -0700453 }
454
455 @Override
456 public void switchRemoved(Dpid dpid) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900457 if (adaptiveFlowSampling) {
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700458 stopCollectorIfNeeded(afsCollectors.remove(dpid));
ssyoon9030fbcd92015-08-17 10:42:07 +0900459 } else {
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700460 stopCollectorIfNeeded(simpleCollectors.remove(dpid));
alshabibdfc7afb2014-10-21 20:13:27 -0700461 }
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700462 stopCollectorIfNeeded(tableStatsCollectors.remove(dpid));
alshabib8f1cf4a2014-09-17 14:44:48 -0700463 }
464
465 @Override
Ayaka Koshibe38594c22014-10-22 13:36:12 -0700466 public void switchChanged(Dpid dpid) {
467 }
468
469 @Override
alshabib8f1cf4a2014-09-17 14:44:48 -0700470 public void portChanged(Dpid dpid, OFPortStatus status) {
jcc3d4e14a2015-04-21 11:32:05 +0800471 // TODO: Decide whether to evict flows internal store.
alshabib8f1cf4a2014-09-17 14:44:48 -0700472 }
473
474 @Override
475 public void handleMessage(Dpid dpid, OFMessage msg) {
Ray Milkeyada9e2d2016-04-05 16:42:35 -0700476 if (providerService == null) {
477 // We are shutting down, nothing to be done
478 return;
479 }
Jonathan Harte4e74f02016-03-03 12:57:40 -0800480 DeviceId deviceId = DeviceId.deviceId(Dpid.uri(dpid));
alshabib8f1cf4a2014-09-17 14:44:48 -0700481 switch (msg.getType()) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700482 case FLOW_REMOVED:
483 OFFlowRemoved removed = (OFFlowRemoved) msg;
alshabib6b5cfec2014-09-18 17:42:18 -0700484
Rodrigo Duarte Sousae37d1292017-08-29 17:01:24 -0300485 FlowEntry fr = new FlowEntryBuilder(deviceId, removed, getDriver(deviceId)).build();
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700486 providerService.flowRemoved(fr);
487 break;
488 case STATS_REPLY:
489 if (((OFStatsReply) msg).getStatsType() == OFStatsType.FLOW) {
Jordan Halterman6de47ff2019-03-05 18:44:03 -0800490 // Let's unblock first the collector
491 SwitchDataCollector collector;
492 if (adaptiveFlowSampling) {
493 collector = afsCollectors.get(dpid);
494 } else {
495 collector = simpleCollectors.get(dpid);
496 }
497 if (collector != null) {
498 collector.received();
499 }
Rodrigo Duarte Sousae37d1292017-08-29 17:01:24 -0300500 pushFlowMetrics(dpid, (OFFlowStatsReply) msg, getDriver(deviceId));
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700501 } else if (((OFStatsReply) msg).getStatsType() == OFStatsType.TABLE) {
502 pushTableStatistics(dpid, (OFTableStatsReply) msg);
Cem Türker3baff672017-10-12 15:09:01 +0300503 } else if (((OFStatsReply) msg).getStatsType() == OFStatsType.FLOW_LIGHTWEIGHT) {
504 pushFlowLightWeightMetrics(dpid, (OFFlowLightweightStatsReply) msg);
sangho89bf6fb2015-02-09 09:33:13 -0800505 }
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700506 break;
507 case BARRIER_REPLY:
508 try {
Thomas Vachuska3358af22015-05-19 18:40:34 -0700509 InternalCacheEntry entry = pendingBatches.getIfPresent(msg.getXid());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800510 if (entry != null) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700511 providerService
512 .batchOperationCompleted(msg.getXid(),
513 entry.completed());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800514 } else {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700515 log.warn("Received unknown Barrier Reply: {}",
516 msg.getXid());
517 }
518 } finally {
519 pendingBatches.invalidate(msg.getXid());
520 }
521 break;
522 case ERROR:
Thomas Vachuska3358af22015-05-19 18:40:34 -0700523 // TODO: This needs to get suppressed in a better way.
524 if (msg instanceof OFBadRequestErrorMsg &&
525 ((OFBadRequestErrorMsg) msg).getCode() == OFBadRequestCode.BAD_TYPE) {
526 log.debug("Received error message {} from {}", msg, dpid);
527 } else {
528 log.warn("Received error message {} from {}", msg, dpid);
529 }
Prince Pereira788797e2016-08-10 11:24:14 +0530530 handleErrorMsg(deviceId, msg);
Ray Milkey4fd3ceb2015-12-10 14:43:08 -0800531 break;
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700532 default:
533 log.debug("Unhandled message type: {}", msg.getType());
alshabib8f1cf4a2014-09-17 14:44:48 -0700534 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700535 }
536
Prince Pereira788797e2016-08-10 11:24:14 +0530537 private void handleErrorMsg(DeviceId deviceId, OFMessage msg) {
Prince Pereira141ed812016-09-02 19:03:18 +0530538 InternalCacheEntry entry = pendingBatches.getIfPresent(msg.getXid());
Prince Pereira788797e2016-08-10 11:24:14 +0530539 OFErrorMsg error = (OFErrorMsg) msg;
540 OFMessage ofMessage = null;
541 switch (error.getErrType()) {
542 case BAD_ACTION:
543 OFBadActionErrorMsg baErrorMsg = (OFBadActionErrorMsg) error;
544 if (baErrorMsg.getData().getParsedMessage().isPresent()) {
545 ofMessage = baErrorMsg.getData().getParsedMessage().get();
546 }
547 break;
548 case BAD_INSTRUCTION:
549 OFBadInstructionErrorMsg biErrorMsg = (OFBadInstructionErrorMsg) error;
550 if (biErrorMsg.getData().getParsedMessage().isPresent()) {
551 ofMessage = biErrorMsg.getData().getParsedMessage().get();
552 }
553 break;
554 case BAD_MATCH:
555 OFBadMatchErrorMsg bmErrorMsg = (OFBadMatchErrorMsg) error;
556 if (bmErrorMsg.getData().getParsedMessage().isPresent()) {
557 ofMessage = bmErrorMsg.getData().getParsedMessage().get();
558 }
559 break;
560 case FLOW_MOD_FAILED:
561 OFFlowModFailedErrorMsg fmFailed = (OFFlowModFailedErrorMsg) error;
562 if (fmFailed.getData().getParsedMessage().isPresent()) {
563 ofMessage = fmFailed.getData().getParsedMessage().get();
564 }
565 break;
566 default:
567 // Do nothing.
568 return;
569 }
Prince Pereira141ed812016-09-02 19:03:18 +0530570
Prince Pereira788797e2016-08-10 11:24:14 +0530571 if (ofMessage != null) {
Prince Pereira141ed812016-09-02 19:03:18 +0530572
Prince Pereira788797e2016-08-10 11:24:14 +0530573 if (entry != null) {
574 OFFlowMod ofFlowMod = (OFFlowMod) ofMessage;
Rodrigo Duarte Sousae37d1292017-08-29 17:01:24 -0300575 entry.appendFailure(new FlowEntryBuilder(deviceId, ofFlowMod, getDriver(deviceId)).build());
Prince Pereira788797e2016-08-10 11:24:14 +0530576 } else {
577 log.error("No matching batch for this error: {}", error);
578 }
Prince Pereira141ed812016-09-02 19:03:18 +0530579
Prince Pereira788797e2016-08-10 11:24:14 +0530580 } else {
Prince Pereira141ed812016-09-02 19:03:18 +0530581
582 U64 cookieId = readCookieIdFromOFErrorMsg(error, msg.getVersion());
583
584 if (cookieId != null) {
585 long flowId = cookieId.getValue();
586
587 if (entry != null) {
588 for (FlowRuleBatchEntry fbEntry : entry.operation.getOperations()) {
589 if (fbEntry.target().id().value() == flowId) {
590 entry.appendFailure(fbEntry.target());
591 break;
592 }
593 }
594 } else {
595 log.error("No matching batch for this error: {}", error);
596 }
597
598 } else {
599 log.error("Flow installation failed but switch " +
600 "didn't tell us which one.");
601 }
Prince Pereira788797e2016-08-10 11:24:14 +0530602 }
603 }
604
Prince Pereira141ed812016-09-02 19:03:18 +0530605 /**
606 * Reading cookieId from OFErrorMsg.
607 *
608 * Loxigen OpenFlow API failed in parsing error messages because of
609 * 64 byte data truncation based on OpenFlow specs. The method written
610 * is a workaround to extract the cookieId from the packet till the
611 * issue is resolved in Loxigen OpenFlow code.
612 * Ref: https://groups.google.com/a/onosproject.org/forum/#!topic
613 * /onos-dev/_KwlHZDllLE
614 *
615 * @param msg OF error message
616 * @param ofVersion Openflow version
617 * @return cookieId
618 */
619 private U64 readCookieIdFromOFErrorMsg(OFErrorMsg msg,
620 OFVersion ofVersion) {
621
622 if (ofVersion.wireVersion < OFVersion.OF_13.wireVersion) {
623 log.debug("Unhandled error msg with OF version {} " +
624 "which is less than {}",
625 ofVersion, OFVersion.OF_13);
626 return null;
627 }
628
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700629 ByteBuf bb = Unpooled.wrappedBuffer(msg.getData().getData());
Prince Pereira141ed812016-09-02 19:03:18 +0530630
631 if (bb.readableBytes() < MIN_EXPECTED_BYTE_LEN) {
632 log.debug("Wrong length: Expected to be >= {}, was: {}",
633 MIN_EXPECTED_BYTE_LEN, bb.readableBytes());
634 return null;
635 }
636
637 byte ofVer = bb.readByte();
638
639 if (ofVer != ofVersion.wireVersion) {
640 log.debug("Wrong version: Expected={}, got={}",
641 ofVersion.wireVersion, ofVer);
642 return null;
643 }
644
645 byte type = bb.readByte();
646
647 if (type != OFType.FLOW_MOD.ordinal()) {
648 log.debug("Wrong type: Expected={}, got={}",
649 OFType.FLOW_MOD.ordinal(), type);
650 return null;
651 }
652
653 int length = U16.f(bb.readShort());
654
655 if (length < MIN_EXPECTED_BYTE_LEN) {
656 log.debug("Wrong length: Expected to be >= {}, was: {}",
657 MIN_EXPECTED_BYTE_LEN, length);
658 return null;
659 }
660
661 bb.skipBytes(SKIP_BYTES);
662 return U64.ofRaw(bb.readLong());
663 }
664
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700665 @Override
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700666 public void receivedRoleReply(Dpid dpid, RoleState requested,
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800667 RoleState response) {
Jordan Halterman6de47ff2019-03-05 18:44:03 -0800668 if (response == RoleState.MASTER) {
669 resetEvents(dpid);
670 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700671 }
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700672
Rodrigo Duarte Sousae37d1292017-08-29 17:01:24 -0300673 private DriverHandler getDriver(DeviceId devId) {
674 Driver driver = driverService.getDriver(devId);
675 DriverHandler handler = new DefaultDriverHandler(new DefaultDriverData(driver, devId));
676 return handler;
677 }
678
679 private void pushFlowMetrics(Dpid dpid, OFFlowStatsReply replies, DriverHandler handler) {
alshabib64def642014-12-02 23:27:37 -0800680
alshabib54ce5892014-09-23 17:50:51 -0700681 DeviceId did = DeviceId.deviceId(Dpid.uri(dpid));
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900682 NewAdaptiveFlowStatsCollector afsc = afsCollectors.get(dpid);
alshabib54ce5892014-09-23 17:50:51 -0700683
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900684 if (adaptiveFlowSampling && afsc != null) {
685 List<FlowEntry> flowEntries = replies.getEntries().stream()
Rodrigo Duarte Sousae37d1292017-08-29 17:01:24 -0300686 .map(entry -> new FlowEntryBuilder(did, entry, handler).withSetAfsc(afsc).build())
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900687 .collect(Collectors.toList());
alshabib54ce5892014-09-23 17:50:51 -0700688
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900689 // Check that OFFlowStatsReply Xid is same with the one of OFFlowStatsRequest?
690 if (afsc.getFlowMissingXid() != NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID) {
691 log.debug("OpenFlowRuleProvider:pushFlowMetrics, flowMissingXid={}, "
692 + "OFFlowStatsReply Xid={}, for {}",
693 afsc.getFlowMissingXid(), replies.getXid(), dpid);
694 if (afsc.getFlowMissingXid() == replies.getXid()) {
695 // call entire flow stats update with flowMissing synchronization.
696 // used existing pushFlowMetrics
697 providerService.pushFlowMetrics(did, flowEntries);
ssyoon9030fbcd92015-08-17 10:42:07 +0900698 }
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900699 // reset flowMissingXid to NO_FLOW_MISSING_XID
700 afsc.setFlowMissingXid(NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID);
701 } else {
702 // call individual flow stats update
703 providerService.pushFlowMetricsWithoutFlowMissing(did, flowEntries);
ssyoon9030fbcd92015-08-17 10:42:07 +0900704 }
705 } else {
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900706 List<FlowEntry> flowEntries = replies.getEntries().stream()
Rodrigo Duarte Sousae37d1292017-08-29 17:01:24 -0300707 .map(entry -> new FlowEntryBuilder(did, entry, handler).build())
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900708 .collect(Collectors.toList());
709
ssyoon9030fbcd92015-08-17 10:42:07 +0900710 // call existing entire flow stats update with flowMissing synchronization
711 providerService.pushFlowMetrics(did, flowEntries);
712 }
alshabib5c370ff2014-09-18 10:12:14 -0700713 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700714
715 private void pushTableStatistics(Dpid dpid, OFTableStatsReply replies) {
716
717 DeviceId did = DeviceId.deviceId(Dpid.uri(dpid));
718 List<TableStatisticsEntry> tableStatsEntries = replies.getEntries().stream()
719 .map(entry -> buildTableStatistics(did, entry))
720 .filter(Objects::nonNull)
721 .collect(Collectors.toList());
722 providerService.pushTableStatistics(did, tableStatsEntries);
723 }
724
Cem Türker3baff672017-10-12 15:09:01 +0300725 private void pushFlowLightWeightMetrics(Dpid dpid, OFFlowLightweightStatsReply replies) {
726
727 DeviceId did = DeviceId.deviceId(Dpid.uri(dpid));
728 NewAdaptiveFlowStatsCollector afsc = afsCollectors.get(dpid);
729 if (adaptiveFlowSampling && afsc != null) {
730 List<FlowEntry> flowEntries = replies.getEntries().stream()
731 .map(entry -> new FlowEntryBuilder(did, entry, driverService).withSetAfsc(afsc).build())
732 .collect(Collectors.toList());
733
734 // Check that OFFlowStatsReply Xid is same with the one of OFFlowStatsRequest?
735 if (afsc.getFlowMissingXid() != NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID) {
736 log.debug("OpenFlowRuleProvider:pushFlowMetrics, flowMissingXid={}, "
737 + "OFFlowStatsReply Xid={}, for {}",
738 afsc.getFlowMissingXid(), replies.getXid(), dpid);
739 if (afsc.getFlowMissingXid() == replies.getXid()) {
740 // call entire flow stats update with flowMissing synchronization.
741 // used existing pushFlowMetrics
742 providerService.pushFlowMetrics(did, flowEntries);
743 }
744 // reset flowMissingXid to NO_FLOW_MISSING_XID
745 afsc.setFlowMissingXid(NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID);
746 } else {
747 // call individual flow stats update
748 providerService.pushFlowMetricsWithoutFlowMissing(did, flowEntries);
749 }
750 } else {
751 List<FlowEntry> flowEntries = replies.getEntries().stream()
752 .map(entry -> new FlowEntryBuilder(did, entry, driverService).build())
753 .collect(Collectors.toList());
754 // call existing entire flow stats update with flowMissing synchronization
755 providerService.pushFlowMetrics(did, flowEntries);
756 }
757 }
758
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700759 private TableStatisticsEntry buildTableStatistics(DeviceId deviceId,
760 OFTableStatsEntry ofEntry) {
761 TableStatisticsEntry entry = null;
762 if (ofEntry != null) {
763 entry = new DefaultTableStatisticsEntry(deviceId,
764 ofEntry.getTableId().getValue(),
765 ofEntry.getActiveCount(),
766 ofEntry.getLookupCount().getValue(),
767 ofEntry.getMatchedCount().getValue());
768 }
769
770 return entry;
771
772 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700773 }
alshabib1cc04f72014-09-16 16:09:58 -0700774
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800775 /**
jcc3d4e14a2015-04-21 11:32:05 +0800776 * The internal cache entry holding the original request as well as
777 * accumulating the any failures along the way.
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700778 * <p/>
jcc3d4e14a2015-04-21 11:32:05 +0800779 * If this entry is evicted from the cache then the entire operation is
780 * considered failed. Otherwise, only the failures reported by the device
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800781 * will be propagated up.
782 */
783 private class InternalCacheEntry {
alshabib902d41b2014-10-07 16:52:05 -0700784
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800785 private final FlowRuleBatchOperation operation;
786 private final Set<FlowRule> failures = Sets.newConcurrentHashSet();
alshabib193525b2014-10-08 18:58:03 -0700787
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800788 public InternalCacheEntry(FlowRuleBatchOperation operation) {
789 this.operation = operation;
alshabib902d41b2014-10-07 16:52:05 -0700790 }
791
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800792 /**
793 * Appends a failed rule to the set of failed items.
jcc3d4e14a2015-04-21 11:32:05 +0800794 *
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800795 * @param rule the failed rule
796 */
797 public void appendFailure(FlowRule rule) {
798 failures.add(rule);
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800799 }
800
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800801 /**
802 * Fails the entire batch and returns the failed operation.
jcc3d4e14a2015-04-21 11:32:05 +0800803 *
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800804 * @return the failed operation
805 */
806 public CompletedBatchOperation failedCompletion() {
807 Set<FlowRule> fails = operation.getOperations().stream()
808 .map(op -> op.target()).collect(Collectors.toSet());
jcc3d4e14a2015-04-21 11:32:05 +0800809 return new CompletedBatchOperation(false,
810 Collections
811 .unmodifiableSet(fails),
812 operation.deviceId());
alshabib902d41b2014-10-07 16:52:05 -0700813 }
814
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800815 /**
816 * Returns the completed operation and whether the batch suceeded.
jcc3d4e14a2015-04-21 11:32:05 +0800817 *
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800818 * @return the completed operation
819 */
820 public CompletedBatchOperation completed() {
jcc3d4e14a2015-04-21 11:32:05 +0800821 return new CompletedBatchOperation(
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700822 failures.isEmpty(),
823 Collections
824 .unmodifiableSet(failures),
825 operation.deviceId());
alshabib902d41b2014-10-07 16:52:05 -0700826 }
alshabib902d41b2014-10-07 16:52:05 -0700827 }
alshabiba68eb962014-09-24 20:34:13 -0700828
alshabib1cc04f72014-09-16 16:09:58 -0700829}