blob: 9dc03cdc7ea53ed7b33a96b425575cae396347dc [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;
Jonathan Hart3c259162015-10-21 21:31:19 -070039import org.onosproject.net.driver.DriverService;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.flow.CompletedBatchOperation;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070041import org.onosproject.net.flow.DefaultTableStatisticsEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.flow.FlowEntry;
43import org.onosproject.net.flow.FlowRule;
Ray Milkey7bf273c2017-09-27 16:15:15 -070044import org.onosproject.net.flow.oldbatch.FlowRuleBatchEntry;
45import org.onosproject.net.flow.oldbatch.FlowRuleBatchOperation;
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -070046import org.onosproject.net.flow.FlowRuleExtPayLoad;
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;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070050import org.onosproject.net.flow.TableStatisticsEntry;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.provider.AbstractProvider;
52import org.onosproject.net.provider.ProviderId;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070053import org.onosproject.net.statistic.DefaultLoad;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.openflow.controller.Dpid;
55import org.onosproject.openflow.controller.OpenFlowController;
56import org.onosproject.openflow.controller.OpenFlowEventListener;
57import org.onosproject.openflow.controller.OpenFlowSwitch;
58import org.onosproject.openflow.controller.OpenFlowSwitchListener;
59import org.onosproject.openflow.controller.RoleState;
jcc3d4e14a2015-04-21 11:32:05 +080060import org.onosproject.openflow.controller.ThirdPartyMessage;
Thomas Vachuska95caba32016-04-04 10:42:05 -070061import org.onosproject.provider.of.flow.util.FlowEntryBuilder;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070062import org.osgi.service.component.ComponentContext;
Thomas Vachuska3358af22015-05-19 18:40:34 -070063import org.projectfloodlight.openflow.protocol.OFBadRequestCode;
alshabib902d41b2014-10-07 16:52:05 -070064import org.projectfloodlight.openflow.protocol.OFBarrierRequest;
65import org.projectfloodlight.openflow.protocol.OFErrorMsg;
alshabib193525b2014-10-08 18:58:03 -070066import org.projectfloodlight.openflow.protocol.OFFlowMod;
alshabib8f1cf4a2014-09-17 14:44:48 -070067import org.projectfloodlight.openflow.protocol.OFFlowRemoved;
alshabib5c370ff2014-09-18 10:12:14 -070068import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
alshabib8f1cf4a2014-09-17 14:44:48 -070069import org.projectfloodlight.openflow.protocol.OFMessage;
70import org.projectfloodlight.openflow.protocol.OFPortStatus;
alshabib5c370ff2014-09-18 10:12:14 -070071import org.projectfloodlight.openflow.protocol.OFStatsReply;
sangho89bf6fb2015-02-09 09:33:13 -080072import org.projectfloodlight.openflow.protocol.OFStatsType;
Jonathan Hart3c259162015-10-21 21:31:19 -070073import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
74import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
Prince Pereira141ed812016-09-02 19:03:18 +053075import org.projectfloodlight.openflow.protocol.OFType;
76import org.projectfloodlight.openflow.protocol.OFVersion;
Prince Pereira788797e2016-08-10 11:24:14 +053077import org.projectfloodlight.openflow.protocol.errormsg.OFBadActionErrorMsg;
78import org.projectfloodlight.openflow.protocol.errormsg.OFBadInstructionErrorMsg;
79import org.projectfloodlight.openflow.protocol.errormsg.OFBadMatchErrorMsg;
Thomas Vachuska3358af22015-05-19 18:40:34 -070080import org.projectfloodlight.openflow.protocol.errormsg.OFBadRequestErrorMsg;
alshabib193525b2014-10-08 18:58:03 -070081import org.projectfloodlight.openflow.protocol.errormsg.OFFlowModFailedErrorMsg;
Prince Pereira141ed812016-09-02 19:03:18 +053082import org.projectfloodlight.openflow.types.U16;
83import org.projectfloodlight.openflow.types.U64;
alshabib1cc04f72014-09-16 16:09:58 -070084import org.slf4j.Logger;
85
Thomas Vachuska75aaa672015-04-29 12:24:43 -070086import java.util.Collections;
87import java.util.Dictionary;
88import java.util.List;
89import java.util.Map;
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -070090import java.util.Objects;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070091import java.util.Optional;
92import java.util.Set;
93import java.util.Timer;
94import java.util.concurrent.TimeUnit;
95import java.util.stream.Collectors;
96
ssyoon9030fbcd92015-08-17 10:42:07 +090097import static com.google.common.base.Preconditions.checkNotNull;
Thomas Vachuska75aaa672015-04-29 12:24:43 -070098import static com.google.common.base.Strings.isNullOrEmpty;
99import static org.onlab.util.Tools.get;
100import static org.slf4j.LoggerFactory.getLogger;
alshabibeec3a062014-09-17 18:01:26 -0700101
alshabib1cc04f72014-09-16 16:09:58 -0700102/**
jcc3d4e14a2015-04-21 11:32:05 +0800103 * Provider which uses an OpenFlow controller to detect network end-station
104 * hosts.
alshabib1cc04f72014-09-16 16:09:58 -0700105 */
106@Component(immediate = true)
jcc3d4e14a2015-04-21 11:32:05 +0800107public class OpenFlowRuleProvider extends AbstractProvider
108 implements FlowRuleProvider {
alshabib1cc04f72014-09-16 16:09:58 -0700109
110 private final Logger log = getLogger(getClass());
111
112 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
113 protected FlowRuleProviderRegistry providerRegistry;
114
115 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
116 protected OpenFlowController controller;
117
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700118 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
119 protected ComponentConfigService cfgService;
120
Jonathan Hart3c259162015-10-21 21:31:19 -0700121 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
122 protected DriverService driverService;
123
ssyoon9030fbcd92015-08-17 10:42:07 +0900124 private static final int DEFAULT_POLL_FREQUENCY = 5;
Prince Pereira141ed812016-09-02 19:03:18 +0530125 private static final int MIN_EXPECTED_BYTE_LEN = 56;
126 private static final int SKIP_BYTES = 4;
127 private static final boolean DEFAULT_ADAPTIVE_FLOW_SAMPLING = false;
128
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700129 @Property(name = "flowPollFrequency", intValue = DEFAULT_POLL_FREQUENCY,
130 label = "Frequency (in seconds) for polling flow statistics")
131 private int flowPollFrequency = DEFAULT_POLL_FREQUENCY;
132
ssyoon9030fbcd92015-08-17 10:42:07 +0900133 @Property(name = "adaptiveFlowSampling", boolValue = DEFAULT_ADAPTIVE_FLOW_SAMPLING,
134 label = "Adaptive Flow Sampling is on or off")
135 private boolean adaptiveFlowSampling = DEFAULT_ADAPTIVE_FLOW_SAMPLING;
136
alshabib1cc04f72014-09-16 16:09:58 -0700137 private FlowRuleProviderService providerService;
138
alshabibeec3a062014-09-17 18:01:26 -0700139 private final InternalFlowProvider listener = new InternalFlowProvider();
140
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800141 private Cache<Long, InternalCacheEntry> pendingBatches;
alshabib193525b2014-10-08 18:58:03 -0700142
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900143 private final Timer timer = new Timer("onos-openflow-collector");
144
145 // Old simple collector set
Madan Jampani6b266102016-06-23 00:56:36 -0700146 private final Map<Dpid, FlowStatsCollector> simpleCollectors = Maps.newConcurrentMap();
ssyoon9030fbcd92015-08-17 10:42:07 +0900147
148 // NewAdaptiveFlowStatsCollector Set
Madan Jampani6b266102016-06-23 00:56:36 -0700149 private final Map<Dpid, NewAdaptiveFlowStatsCollector> afsCollectors = Maps.newConcurrentMap();
150 private final Map<Dpid, TableStatisticsCollector> tableStatsCollectors = Maps.newConcurrentMap();
alshabib3d643ec2014-10-22 18:33:00 -0700151
alshabib1cc04f72014-09-16 16:09:58 -0700152 /**
153 * Creates an OpenFlow host provider.
154 */
155 public OpenFlowRuleProvider() {
Brian O'Connorabafb502014-12-02 22:26:20 -0800156 super(new ProviderId("of", "org.onosproject.provider.openflow"));
alshabib1cc04f72014-09-16 16:09:58 -0700157 }
158
159 @Activate
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700160 protected void activate(ComponentContext context) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700161 cfgService.registerProperties(getClass());
alshabib1cc04f72014-09-16 16:09:58 -0700162 providerService = providerRegistry.register(this);
alshabibeec3a062014-09-17 18:01:26 -0700163 controller.addListener(listener);
164 controller.addEventListener(listener);
alshabib3d643ec2014-10-22 18:33:00 -0700165
Antonio Marsico1c5ae1f2015-12-15 15:31:56 +0100166 modified(context);
167
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700168 pendingBatches = createBatchCache();
ssyoon9030fbcd92015-08-17 10:42:07 +0900169
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700170 createCollectors();
alshabib3d643ec2014-10-22 18:33:00 -0700171
ssyoon9030fbcd92015-08-17 10:42:07 +0900172 log.info("Started with flowPollFrequency = {}, adaptiveFlowSampling = {}",
173 flowPollFrequency, adaptiveFlowSampling);
alshabib1cc04f72014-09-16 16:09:58 -0700174 }
175
176 @Deactivate
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700177 protected void deactivate(ComponentContext context) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700178 cfgService.unregisterProperties(getClass(), false);
179 stopCollectors();
alshabib1cc04f72014-09-16 16:09:58 -0700180 providerRegistry.unregister(this);
181 providerService = null;
182
183 log.info("Stopped");
184 }
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800185
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700186 @Modified
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700187 protected void modified(ComponentContext context) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700188 Dictionary<?, ?> properties = context.getProperties();
189 int newFlowPollFrequency;
190 try {
191 String s = get(properties, "flowPollFrequency");
192 newFlowPollFrequency = isNullOrEmpty(s) ? flowPollFrequency : Integer.parseInt(s.trim());
193
194 } catch (NumberFormatException | ClassCastException e) {
195 newFlowPollFrequency = flowPollFrequency;
196 }
197
198 if (newFlowPollFrequency != flowPollFrequency) {
199 flowPollFrequency = newFlowPollFrequency;
200 adjustRate();
201 }
202
203 log.info("Settings: flowPollFrequency={}", flowPollFrequency);
ssyoon9030fbcd92015-08-17 10:42:07 +0900204
205 boolean newAdaptiveFlowSampling;
206 String s = get(properties, "adaptiveFlowSampling");
207 newAdaptiveFlowSampling = isNullOrEmpty(s) ? adaptiveFlowSampling : Boolean.parseBoolean(s.trim());
208
209 if (newAdaptiveFlowSampling != adaptiveFlowSampling) {
210 // stop previous collector
211 stopCollectors();
212 adaptiveFlowSampling = newAdaptiveFlowSampling;
213 // create new collectors
214 createCollectors();
215 }
216
217 log.info("Settings: adaptiveFlowSampling={}", adaptiveFlowSampling);
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700218 }
219
220 private Cache<Long, InternalCacheEntry> createBatchCache() {
221 return CacheBuilder.newBuilder()
222 .expireAfterWrite(10, TimeUnit.SECONDS)
223 .removalListener((RemovalNotification<Long, InternalCacheEntry> notification) -> {
224 if (notification.getCause() == RemovalCause.EXPIRED) {
225 providerService.batchOperationCompleted(notification.getKey(),
226 notification.getValue().failedCompletion());
227 }
228 }).build();
229 }
230
231 private void createCollectors() {
232 controller.getSwitches().forEach(this::createCollector);
233 }
234
235 private void createCollector(OpenFlowSwitch sw) {
Kavitha Alagesan6704df32016-08-18 15:15:31 +0530236 if (sw == null) {
237 return;
238 }
ssyoon9030fbcd92015-08-17 10:42:07 +0900239 if (adaptiveFlowSampling) {
240 // NewAdaptiveFlowStatsCollector Constructor
Charles Chan14967c22015-12-07 11:11:50 -0800241 NewAdaptiveFlowStatsCollector fsc =
242 new NewAdaptiveFlowStatsCollector(driverService, sw, flowPollFrequency);
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700243 stopCollectorIfNeeded(afsCollectors.put(new Dpid(sw.getId()), fsc));
Palash Kalaa439afe2017-05-16 14:53:15 +0900244 fsc.start();
ssyoon9030fbcd92015-08-17 10:42:07 +0900245 } else {
246 FlowStatsCollector fsc = new FlowStatsCollector(timer, sw, flowPollFrequency);
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700247 stopCollectorIfNeeded(simpleCollectors.put(new Dpid(sw.getId()), fsc));
Palash Kalaa439afe2017-05-16 14:53:15 +0900248 fsc.start();
ssyoon9030fbcd92015-08-17 10:42:07 +0900249 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700250 TableStatisticsCollector tsc = new TableStatisticsCollector(timer, sw, flowPollFrequency);
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700251 stopCollectorIfNeeded(tableStatsCollectors.put(new Dpid(sw.getId()), tsc));
Palash Kalaa439afe2017-05-16 14:53:15 +0900252 tsc.start();
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700253 }
254
255 private void stopCollectorIfNeeded(SwitchDataCollector collector) {
256 if (collector != null) {
257 collector.stop();
258 }
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700259 }
260
261 private void stopCollectors() {
ssyoon9030fbcd92015-08-17 10:42:07 +0900262 if (adaptiveFlowSampling) {
263 // NewAdaptiveFlowStatsCollector Destructor
264 afsCollectors.values().forEach(NewAdaptiveFlowStatsCollector::stop);
265 afsCollectors.clear();
266 } else {
267 simpleCollectors.values().forEach(FlowStatsCollector::stop);
268 simpleCollectors.clear();
269 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700270 tableStatsCollectors.values().forEach(TableStatisticsCollector::stop);
271 tableStatsCollectors.clear();
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700272 }
273
274 private void adjustRate() {
275 DefaultLoad.setPollInterval(flowPollFrequency);
ssyoon9030fbcd92015-08-17 10:42:07 +0900276 if (adaptiveFlowSampling) {
277 // NewAdaptiveFlowStatsCollector calAndPollInterval
278 afsCollectors.values().forEach(fsc -> fsc.adjustCalAndPollInterval(flowPollFrequency));
279 } else {
280 simpleCollectors.values().forEach(fsc -> fsc.adjustPollInterval(flowPollFrequency));
281 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700282 tableStatsCollectors.values().forEach(tsc -> tsc.adjustPollInterval(flowPollFrequency));
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700283 }
284
alshabib1cc04f72014-09-16 16:09:58 -0700285 @Override
286 public void applyFlowRule(FlowRule... flowRules) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800287 for (FlowRule flowRule : flowRules) {
288 applyRule(flowRule);
alshabib35edb1a2014-09-16 17:44:44 -0700289 }
alshabib1cc04f72014-09-16 16:09:58 -0700290 }
291
alshabib35edb1a2014-09-16 17:44:44 -0700292 private void applyRule(FlowRule flowRule) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900293 Dpid dpid = Dpid.dpid(flowRule.deviceId().uri());
294 OpenFlowSwitch sw = controller.getSwitch(dpid);
295
Ray Milkey0ae473d2016-04-04 10:56:47 -0700296 if (sw == null) {
297 return;
298 }
299
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700300 FlowRuleExtPayLoad flowRuleExtPayLoad = flowRule.payLoad();
301 if (hasPayload(flowRuleExtPayLoad)) {
302 OFMessage msg = new ThirdPartyMessage(flowRuleExtPayLoad.payLoad());
jcc3d4e14a2015-04-21 11:32:05 +0800303 sw.sendMsg(msg);
304 return;
305 }
alshabibbdcbb102015-04-22 14:16:38 -0700306 sw.sendMsg(FlowModBuilder.builder(flowRule, sw.factory(),
Jonathan Hart3c259162015-10-21 21:31:19 -0700307 Optional.empty(), Optional.of(driverService)).buildFlowAdd());
alshabib35edb1a2014-09-16 17:44:44 -0700308 }
309
alshabib1cc04f72014-09-16 16:09:58 -0700310 @Override
311 public void removeFlowRule(FlowRule... flowRules) {
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800312 for (FlowRule flowRule : flowRules) {
313 removeRule(flowRule);
alshabib219ebaa2014-09-22 15:41:24 -0700314 }
alshabib1cc04f72014-09-16 16:09:58 -0700315 }
316
alshabib219ebaa2014-09-22 15:41:24 -0700317 private void removeRule(FlowRule flowRule) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900318 Dpid dpid = Dpid.dpid(flowRule.deviceId().uri());
319 OpenFlowSwitch sw = controller.getSwitch(dpid);
320
Ray Milkey0ae473d2016-04-04 10:56:47 -0700321 if (sw == null) {
322 return;
323 }
324
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700325 FlowRuleExtPayLoad flowRuleExtPayLoad = flowRule.payLoad();
326 if (hasPayload(flowRuleExtPayLoad)) {
327 OFMessage msg = new ThirdPartyMessage(flowRuleExtPayLoad.payLoad());
jcc3d4e14a2015-04-21 11:32:05 +0800328 sw.sendMsg(msg);
329 return;
330 }
alshabibbdcbb102015-04-22 14:16:38 -0700331 sw.sendMsg(FlowModBuilder.builder(flowRule, sw.factory(),
Jonathan Hart3c259162015-10-21 21:31:19 -0700332 Optional.empty(), Optional.of(driverService)).buildFlowDel());
alshabib219ebaa2014-09-22 15:41:24 -0700333 }
334
alshabiba68eb962014-09-24 20:34:13 -0700335 @Override
336 public void removeRulesById(ApplicationId id, FlowRule... flowRules) {
337 // TODO: optimize using the ApplicationId
338 removeFlowRule(flowRules);
339 }
340
alshabib193525b2014-10-08 18:58:03 -0700341 @Override
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800342 public void executeBatch(FlowRuleBatchOperation batch) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900343 checkNotNull(batch);
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800344
ssyoon9030fbcd92015-08-17 10:42:07 +0900345 Dpid dpid = Dpid.dpid(batch.deviceId().uri());
346 OpenFlowSwitch sw = controller.getSwitch(dpid);
Madan Jampani84382b92016-06-22 08:26:49 -0700347
348 // If switch no longer exists, simply return.
349 if (sw == null) {
350 Set<FlowRule> failures = ImmutableSet.copyOf(Lists.transform(batch.getOperations(), e -> e.target()));
351 providerService.batchOperationCompleted(batch.id(),
352 new CompletedBatchOperation(false, failures, batch.deviceId()));
353 return;
354 }
355 pendingBatches.put(batch.id(), new InternalCacheEntry(batch));
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800356 OFFlowMod mod;
alshabib193525b2014-10-08 18:58:03 -0700357 for (FlowRuleBatchEntry fbe : batch.getOperations()) {
jcc3d4e14a2015-04-21 11:32:05 +0800358 // flow is the third party privacy flow
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700359
360 FlowRuleExtPayLoad flowRuleExtPayLoad = fbe.target().payLoad();
361 if (hasPayload(flowRuleExtPayLoad)) {
362 OFMessage msg = new ThirdPartyMessage(flowRuleExtPayLoad.payLoad());
jcc3d4e14a2015-04-21 11:32:05 +0800363 sw.sendMsg(msg);
364 continue;
365 }
Thomas Vachuskad07c0922015-10-06 14:48:06 -0700366 FlowModBuilder builder =
Jonathan Hart3c259162015-10-21 21:31:19 -0700367 FlowModBuilder.builder(fbe.target(), sw.factory(),
368 Optional.of(batch.id()), Optional.of(driverService));
Thomas Vachuskad07c0922015-10-06 14:48:06 -0700369 NewAdaptiveFlowStatsCollector collector = afsCollectors.get(dpid);
Sho SHIMIZUaba9d002015-01-29 14:51:04 -0800370 switch (fbe.operator()) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700371 case ADD:
372 mod = builder.buildFlowAdd();
373 break;
374 case REMOVE:
375 mod = builder.buildFlowDel();
376 break;
377 case MODIFY:
378 mod = builder.buildFlowMod();
379 break;
380 default:
381 log.error("Unsupported batch operation {}; skipping flowmod {}",
ssyoon9030fbcd92015-08-17 10:42:07 +0900382 fbe.operator(), fbe);
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700383 continue;
jcc3d4e14a2015-04-21 11:32:05 +0800384 }
Saurav Das3ea46622015-04-22 14:01:34 -0700385 sw.sendMsg(mod);
alshabib193525b2014-10-08 18:58:03 -0700386 }
jcc3d4e14a2015-04-21 11:32:05 +0800387 OFBarrierRequest.Builder builder = sw.factory().buildBarrierRequest()
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800388 .setXid(batch.id());
389 sw.sendMsg(builder.build());
alshabib193525b2014-10-08 18:58:03 -0700390 }
391
Thomas Vachuskaa6c0d042015-04-23 10:17:37 -0700392 private boolean hasPayload(FlowRuleExtPayLoad flowRuleExtPayLoad) {
393 return flowRuleExtPayLoad != null &&
394 flowRuleExtPayLoad.payLoad() != null &&
395 flowRuleExtPayLoad.payLoad().length > 0;
396 }
397
alshabib8f1cf4a2014-09-17 14:44:48 -0700398 private class InternalFlowProvider
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800399 implements OpenFlowSwitchListener, OpenFlowEventListener {
alshabib8f1cf4a2014-09-17 14:44:48 -0700400
alshabib8f1cf4a2014-09-17 14:44:48 -0700401 @Override
402 public void switchAdded(Dpid dpid) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700403 createCollector(controller.getSwitch(dpid));
alshabib8f1cf4a2014-09-17 14:44:48 -0700404 }
405
406 @Override
407 public void switchRemoved(Dpid dpid) {
ssyoon9030fbcd92015-08-17 10:42:07 +0900408 if (adaptiveFlowSampling) {
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700409 stopCollectorIfNeeded(afsCollectors.remove(dpid));
ssyoon9030fbcd92015-08-17 10:42:07 +0900410 } else {
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700411 stopCollectorIfNeeded(simpleCollectors.remove(dpid));
alshabibdfc7afb2014-10-21 20:13:27 -0700412 }
Thomas Vachuskaa394b952016-06-14 15:02:09 -0700413 stopCollectorIfNeeded(tableStatsCollectors.remove(dpid));
alshabib8f1cf4a2014-09-17 14:44:48 -0700414 }
415
416 @Override
Ayaka Koshibe38594c22014-10-22 13:36:12 -0700417 public void switchChanged(Dpid dpid) {
418 }
419
420 @Override
alshabib8f1cf4a2014-09-17 14:44:48 -0700421 public void portChanged(Dpid dpid, OFPortStatus status) {
jcc3d4e14a2015-04-21 11:32:05 +0800422 // TODO: Decide whether to evict flows internal store.
alshabib8f1cf4a2014-09-17 14:44:48 -0700423 }
424
425 @Override
426 public void handleMessage(Dpid dpid, OFMessage msg) {
Ray Milkeyada9e2d2016-04-05 16:42:35 -0700427 if (providerService == null) {
428 // We are shutting down, nothing to be done
429 return;
430 }
Jonathan Harte4e74f02016-03-03 12:57:40 -0800431 DeviceId deviceId = DeviceId.deviceId(Dpid.uri(dpid));
alshabib8f1cf4a2014-09-17 14:44:48 -0700432 switch (msg.getType()) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700433 case FLOW_REMOVED:
434 OFFlowRemoved removed = (OFFlowRemoved) msg;
alshabib6b5cfec2014-09-18 17:42:18 -0700435
Jonathan Harte4e74f02016-03-03 12:57:40 -0800436 FlowEntry fr = new FlowEntryBuilder(deviceId, removed, driverService).build();
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700437 providerService.flowRemoved(fr);
438 break;
439 case STATS_REPLY:
440 if (((OFStatsReply) msg).getStatsType() == OFStatsType.FLOW) {
441 pushFlowMetrics(dpid, (OFFlowStatsReply) msg);
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700442 } else if (((OFStatsReply) msg).getStatsType() == OFStatsType.TABLE) {
443 pushTableStatistics(dpid, (OFTableStatsReply) msg);
sangho89bf6fb2015-02-09 09:33:13 -0800444 }
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700445 break;
446 case BARRIER_REPLY:
447 try {
Thomas Vachuska3358af22015-05-19 18:40:34 -0700448 InternalCacheEntry entry = pendingBatches.getIfPresent(msg.getXid());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800449 if (entry != null) {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700450 providerService
451 .batchOperationCompleted(msg.getXid(),
452 entry.completed());
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800453 } else {
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700454 log.warn("Received unknown Barrier Reply: {}",
455 msg.getXid());
456 }
457 } finally {
458 pendingBatches.invalidate(msg.getXid());
459 }
460 break;
461 case ERROR:
Thomas Vachuska3358af22015-05-19 18:40:34 -0700462 // TODO: This needs to get suppressed in a better way.
463 if (msg instanceof OFBadRequestErrorMsg &&
464 ((OFBadRequestErrorMsg) msg).getCode() == OFBadRequestCode.BAD_TYPE) {
465 log.debug("Received error message {} from {}", msg, dpid);
466 } else {
467 log.warn("Received error message {} from {}", msg, dpid);
468 }
Prince Pereira788797e2016-08-10 11:24:14 +0530469 handleErrorMsg(deviceId, msg);
Ray Milkey4fd3ceb2015-12-10 14:43:08 -0800470 break;
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700471 default:
472 log.debug("Unhandled message type: {}", msg.getType());
alshabib8f1cf4a2014-09-17 14:44:48 -0700473 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700474 }
475
Prince Pereira788797e2016-08-10 11:24:14 +0530476 private void handleErrorMsg(DeviceId deviceId, OFMessage msg) {
Prince Pereira141ed812016-09-02 19:03:18 +0530477 InternalCacheEntry entry = pendingBatches.getIfPresent(msg.getXid());
Prince Pereira788797e2016-08-10 11:24:14 +0530478 OFErrorMsg error = (OFErrorMsg) msg;
479 OFMessage ofMessage = null;
480 switch (error.getErrType()) {
481 case BAD_ACTION:
482 OFBadActionErrorMsg baErrorMsg = (OFBadActionErrorMsg) error;
483 if (baErrorMsg.getData().getParsedMessage().isPresent()) {
484 ofMessage = baErrorMsg.getData().getParsedMessage().get();
485 }
486 break;
487 case BAD_INSTRUCTION:
488 OFBadInstructionErrorMsg biErrorMsg = (OFBadInstructionErrorMsg) error;
489 if (biErrorMsg.getData().getParsedMessage().isPresent()) {
490 ofMessage = biErrorMsg.getData().getParsedMessage().get();
491 }
492 break;
493 case BAD_MATCH:
494 OFBadMatchErrorMsg bmErrorMsg = (OFBadMatchErrorMsg) error;
495 if (bmErrorMsg.getData().getParsedMessage().isPresent()) {
496 ofMessage = bmErrorMsg.getData().getParsedMessage().get();
497 }
498 break;
499 case FLOW_MOD_FAILED:
500 OFFlowModFailedErrorMsg fmFailed = (OFFlowModFailedErrorMsg) error;
501 if (fmFailed.getData().getParsedMessage().isPresent()) {
502 ofMessage = fmFailed.getData().getParsedMessage().get();
503 }
504 break;
505 default:
506 // Do nothing.
507 return;
508 }
Prince Pereira141ed812016-09-02 19:03:18 +0530509
Prince Pereira788797e2016-08-10 11:24:14 +0530510 if (ofMessage != null) {
Prince Pereira141ed812016-09-02 19:03:18 +0530511
Prince Pereira788797e2016-08-10 11:24:14 +0530512 if (entry != null) {
513 OFFlowMod ofFlowMod = (OFFlowMod) ofMessage;
514 entry.appendFailure(new FlowEntryBuilder(deviceId, ofFlowMod, driverService).build());
515 } else {
516 log.error("No matching batch for this error: {}", error);
517 }
Prince Pereira141ed812016-09-02 19:03:18 +0530518
Prince Pereira788797e2016-08-10 11:24:14 +0530519 } else {
Prince Pereira141ed812016-09-02 19:03:18 +0530520
521 U64 cookieId = readCookieIdFromOFErrorMsg(error, msg.getVersion());
522
523 if (cookieId != null) {
524 long flowId = cookieId.getValue();
525
526 if (entry != null) {
527 for (FlowRuleBatchEntry fbEntry : entry.operation.getOperations()) {
528 if (fbEntry.target().id().value() == flowId) {
529 entry.appendFailure(fbEntry.target());
530 break;
531 }
532 }
533 } else {
534 log.error("No matching batch for this error: {}", error);
535 }
536
537 } else {
538 log.error("Flow installation failed but switch " +
539 "didn't tell us which one.");
540 }
Prince Pereira788797e2016-08-10 11:24:14 +0530541 }
542 }
543
Prince Pereira141ed812016-09-02 19:03:18 +0530544 /**
545 * Reading cookieId from OFErrorMsg.
546 *
547 * Loxigen OpenFlow API failed in parsing error messages because of
548 * 64 byte data truncation based on OpenFlow specs. The method written
549 * is a workaround to extract the cookieId from the packet till the
550 * issue is resolved in Loxigen OpenFlow code.
551 * Ref: https://groups.google.com/a/onosproject.org/forum/#!topic
552 * /onos-dev/_KwlHZDllLE
553 *
554 * @param msg OF error message
555 * @param ofVersion Openflow version
556 * @return cookieId
557 */
558 private U64 readCookieIdFromOFErrorMsg(OFErrorMsg msg,
559 OFVersion ofVersion) {
560
561 if (ofVersion.wireVersion < OFVersion.OF_13.wireVersion) {
562 log.debug("Unhandled error msg with OF version {} " +
563 "which is less than {}",
564 ofVersion, OFVersion.OF_13);
565 return null;
566 }
567
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700568 ByteBuf bb = Unpooled.wrappedBuffer(msg.getData().getData());
Prince Pereira141ed812016-09-02 19:03:18 +0530569
570 if (bb.readableBytes() < MIN_EXPECTED_BYTE_LEN) {
571 log.debug("Wrong length: Expected to be >= {}, was: {}",
572 MIN_EXPECTED_BYTE_LEN, bb.readableBytes());
573 return null;
574 }
575
576 byte ofVer = bb.readByte();
577
578 if (ofVer != ofVersion.wireVersion) {
579 log.debug("Wrong version: Expected={}, got={}",
580 ofVersion.wireVersion, ofVer);
581 return null;
582 }
583
584 byte type = bb.readByte();
585
586 if (type != OFType.FLOW_MOD.ordinal()) {
587 log.debug("Wrong type: Expected={}, got={}",
588 OFType.FLOW_MOD.ordinal(), type);
589 return null;
590 }
591
592 int length = U16.f(bb.readShort());
593
594 if (length < MIN_EXPECTED_BYTE_LEN) {
595 log.debug("Wrong length: Expected to be >= {}, was: {}",
596 MIN_EXPECTED_BYTE_LEN, length);
597 return null;
598 }
599
600 bb.skipBytes(SKIP_BYTES);
601 return U64.ofRaw(bb.readLong());
602 }
603
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700604 @Override
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700605 public void receivedRoleReply(Dpid dpid, RoleState requested,
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800606 RoleState response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700607 // Do nothing here for now.
608 }
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700609
sangho89bf6fb2015-02-09 09:33:13 -0800610 private void pushFlowMetrics(Dpid dpid, OFFlowStatsReply replies) {
alshabib64def642014-12-02 23:27:37 -0800611
alshabib54ce5892014-09-23 17:50:51 -0700612 DeviceId did = DeviceId.deviceId(Dpid.uri(dpid));
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900613 NewAdaptiveFlowStatsCollector afsc = afsCollectors.get(dpid);
alshabib54ce5892014-09-23 17:50:51 -0700614
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900615 if (adaptiveFlowSampling && afsc != null) {
616 List<FlowEntry> flowEntries = replies.getEntries().stream()
617 .map(entry -> new FlowEntryBuilder(did, entry, driverService).withSetAfsc(afsc).build())
618 .collect(Collectors.toList());
alshabib54ce5892014-09-23 17:50:51 -0700619
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900620 // Check that OFFlowStatsReply Xid is same with the one of OFFlowStatsRequest?
621 if (afsc.getFlowMissingXid() != NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID) {
622 log.debug("OpenFlowRuleProvider:pushFlowMetrics, flowMissingXid={}, "
623 + "OFFlowStatsReply Xid={}, for {}",
624 afsc.getFlowMissingXid(), replies.getXid(), dpid);
625 if (afsc.getFlowMissingXid() == replies.getXid()) {
626 // call entire flow stats update with flowMissing synchronization.
627 // used existing pushFlowMetrics
628 providerService.pushFlowMetrics(did, flowEntries);
ssyoon9030fbcd92015-08-17 10:42:07 +0900629 }
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900630 // reset flowMissingXid to NO_FLOW_MISSING_XID
631 afsc.setFlowMissingXid(NewAdaptiveFlowStatsCollector.NO_FLOW_MISSING_XID);
632 } else {
633 // call individual flow stats update
634 providerService.pushFlowMetricsWithoutFlowMissing(did, flowEntries);
ssyoon9030fbcd92015-08-17 10:42:07 +0900635 }
636 } else {
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900637 List<FlowEntry> flowEntries = replies.getEntries().stream()
638 .map(entry -> new FlowEntryBuilder(did, entry, driverService).build())
639 .collect(Collectors.toList());
640
ssyoon9030fbcd92015-08-17 10:42:07 +0900641 // call existing entire flow stats update with flowMissing synchronization
642 providerService.pushFlowMetrics(did, flowEntries);
643 }
alshabib5c370ff2014-09-18 10:12:14 -0700644 }
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700645
646 private void pushTableStatistics(Dpid dpid, OFTableStatsReply replies) {
647
648 DeviceId did = DeviceId.deviceId(Dpid.uri(dpid));
649 List<TableStatisticsEntry> tableStatsEntries = replies.getEntries().stream()
650 .map(entry -> buildTableStatistics(did, entry))
651 .filter(Objects::nonNull)
652 .collect(Collectors.toList());
653 providerService.pushTableStatistics(did, tableStatsEntries);
654 }
655
656 private TableStatisticsEntry buildTableStatistics(DeviceId deviceId,
657 OFTableStatsEntry ofEntry) {
658 TableStatisticsEntry entry = null;
659 if (ofEntry != null) {
660 entry = new DefaultTableStatisticsEntry(deviceId,
661 ofEntry.getTableId().getValue(),
662 ofEntry.getActiveCount(),
663 ofEntry.getLookupCount().getValue(),
664 ofEntry.getMatchedCount().getValue());
665 }
666
667 return entry;
668
669 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700670 }
alshabib1cc04f72014-09-16 16:09:58 -0700671
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800672 /**
jcc3d4e14a2015-04-21 11:32:05 +0800673 * The internal cache entry holding the original request as well as
674 * accumulating the any failures along the way.
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700675 * <p/>
jcc3d4e14a2015-04-21 11:32:05 +0800676 * If this entry is evicted from the cache then the entire operation is
677 * considered failed. Otherwise, only the failures reported by the device
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800678 * will be propagated up.
679 */
680 private class InternalCacheEntry {
alshabib902d41b2014-10-07 16:52:05 -0700681
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800682 private final FlowRuleBatchOperation operation;
683 private final Set<FlowRule> failures = Sets.newConcurrentHashSet();
alshabib193525b2014-10-08 18:58:03 -0700684
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800685 public InternalCacheEntry(FlowRuleBatchOperation operation) {
686 this.operation = operation;
alshabib902d41b2014-10-07 16:52:05 -0700687 }
688
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800689 /**
690 * Appends a failed rule to the set of failed items.
jcc3d4e14a2015-04-21 11:32:05 +0800691 *
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800692 * @param rule the failed rule
693 */
694 public void appendFailure(FlowRule rule) {
695 failures.add(rule);
Thomas Vachuska9b2da212014-11-10 19:30:25 -0800696 }
697
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800698 /**
699 * Fails the entire batch and returns the failed operation.
jcc3d4e14a2015-04-21 11:32:05 +0800700 *
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800701 * @return the failed operation
702 */
703 public CompletedBatchOperation failedCompletion() {
704 Set<FlowRule> fails = operation.getOperations().stream()
705 .map(op -> op.target()).collect(Collectors.toSet());
jcc3d4e14a2015-04-21 11:32:05 +0800706 return new CompletedBatchOperation(false,
707 Collections
708 .unmodifiableSet(fails),
709 operation.deviceId());
alshabib902d41b2014-10-07 16:52:05 -0700710 }
711
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800712 /**
713 * Returns the completed operation and whether the batch suceeded.
jcc3d4e14a2015-04-21 11:32:05 +0800714 *
Brian O'Connor72cb19a2015-01-16 16:14:41 -0800715 * @return the completed operation
716 */
717 public CompletedBatchOperation completed() {
jcc3d4e14a2015-04-21 11:32:05 +0800718 return new CompletedBatchOperation(
Thomas Vachuska75aaa672015-04-29 12:24:43 -0700719 failures.isEmpty(),
720 Collections
721 .unmodifiableSet(failures),
722 operation.deviceId());
alshabib902d41b2014-10-07 16:52:05 -0700723 }
alshabib902d41b2014-10-07 16:52:05 -0700724 }
alshabiba68eb962014-09-24 20:34:13 -0700725
alshabib1cc04f72014-09-16 16:09:58 -0700726}