blob: 3564750fb7f415c183c85a417d6781ac33208d24 [file] [log] [blame]
Simon Hunt026a2872017-11-13 17:09:43 -08001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
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 */
16
17package org.onosproject.t3.impl;
18
Andrea Campanella17d45192018-01-18 17:11:42 +010019import com.google.common.base.Preconditions;
Andrea Campanellae4084402017-12-15 15:27:31 +010020import com.google.common.collect.ImmutableList;
Andrea Campanella696ef032018-02-27 18:03:17 +010021import com.google.common.collect.ImmutableSet;
Andrea Campanellae4084402017-12-15 15:27:31 +010022import com.google.common.collect.Lists;
Andrea Campanella5befe1c2018-02-27 14:50:45 +010023import com.google.common.collect.Sets;
Andrea Campanella6a614fa2018-02-21 14:28:20 +010024import org.apache.commons.lang3.tuple.Pair;
Simon Hunt026a2872017-11-13 17:09:43 -080025import org.apache.felix.scr.annotations.Component;
26import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.Service;
Andrea Campanella55c3f422018-02-08 17:10:11 +010029import org.onlab.packet.IpAddress;
Andrea Campanellae4084402017-12-15 15:27:31 +010030import org.onlab.packet.VlanId;
Andrea Campanella54923d62018-01-23 12:46:04 +010031import org.onosproject.cluster.NodeId;
32import org.onosproject.mastership.MastershipService;
Simon Hunt026a2872017-11-13 17:09:43 -080033import org.onosproject.net.ConnectPoint;
Andrea Campanellae4084402017-12-15 15:27:31 +010034import org.onosproject.net.DeviceId;
35import org.onosproject.net.Host;
Andrea Campanella55c3f422018-02-08 17:10:11 +010036import org.onosproject.net.HostId;
Andrea Campanellae4084402017-12-15 15:27:31 +010037import org.onosproject.net.Link;
Andrea Campanella1445f7a2018-02-07 12:00:12 +010038import org.onosproject.net.Port;
Andrea Campanellae4084402017-12-15 15:27:31 +010039import org.onosproject.net.PortNumber;
Andrea Campanella55c3f422018-02-08 17:10:11 +010040import org.onosproject.net.config.ConfigException;
41import org.onosproject.net.config.NetworkConfigService;
42import org.onosproject.net.config.basics.InterfaceConfig;
Andrea Campanella17d45192018-01-18 17:11:42 +010043import org.onosproject.net.device.DeviceService;
Andrea Campanellae4084402017-12-15 15:27:31 +010044import org.onosproject.net.driver.DriverService;
Andrea Campanella4c6170a2018-01-17 16:34:51 +010045import org.onosproject.net.edge.EdgePortService;
Andrea Campanellae4084402017-12-15 15:27:31 +010046import org.onosproject.net.flow.DefaultTrafficSelector;
47import org.onosproject.net.flow.FlowEntry;
48import org.onosproject.net.flow.FlowRule;
Simon Hunt026a2872017-11-13 17:09:43 -080049import org.onosproject.net.flow.FlowRuleService;
Andrea Campanellae4084402017-12-15 15:27:31 +010050import org.onosproject.net.flow.IndexTableId;
51import org.onosproject.net.flow.TableId;
Simon Hunt026a2872017-11-13 17:09:43 -080052import org.onosproject.net.flow.TrafficSelector;
Andrea Campanellae4084402017-12-15 15:27:31 +010053import org.onosproject.net.flow.criteria.Criteria;
54import org.onosproject.net.flow.criteria.Criterion;
55import org.onosproject.net.flow.criteria.EthCriterion;
56import org.onosproject.net.flow.criteria.EthTypeCriterion;
57import org.onosproject.net.flow.criteria.IPCriterion;
Andrea Campanellae6798012018-02-06 15:46:52 +010058import org.onosproject.net.flow.criteria.VlanIdCriterion;
Andrea Campanellae4084402017-12-15 15:27:31 +010059import org.onosproject.net.flow.instructions.Instruction;
60import org.onosproject.net.flow.instructions.Instructions;
61import org.onosproject.net.flow.instructions.Instructions.OutputInstruction;
62import org.onosproject.net.flow.instructions.L2ModificationInstruction;
63import org.onosproject.net.group.Group;
64import org.onosproject.net.group.GroupBucket;
Simon Hunt026a2872017-11-13 17:09:43 -080065import org.onosproject.net.group.GroupService;
Andrea Campanellae4084402017-12-15 15:27:31 +010066import org.onosproject.net.host.HostService;
Andrea Campanella55c3f422018-02-08 17:10:11 +010067import org.onosproject.net.host.InterfaceIpAddress;
68import org.onosproject.net.intf.Interface;
Andrea Campanellae4084402017-12-15 15:27:31 +010069import org.onosproject.net.link.LinkService;
Andrea Campanella08d07e12018-03-07 14:27:54 -080070import org.onosproject.routeservice.ResolvedRoute;
71import org.onosproject.routeservice.RouteService;
Andrea Campanella55c3f422018-02-08 17:10:11 +010072import org.onosproject.segmentrouting.config.SegmentRoutingDeviceConfig;
Andrea Campanellae4084402017-12-15 15:27:31 +010073import org.onosproject.t3.api.GroupsInDevice;
Simon Hunt026a2872017-11-13 17:09:43 -080074import org.onosproject.t3.api.StaticPacketTrace;
75import org.onosproject.t3.api.TroubleshootService;
76import org.slf4j.Logger;
77
Andrea Campanellae4084402017-12-15 15:27:31 +010078import java.net.UnknownHostException;
79import java.util.ArrayList;
Andrea Campanella54923d62018-01-23 12:46:04 +010080import java.util.Collection;
Andrea Campanellae4084402017-12-15 15:27:31 +010081import java.util.Collections;
82import java.util.Comparator;
83import java.util.HashSet;
84import java.util.List;
Andrea Campanella08d07e12018-03-07 14:27:54 -080085import java.util.Optional;
Andrea Campanellae4084402017-12-15 15:27:31 +010086import java.util.Set;
87import java.util.stream.Collectors;
88
89import static org.onlab.packet.EthType.EtherType;
Andrea Campanellae6798012018-02-06 15:46:52 +010090import static org.onosproject.net.flow.TrafficSelector.Builder;
Andrea Campanellae4084402017-12-15 15:27:31 +010091import static org.onosproject.net.flow.instructions.Instructions.GroupInstruction;
Andrea Campanella94c594a2018-02-06 18:58:40 +010092import static org.onosproject.net.flow.instructions.L2ModificationInstruction.ModEtherInstruction;
93import static org.onosproject.net.flow.instructions.L2ModificationInstruction.ModMplsHeaderInstruction;
94import static org.onosproject.net.flow.instructions.L2ModificationInstruction.ModMplsLabelInstruction;
95import static org.onosproject.net.flow.instructions.L2ModificationInstruction.ModVlanIdInstruction;
Andrea Campanella4c6170a2018-01-17 16:34:51 +010096import static org.onosproject.t3.impl.TroubleshootUtils.compareMac;
Simon Hunt026a2872017-11-13 17:09:43 -080097import static org.slf4j.LoggerFactory.getLogger;
98
99/**
Andrea Campanellae4084402017-12-15 15:27:31 +0100100 * Manager to troubleshoot packets inside the network.
101 * Given a representation of a packet follows it's path in the network according to the existing flows and groups in
102 * the devices.
Simon Hunt026a2872017-11-13 17:09:43 -0800103 */
104@Service
105@Component(immediate = true)
106public class TroubleshootManager implements TroubleshootService {
107
108 private static final Logger log = getLogger(TroubleshootManager.class);
109
Andrea Campanella1445f7a2018-02-07 12:00:12 +0100110 static final String PACKET_TO_CONTROLLER = "Packet goes to the controller";
111
Simon Hunt026a2872017-11-13 17:09:43 -0800112 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
113 protected FlowRuleService flowRuleService;
114
115 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
116 protected GroupService groupService;
117
Andrea Campanellae4084402017-12-15 15:27:31 +0100118 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
119 protected LinkService linkService;
Simon Hunt026a2872017-11-13 17:09:43 -0800120
Andrea Campanellae4084402017-12-15 15:27:31 +0100121 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
122 protected HostService hostService;
123
124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
125 protected DriverService driverService;
Simon Hunt026a2872017-11-13 17:09:43 -0800126
Andrea Campanella17d45192018-01-18 17:11:42 +0100127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
128 protected DeviceService deviceService;
129
Andrea Campanella54923d62018-01-23 12:46:04 +0100130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
131 protected MastershipService mastershipService;
132
Andrea Campanella55c3f422018-02-08 17:10:11 +0100133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
134 protected NetworkConfigService networkConfigService;
135
Andrea Campanella4c6170a2018-01-17 16:34:51 +0100136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
137 protected EdgePortService edgePortService;
138
Andrea Campanella08d07e12018-03-07 14:27:54 -0800139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
140 protected RouteService routeService;
141
Andrea Campanella55c3f422018-02-08 17:10:11 +0100142 @Override
Andrea Campanella6a614fa2018-02-21 14:28:20 +0100143 public List<StaticPacketTrace> pingAll(EtherType type) {
144 ImmutableList.Builder<StaticPacketTrace> tracesBuilder = ImmutableList.builder();
145 hostService.getHosts().forEach(host -> {
146 List<IpAddress> ipAddresses = getIpAddresses(host, type, false);
147 if (ipAddresses.size() > 0) {
Andrea Campanella5befe1c2018-02-27 14:50:45 +0100148 //check if the host has only local IPs of that ETH type
149 boolean onlyLocalSrc = ipAddresses.size() == 1 && ipAddresses.get(0).isLinkLocal();
Andrea Campanella6a614fa2018-02-21 14:28:20 +0100150 hostService.getHosts().forEach(hostToPing -> {
151 List<IpAddress> ipAddressesToPing = getIpAddresses(hostToPing, type, false);
Andrea Campanella5befe1c2018-02-27 14:50:45 +0100152 //check if the other host has only local IPs of that ETH type
153 boolean onlyLocalDst = ipAddressesToPing.size() == 1 && ipAddressesToPing.get(0).isLinkLocal();
154 boolean sameLocation = Sets.intersection(host.locations(), hostToPing.locations()).size() > 0;
155 //Trace is done only if they are both local and under the same location
156 // or not local and if they are not the same host.
157 if (((sameLocation && onlyLocalDst && onlyLocalSrc) ||
158 (!onlyLocalSrc && !onlyLocalDst && ipAddressesToPing.size() > 0))
159 && !host.equals(hostToPing)) {
Andrea Campanella696ef032018-02-27 18:03:17 +0100160 tracesBuilder.addAll(trace(host.id(), hostToPing.id(), type));
Andrea Campanella6a614fa2018-02-21 14:28:20 +0100161 }
162 });
163 }
164 });
165 return tracesBuilder.build();
166 }
167
168 @Override
Andrea Campanella0cc6acd2018-02-28 16:43:16 +0100169 public Generator<Set<StaticPacketTrace>> pingAllGenerator(EtherType type) {
170 return new PingAllGenerator(type, hostService, this);
171 }
172
173 @Override
Andrea Campanella696ef032018-02-27 18:03:17 +0100174 public Set<StaticPacketTrace> trace(HostId sourceHost, HostId destinationHost, EtherType etherType) {
Andrea Campanella55c3f422018-02-08 17:10:11 +0100175 Host source = hostService.getHost(sourceHost);
176 Host destination = hostService.getHost(destinationHost);
177
Andrea Campanella6a614fa2018-02-21 14:28:20 +0100178 //Temporary trace to fail in case we don't have enough information or what is provided is incoherent
179 StaticPacketTrace failTrace = new StaticPacketTrace(null, null, Pair.of(source, destination));
Andrea Campanella55c3f422018-02-08 17:10:11 +0100180
181 if (source == null) {
182 failTrace.addResultMessage("Source Host " + sourceHost + " does not exist");
Andrea Campanella696ef032018-02-27 18:03:17 +0100183 return ImmutableSet.of(failTrace);
Andrea Campanella55c3f422018-02-08 17:10:11 +0100184 }
185
186 if (destination == null) {
187 failTrace.addResultMessage("Destination Host " + destinationHost + " does not exist");
Andrea Campanella696ef032018-02-27 18:03:17 +0100188 return ImmutableSet.of(failTrace);
Andrea Campanella55c3f422018-02-08 17:10:11 +0100189 }
190
191 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder()
Andrea Campanella55c3f422018-02-08 17:10:11 +0100192 .matchEthType(etherType.ethType().toShort())
193 .matchEthDst(source.mac())
194 .matchVlanId(source.vlan());
195
196
Andrea Campanella55c3f422018-02-08 17:10:11 +0100197 try {
198 //if the location deviceId is the same, the two hosts are under same subnet and vlan on the interface
199 // we are under same leaf so it's L2 Unicast.
200 if (areBridged(source, destination)) {
201 selectorBuilder.matchEthDst(destination.mac());
Andrea Campanella696ef032018-02-27 18:03:17 +0100202 ImmutableSet.Builder<StaticPacketTrace> traces = ImmutableSet.builder();
203 source.locations().forEach(hostLocation -> {
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800204 selectorBuilder.matchInPort(hostLocation.port());
Andrea Campanella696ef032018-02-27 18:03:17 +0100205 StaticPacketTrace trace = trace(selectorBuilder.build(), hostLocation);
206 trace.addEndpointHosts(Pair.of(source, destination));
207 traces.add(trace);
208 });
209 return traces.build();
Andrea Campanella55c3f422018-02-08 17:10:11 +0100210 }
211
212 //handle the IPs for src and dst in case of L3
213 if (etherType.equals(EtherType.IPV4) || etherType.equals(EtherType.IPV6)) {
214
215 //Match on the source IP
216 if (!matchIP(source, failTrace, selectorBuilder, etherType, true)) {
Andrea Campanella696ef032018-02-27 18:03:17 +0100217 return ImmutableSet.of(failTrace);
Andrea Campanella55c3f422018-02-08 17:10:11 +0100218 }
219
220 //Match on destination IP
221 if (!matchIP(destination, failTrace, selectorBuilder, etherType, false)) {
Andrea Campanella696ef032018-02-27 18:03:17 +0100222 return ImmutableSet.of(failTrace);
Andrea Campanella55c3f422018-02-08 17:10:11 +0100223 }
224
225 } else {
226 failTrace.addResultMessage("Host based trace supports only IPv4 or IPv6 as EtherType, " +
227 "please use packet based");
Andrea Campanella696ef032018-02-27 18:03:17 +0100228 return ImmutableSet.of(failTrace);
Andrea Campanella55c3f422018-02-08 17:10:11 +0100229 }
230
231 //l3 unicast, we get the dst mac of the leaf the source is connected to from netcfg
232 SegmentRoutingDeviceConfig segmentRoutingConfig = networkConfigService.getConfig(source.location()
233 .deviceId(), SegmentRoutingDeviceConfig.class);
234 if (segmentRoutingConfig != null) {
235 selectorBuilder.matchEthDst(segmentRoutingConfig.routerMac());
236 } else {
237 failTrace.addResultMessage("Can't get " + source.location().deviceId() +
238 " router MAC from segment routing config can't perform L3 tracing.");
239 }
Andrea Campanella696ef032018-02-27 18:03:17 +0100240 ImmutableSet.Builder<StaticPacketTrace> traces = ImmutableSet.builder();
241 source.locations().forEach(hostLocation -> {
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800242 selectorBuilder.matchInPort(hostLocation.port());
Andrea Campanella696ef032018-02-27 18:03:17 +0100243 StaticPacketTrace trace = trace(selectorBuilder.build(), hostLocation);
244 trace.addEndpointHosts(Pair.of(source, destination));
245 traces.add(trace);
246 });
247 return traces.build();
Andrea Campanella55c3f422018-02-08 17:10:11 +0100248
249 } catch (ConfigException e) {
250 failTrace.addResultMessage("Can't get config " + e.getMessage());
Andrea Campanella696ef032018-02-27 18:03:17 +0100251 return ImmutableSet.of(failTrace);
Andrea Campanella55c3f422018-02-08 17:10:11 +0100252 }
253 }
254
255 /**
256 * Matches src and dst IPs based on host information.
257 *
258 * @param host the host
259 * @param failTrace the trace to use in case of failure
260 * @param selectorBuilder the packet we are building to trace
261 * @param etherType the traffic type
262 * @param src is this src host or dst host
263 * @return true if properly matched
264 */
265 private boolean matchIP(Host host, StaticPacketTrace failTrace, Builder selectorBuilder,
266 EtherType etherType, boolean src) {
Andrea Campanella6a614fa2018-02-21 14:28:20 +0100267 List<IpAddress> ips = getIpAddresses(host, etherType, true);
Andrea Campanella55c3f422018-02-08 17:10:11 +0100268
269 if (ips.size() > 0) {
Andrea Campanellabf8d9302018-02-21 14:43:21 +0100270 if (etherType.equals(EtherType.IPV4)) {
271 if (src) {
272 selectorBuilder.matchIPSrc(ips.get(0).toIpPrefix());
273 } else {
274 selectorBuilder.matchIPDst(ips.get(0).toIpPrefix());
275 }
276 } else if (etherType.equals(EtherType.IPV6)) {
277 if (src) {
278 selectorBuilder.matchIPv6Src(ips.get(0).toIpPrefix());
279 } else {
280 selectorBuilder.matchIPv6Dst(ips.get(0).toIpPrefix());
281 }
Andrea Campanella55c3f422018-02-08 17:10:11 +0100282 }
283 } else {
284 failTrace.addResultMessage("Host " + host + " has no " + etherType + " address");
285 return false;
286 }
287 return true;
288 }
289
Andrea Campanella0cc6acd2018-02-28 16:43:16 +0100290 List<IpAddress> getIpAddresses(Host host, EtherType etherType, boolean checklocal) {
Andrea Campanella6a614fa2018-02-21 14:28:20 +0100291 return host.ipAddresses().stream().filter(ipAddress -> {
292 boolean correctIp = false;
293 if (etherType.equals(EtherType.IPV4)) {
294 correctIp = ipAddress.isIp4();
295 } else if (etherType.equals(EtherType.IPV6)) {
296 correctIp = ipAddress.isIp6();
297 }
298 if (checklocal) {
299 correctIp = correctIp && !ipAddress.isLinkLocal();
300 }
301 return correctIp;
302 }).collect(Collectors.toList());
303 }
304
Andrea Campanella55c3f422018-02-08 17:10:11 +0100305 /**
306 * Checks that two hosts are bridged (L2Unicast).
307 *
308 * @param source the source host
309 * @param destination the destination host
310 * @return true if bridged.
311 * @throws ConfigException if config can't be properly retrieved
312 */
313 private boolean areBridged(Host source, Host destination) throws ConfigException {
314
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800315 //If the locations is not the same we don't even check vlan or subnets
316 if (Collections.disjoint(source.locations(), destination.locations())) {
317 return false;
318 }
319
320 if (!source.vlan().equals(VlanId.NONE) && !destination.vlan().equals(VlanId.NONE)
321 && !source.vlan().equals(destination.vlan())) {
Andrea Campanella55c3f422018-02-08 17:10:11 +0100322 return false;
323 }
324
325 InterfaceConfig interfaceCfgH1 = networkConfigService.getConfig(source.location(), InterfaceConfig.class);
326 InterfaceConfig interfaceCfgH2 = networkConfigService.getConfig(destination.location(), InterfaceConfig.class);
327 if (interfaceCfgH1 != null && interfaceCfgH2 != null) {
328
329 //following can be optimized but for clarity is left as is
330 Interface intfH1 = interfaceCfgH1.getInterfaces().stream().findFirst().get();
331 Interface intfH2 = interfaceCfgH2.getInterfaces().stream().findFirst().get();
332
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800333 if (source.vlan().equals(VlanId.NONE) && !destination.vlan().equals(VlanId.NONE)) {
334 return intfH1.vlanUntagged().equals(destination.vlan()) ||
335 intfH1.vlanNative().equals(destination.vlan());
Andrea Campanella55c3f422018-02-08 17:10:11 +0100336 }
337
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800338 if (!source.vlan().equals(VlanId.NONE) && destination.vlan().equals(VlanId.NONE)) {
339 return intfH2.vlanUntagged().equals(source.vlan()) ||
340 intfH2.vlanNative().equals(source.vlan());
341 }
342
343 if (!intfH1.vlanNative().equals(intfH2.vlanNative())) {
Andrea Campanella55c3f422018-02-08 17:10:11 +0100344 return false;
345 }
346
347 if (!intfH1.vlanUntagged().equals(intfH2.vlanUntagged())) {
348 return false;
349 }
350
351 List<InterfaceIpAddress> intersection = new ArrayList<>(intfH1.ipAddressesList());
352 intersection.retainAll(intfH2.ipAddressesList());
353 if (intersection.size() == 0) {
354 return false;
355 }
356 }
357 return true;
358 }
359
Simon Hunt026a2872017-11-13 17:09:43 -0800360 @Override
361 public StaticPacketTrace trace(TrafficSelector packet, ConnectPoint in) {
Andrea Campanellae4084402017-12-15 15:27:31 +0100362 log.info("Tracing packet {} coming in through {}", packet, in);
Andrea Campanella17d45192018-01-18 17:11:42 +0100363 //device must exist in ONOS
364 Preconditions.checkNotNull(deviceService.getDevice(in.deviceId()),
365 "Device " + in.deviceId() + " must exist in ONOS");
366
Andrea Campanellae4084402017-12-15 15:27:31 +0100367 StaticPacketTrace trace = new StaticPacketTrace(packet, in);
Andrea Campanella696ef032018-02-27 18:03:17 +0100368 boolean isDualHomed = getHosts(trace).stream().anyMatch(host -> host.locations().size() > 1);
Andrea Campanellae4084402017-12-15 15:27:31 +0100369 //FIXME this can be done recursively
Andrea Campanella696ef032018-02-27 18:03:17 +0100370 trace = traceInDevice(trace, packet, in, isDualHomed);
Andrea Campanellae4084402017-12-15 15:27:31 +0100371 //Building output connect Points
372 List<ConnectPoint> path = new ArrayList<>();
Andrea Campanella696ef032018-02-27 18:03:17 +0100373 trace = getTrace(path, in, trace, isDualHomed);
Andrea Campanellae4084402017-12-15 15:27:31 +0100374 return trace;
375 }
376
377 /**
378 * Computes a trace for a give packet that start in the network at the given connect point.
379 *
380 * @param completePath the path traversed by the packet
381 * @param in the input connect point
382 * @param trace the trace to build
Andrea Campanella696ef032018-02-27 18:03:17 +0100383 * @param isDualHomed true if the trace we are doing starts or ends in a dual homed host
Andrea Campanellae4084402017-12-15 15:27:31 +0100384 * @return the build trace for that packet.
385 */
Andrea Campanella696ef032018-02-27 18:03:17 +0100386 private StaticPacketTrace getTrace(List<ConnectPoint> completePath, ConnectPoint in, StaticPacketTrace trace,
387 boolean isDualHomed) {
Andrea Campanellae4084402017-12-15 15:27:31 +0100388
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100389 log.debug("------------------------------------------------------------");
390
Andrea Campanellae4084402017-12-15 15:27:31 +0100391 //if the trace already contains the input connect point there is a loop
392 if (pathContainsDevice(completePath, in.deviceId())) {
393 trace.addResultMessage("Loop encountered in device " + in.deviceId());
Andrea Campanella3ddbadb2018-03-09 14:52:10 -0800394 completePath.add(in);
395 trace.addCompletePath(completePath);
Andrea Campanellae4084402017-12-15 15:27:31 +0100396 return trace;
397 }
398
399 //let's add the input connect point
400 completePath.add(in);
401
402 //If the trace has no outputs for the given input we stop here
403 if (trace.getGroupOuputs(in.deviceId()) == null) {
404 computePath(completePath, trace, null);
405 trace.addResultMessage("No output out of device " + in.deviceId() + ". Packet is dropped");
406 return trace;
407 }
Andrea Campanella7d3cf652018-01-22 15:10:30 +0100408
Andrea Campanellae4084402017-12-15 15:27:31 +0100409 //If the trace has ouputs we analyze them all
410 for (GroupsInDevice outputPath : trace.getGroupOuputs(in.deviceId())) {
Andrea Campanella54923d62018-01-23 12:46:04 +0100411
412 ConnectPoint cp = outputPath.getOutput();
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100413 log.debug("Connect point in {}", in);
Andrea Campanella54923d62018-01-23 12:46:04 +0100414 log.debug("Output path {}", cp);
Andrea Campanella08d07e12018-03-07 14:27:54 -0800415 log.debug("{}", outputPath.getFinalPacket());
Andrea Campanella54923d62018-01-23 12:46:04 +0100416
Andrea Campanellae4084402017-12-15 15:27:31 +0100417 //Hosts for the the given output
Andrea Campanella54923d62018-01-23 12:46:04 +0100418 Set<Host> hostsList = hostService.getConnectedHosts(cp);
Andrea Campanellae4084402017-12-15 15:27:31 +0100419 //Hosts queried from the original ip or mac
420 Set<Host> hosts = getHosts(trace);
421
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800422 if (in.equals(cp) && trace.getInitialPacket().getCriterion(Criterion.Type.VLAN_VID) != null &&
423 outputPath.getFinalPacket().getCriterion(Criterion.Type.VLAN_VID) != null
424 && ((VlanIdCriterion) trace.getInitialPacket().getCriterion(Criterion.Type.VLAN_VID)).vlanId()
425 .equals(((VlanIdCriterion) outputPath.getFinalPacket().getCriterion(Criterion.Type.VLAN_VID))
426 .vlanId())) {
Andrea Campanellafe5d8df2018-03-12 11:07:35 -0700427 if (computePath(completePath, trace, outputPath.getOutput())) {
428 trace.addResultMessage("Connect point out " + cp + " is same as initial input " + in);
429 }
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800430 break;
431 }
432
Andrea Campanellae4084402017-12-15 15:27:31 +0100433 //If the two host collections contain the same item it means we reached the proper output
434 if (!Collections.disjoint(hostsList, hosts)) {
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100435 log.debug("Stopping here because host is expected destination {}, reached through", completePath);
Andrea Campanella696ef032018-02-27 18:03:17 +0100436 if (computePath(completePath, trace, outputPath.getOutput())) {
437 trace.addResultMessage("Reached required destination Host " + cp);
Andrea Campanella0cc6acd2018-02-28 16:43:16 +0100438 trace.setSuccess(true);
Andrea Campanella696ef032018-02-27 18:03:17 +0100439 }
Andrea Campanellae4084402017-12-15 15:27:31 +0100440 break;
Andrea Campanella54923d62018-01-23 12:46:04 +0100441 } else if (cp.port().equals(PortNumber.CONTROLLER)) {
Andrea Campanella8292ba62018-01-31 16:43:23 +0100442
Andrea Campanella54923d62018-01-23 12:46:04 +0100443 //Getting the master when the packet gets sent as packet in
444 NodeId master = mastershipService.getMasterFor(cp.deviceId());
Andrea Campanella1445f7a2018-02-07 12:00:12 +0100445 trace.addResultMessage(PACKET_TO_CONTROLLER + " " + master.id());
Andrea Campanella54923d62018-01-23 12:46:04 +0100446 computePath(completePath, trace, outputPath.getOutput());
Andrea Campanellae6798012018-02-06 15:46:52 +0100447 handleVlanToController(outputPath, trace);
Andrea Campanella54923d62018-01-23 12:46:04 +0100448
Andrea Campanella8292ba62018-01-31 16:43:23 +0100449 } else if (linkService.getEgressLinks(cp).size() > 0) {
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100450
451 //TODO this can be optimized if we use a Tree structure for paths.
452 //if we already have outputs let's check if the one we are considering starts from one of the devices
453 // in any of the ones we have.
454 if (trace.getCompletePaths().size() > 0) {
455 ConnectPoint inputForOutput = null;
456 List<ConnectPoint> previousPath = new ArrayList<>();
457 for (List<ConnectPoint> path : trace.getCompletePaths()) {
458 for (ConnectPoint connect : path) {
459 //if the path already contains the input for the output we've found we use it
460 if (connect.equals(in)) {
461 inputForOutput = connect;
462 previousPath = path;
463 break;
464 }
465 }
466 }
Andrea Campanella3ddbadb2018-03-09 14:52:10 -0800467
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100468 //we use the pre-existing path up to the point we fork to a new output
469 if (inputForOutput != null && completePath.contains(inputForOutput)) {
470 List<ConnectPoint> temp = new ArrayList<>(previousPath);
Andrea Campanella3ddbadb2018-03-09 14:52:10 -0800471 temp = temp.subList(0, previousPath.indexOf(inputForOutput) + 1);
472 if (completePath.containsAll(temp)) {
473 completePath = temp;
474 }
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100475 }
476 }
477
Andrea Campanellae4084402017-12-15 15:27:31 +0100478 //let's add the ouput for the input
479 completePath.add(cp);
Andrea Campanellae4084402017-12-15 15:27:31 +0100480 //let's compute the links for the given output
481 Set<Link> links = linkService.getEgressLinks(cp);
482 log.debug("Egress Links {}", links);
Andrea Campanellae4084402017-12-15 15:27:31 +0100483 //For each link we trace the corresponding device
484 for (Link link : links) {
485 ConnectPoint dst = link.dst();
486 //change in-port to the dst link in port
Andrea Campanella8292ba62018-01-31 16:43:23 +0100487 Builder updatedPacket = DefaultTrafficSelector.builder();
Andrea Campanellae4084402017-12-15 15:27:31 +0100488 outputPath.getFinalPacket().criteria().forEach(updatedPacket::add);
489 updatedPacket.add(Criteria.matchInPort(dst.port()));
490 log.debug("DST Connect Point {}", dst);
491 //build the elements for that device
Andrea Campanella696ef032018-02-27 18:03:17 +0100492 traceInDevice(trace, updatedPacket.build(), dst, isDualHomed);
Andrea Campanellae4084402017-12-15 15:27:31 +0100493 //continue the trace along the path
Andrea Campanella696ef032018-02-27 18:03:17 +0100494 getTrace(completePath, dst, trace, isDualHomed);
Andrea Campanellae4084402017-12-15 15:27:31 +0100495 }
Andrea Campanella4c6170a2018-01-17 16:34:51 +0100496 } else if (edgePortService.isEdgePoint(outputPath.getOutput()) &&
497 trace.getInitialPacket().getCriterion(Criterion.Type.ETH_DST) != null &&
498 ((EthCriterion) trace.getInitialPacket().getCriterion(Criterion.Type.ETH_DST))
499 .mac().isMulticast()) {
500 trace.addResultMessage("Packet is multicast and reached output " + outputPath.getOutput() +
501 " which is enabled and is edge port");
Andrea Campanella0cc6acd2018-02-28 16:43:16 +0100502 trace.setSuccess(true);
Andrea Campanella4c6170a2018-01-17 16:34:51 +0100503 computePath(completePath, trace, outputPath.getOutput());
504 completePath.clear();
505 if (!hasOtherOutput(in.deviceId(), trace, outputPath.getOutput())) {
506 return trace;
507 }
Andrea Campanella8292ba62018-01-31 16:43:23 +0100508 } else if (deviceService.getPort(cp).isEnabled()) {
Andrea Campanella1445f7a2018-02-07 12:00:12 +0100509 EthTypeCriterion ethTypeCriterion = (EthTypeCriterion) trace.getInitialPacket()
510 .getCriterion(Criterion.Type.ETH_TYPE);
511 //We treat as correct output only if it's not LLDP or BDDP
512 if (!(ethTypeCriterion.ethType().equals(EtherType.LLDP.ethType())
Andrea Campanellac6d10fc2018-02-27 12:42:28 +0100513 && !ethTypeCriterion.ethType().equals(EtherType.BDDP.ethType()))) {
Andrea Campanella08d07e12018-03-07 14:27:54 -0800514 if (computePath(completePath, trace, outputPath.getOutput())) {
515 if (hostsList.isEmpty()) {
516 trace.addResultMessage("Packet is " + ((EthTypeCriterion) outputPath.getFinalPacket()
517 .getCriterion(Criterion.Type.ETH_TYPE)).ethType() + " and reached " +
518 cp + " with no hosts connected ");
519 } else {
520 IpAddress ipAddress = null;
521 if (trace.getInitialPacket().getCriterion(Criterion.Type.IPV4_DST) != null) {
522 ipAddress = ((IPCriterion) trace.getInitialPacket()
523 .getCriterion(Criterion.Type.IPV4_DST)).ip().address();
524 } else if (trace.getInitialPacket().getCriterion(Criterion.Type.IPV6_DST) != null) {
525 ipAddress = ((IPCriterion) trace.getInitialPacket()
526 .getCriterion(Criterion.Type.IPV6_DST)).ip().address();
527 }
528 if (ipAddress != null) {
529 IpAddress finalIpAddress = ipAddress;
530 if (hostsList.stream().anyMatch(host -> host.ipAddresses().contains(finalIpAddress)) ||
531 hostService.getHostsByIp(finalIpAddress).isEmpty()) {
532 trace.addResultMessage("Packet is " +
533 ((EthTypeCriterion) outputPath.getFinalPacket()
Andrea Campanella7fa8f0a2018-03-09 15:30:22 -0800534 .getCriterion(Criterion.Type.ETH_TYPE)).ethType() +
535 " and reached " + cp + " with hosts " + hostsList);
Andrea Campanella08d07e12018-03-07 14:27:54 -0800536 } else {
537 trace.addResultMessage("Wrong output " + cp + " for required destination ip " +
538 ipAddress);
539 }
540 } else {
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800541 trace.addResultMessage("Packet is " + ((EthTypeCriterion) outputPath.getFinalPacket()
542 .getCriterion(Criterion.Type.ETH_TYPE)).ethType() + " and reached " +
543 cp + " with hosts " + hostsList);
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800544 }
Andrea Campanella2ff88a92018-03-06 15:21:09 -0800545 }
Andrea Campanella08d07e12018-03-07 14:27:54 -0800546 trace.setSuccess(true);
Andrea Campanella1445f7a2018-02-07 12:00:12 +0100547 }
Andrea Campanella8292ba62018-01-31 16:43:23 +0100548 }
Andrea Campanella8292ba62018-01-31 16:43:23 +0100549
550 } else {
551 //No links means that the packet gets dropped.
552 log.warn("No links out of {}", cp);
553 computePath(completePath, trace, cp);
554 trace.addResultMessage("No links depart from " + cp + ". Packet is dropped");
Andrea Campanellae4084402017-12-15 15:27:31 +0100555 }
556 }
557 return trace;
558 }
559
Andrea Campanella4c6170a2018-01-17 16:34:51 +0100560
Andrea Campanellae4084402017-12-15 15:27:31 +0100561 /**
Andrea Campanellae6798012018-02-06 15:46:52 +0100562 * If the initial packet comes tagged with a Vlan we output it with that to ONOS.
563 * If ONOS applied a vlan we remove it.
564 *
565 * @param outputPath the output
566 * @param trace the trace we are building
567 */
Andrea Campanella4c6170a2018-01-17 16:34:51 +0100568
Andrea Campanellae6798012018-02-06 15:46:52 +0100569 private void handleVlanToController(GroupsInDevice outputPath, StaticPacketTrace trace) {
570
571 VlanIdCriterion initialVid = (VlanIdCriterion) trace.getInitialPacket().getCriterion(Criterion.Type.VLAN_VID);
572 VlanIdCriterion finalVid = (VlanIdCriterion) outputPath.getFinalPacket().getCriterion(Criterion.Type.VLAN_VID);
573
574 if (initialVid != null && !initialVid.equals(finalVid) && initialVid.vlanId().equals(VlanId.NONE)) {
575
576 Set<Criterion> finalCriteria = new HashSet<>(outputPath.getFinalPacket().criteria());
577 //removing the final vlanId
578 finalCriteria.remove(finalVid);
579 Builder packetUpdated = DefaultTrafficSelector.builder();
580 finalCriteria.forEach(packetUpdated::add);
581 //Initial was none so we set it to that
582 packetUpdated.add(Criteria.matchVlanId(VlanId.NONE));
583 //Update final packet
584 outputPath.setFinalPacket(packetUpdated.build());
585 }
586 }
587
588 /**
Andrea Campanella4c6170a2018-01-17 16:34:51 +0100589 * Checks if the device has other outputs than the given connect point.
590 *
591 * @param inDeviceId the device
592 * @param trace the trace we are building
593 * @param cp an output connect point
594 * @return true if the device has other outputs.
595 */
596 private boolean hasOtherOutput(DeviceId inDeviceId, StaticPacketTrace trace, ConnectPoint cp) {
597 return trace.getGroupOuputs(inDeviceId).stream().filter(groupsInDevice -> {
598 return !groupsInDevice.getOutput().equals(cp);
599 }).count() > 0;
600 }
601
602 /**
Andrea Campanellae4084402017-12-15 15:27:31 +0100603 * Checks if the path contains the device.
604 *
605 * @param completePath the path
606 * @param deviceId the device to check
607 * @return true if the path contains the device
608 */
609 //TODO might prove costly, improvement: a class with both CPs and DeviceIds point.
610 private boolean pathContainsDevice(List<ConnectPoint> completePath, DeviceId deviceId) {
611 for (ConnectPoint cp : completePath) {
612 if (cp.deviceId().equals(deviceId)) {
613 return true;
614 }
615 }
616 return false;
617 }
618
619 /**
620 * Gets the hosts for the given initial packet.
621 *
622 * @param trace the trace we are building
623 * @return set of the hosts we are trying to reach
624 */
625 private Set<Host> getHosts(StaticPacketTrace trace) {
626 IPCriterion ipv4Criterion = ((IPCriterion) trace.getInitialPacket()
627 .getCriterion(Criterion.Type.IPV4_DST));
628 IPCriterion ipv6Criterion = ((IPCriterion) trace.getInitialPacket()
629 .getCriterion(Criterion.Type.IPV6_DST));
630 Set<Host> hosts = new HashSet<>();
631 if (ipv4Criterion != null) {
632 hosts.addAll(hostService.getHostsByIp(ipv4Criterion.ip().address()));
633 }
634 if (ipv6Criterion != null) {
635 hosts.addAll(hostService.getHostsByIp(ipv6Criterion.ip().address()));
636 }
637 EthCriterion ethCriterion = ((EthCriterion) trace.getInitialPacket()
638 .getCriterion(Criterion.Type.ETH_DST));
639 if (ethCriterion != null) {
640 hosts.addAll(hostService.getHostsByMac(ethCriterion.mac()));
641 }
642 return hosts;
643 }
644
645 /**
646 * Computes the list of traversed connect points.
647 *
648 * @param completePath the list of devices
649 * @param trace the trace we are building
650 * @param output the final output connect point
651 */
Andrea Campanella696ef032018-02-27 18:03:17 +0100652 private boolean computePath(List<ConnectPoint> completePath, StaticPacketTrace trace, ConnectPoint output) {
Andrea Campanellae4084402017-12-15 15:27:31 +0100653 List<ConnectPoint> traverseList = new ArrayList<>();
654 if (!completePath.contains(trace.getInitialConnectPoint())) {
655 traverseList.add(trace.getInitialConnectPoint());
656 }
657 traverseList.addAll(completePath);
658 if (output != null && !completePath.contains(output)) {
659 traverseList.add(output);
660 }
Andrea Campanella696ef032018-02-27 18:03:17 +0100661 if (!trace.getCompletePaths().contains(traverseList)) {
Andrea Campanella3ddbadb2018-03-09 14:52:10 -0800662 trace.addCompletePath(ImmutableList.copyOf(traverseList));
Andrea Campanella696ef032018-02-27 18:03:17 +0100663 return true;
664 }
665 return false;
Andrea Campanellae4084402017-12-15 15:27:31 +0100666 }
667
668 /**
669 * Traces the packet inside a device starting from an input connect point.
670 *
Andrea Campanella696ef032018-02-27 18:03:17 +0100671 * @param trace the trace we are building
672 * @param packet the packet we are tracing
673 * @param in the input connect point.
674 * @param isDualHomed true if the trace we are doing starts or ends in a dual homed host
Andrea Campanellae4084402017-12-15 15:27:31 +0100675 * @return updated trace
676 */
Andrea Campanella696ef032018-02-27 18:03:17 +0100677 private StaticPacketTrace traceInDevice(StaticPacketTrace trace, TrafficSelector packet, ConnectPoint in,
678 boolean isDualHomed) {
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100679
Andrea Campanella08d07e12018-03-07 14:27:54 -0800680 boolean multipleRoutes = false;
681 if (trace.getGroupOuputs(in.deviceId()) != null) {
682 multipleRoutes = multipleRoutes(trace);
683 }
684 if (trace.getGroupOuputs(in.deviceId()) != null && !isDualHomed && !multipleRoutes) {
Andrea Campanellab022b5e2018-01-31 14:59:03 +0100685 log.debug("Trace already contains device and given outputs");
686 return trace;
687 }
Andrea Campanella08d07e12018-03-07 14:27:54 -0800688
Andrea Campanellae4084402017-12-15 15:27:31 +0100689 log.debug("Packet {} coming in from {}", packet, in);
Andrea Campanella17d45192018-01-18 17:11:42 +0100690
691 //if device is not available exit here.
692 if (!deviceService.isAvailable(in.deviceId())) {
693 trace.addResultMessage("Device is offline " + in.deviceId());
694 return trace;
695 }
696
Andrea Campanella1445f7a2018-02-07 12:00:12 +0100697 //handle when the input is the controller
698 //NOTE, we are using the input port as a convenience to carry the CONTROLLER port number even if
699 // a packet in from the controller will not actually traverse the pipeline and have no such notion
700 // as the input port.
701 if (in.port().equals(PortNumber.CONTROLLER)) {
702 StaticPacketTrace outputTrace = inputFromController(trace, in);
703 if (outputTrace != null) {
704 return trace;
705 }
706 }
707
Andrea Campanellae4084402017-12-15 15:27:31 +0100708 List<FlowEntry> flows = new ArrayList<>();
709 List<FlowEntry> outputFlows = new ArrayList<>();
Andrea Campanella8292ba62018-01-31 16:43:23 +0100710 List<Instruction> deferredInstructions = new ArrayList<>();
711
Andrea Campanellae4084402017-12-15 15:27:31 +0100712 FlowEntry nextTableIdEntry = findNextTableIdEntry(in.deviceId(), -1);
713 if (nextTableIdEntry == null) {
714 trace.addResultMessage("No flow rules for device " + in.deviceId() + ". Aborting");
715 return trace;
716 }
717 TableId tableId = nextTableIdEntry.table();
718 FlowEntry flowEntry;
719 boolean output = false;
720 while (!output) {
721 log.debug("Searching a Flow Entry on table {} for packet {}", tableId, packet);
722 //get the rule that matches the incoming packet
723 flowEntry = matchHighestPriority(packet, in, tableId);
724 log.debug("Found Flow Entry {}", flowEntry);
725
726 boolean isOfdpaHardware = TroubleshootUtils.hardwareOfdpaMap
727 .getOrDefault(driverService.getDriver(in.deviceId()).name(), false);
728
729 //if the flow entry on a table is null and we are on hardware we treat as table miss, with few exceptions
730 if (flowEntry == null && isOfdpaHardware) {
731 log.debug("Ofdpa Hw setup, no flow rule means table miss");
732
Andrea Campanellae4084402017-12-15 15:27:31 +0100733 if (((IndexTableId) tableId).id() == 27) {
734 //Apparently a miss but Table 27 on OFDPA is a fixed table
735 packet = handleOfdpa27FixedTable(trace, packet);
736 }
737
738 //Finding next table to go In case of miss
739 nextTableIdEntry = findNextTableIdEntry(in.deviceId(), ((IndexTableId) tableId).id());
740 log.debug("Next table id entry {}", nextTableIdEntry);
741
742 //FIXME find better solution that enable granularity greater than 0 or all rules
743 //(another possibility is max tableId)
744 if (nextTableIdEntry == null && flows.size() == 0) {
Andrea Campanella09eec852018-02-05 19:39:25 +0100745 trace.addResultMessage("No matching flow rules for device " + in.deviceId() + ". Aborting");
Andrea Campanellae4084402017-12-15 15:27:31 +0100746 return trace;
747
748 } else if (nextTableIdEntry == null) {
749 //Means that no more flow rules are present
750 output = true;
751
752 } else if (((IndexTableId) tableId).id() == 20) {
753 //if the table is 20 OFDPA skips to table 50
754 log.debug("A miss on Table 20 on OFDPA means that we skip directly to table 50");
755 tableId = IndexTableId.of(50);
756
757 } else {
758 tableId = nextTableIdEntry.table();
759 }
760
Andrea Campanellae4084402017-12-15 15:27:31 +0100761 } else if (flowEntry == null) {
762 trace.addResultMessage("Packet has no match on table " + tableId + " in device " +
763 in.deviceId() + ". Dropping");
764 return trace;
765 } else {
Andrea Campanella94c594a2018-02-06 18:58:40 +0100766
Andrea Campanellae4084402017-12-15 15:27:31 +0100767 //IF the table has a transition
768 if (flowEntry.treatment().tableTransition() != null) {
769 //update the next table we transitions to
770 tableId = IndexTableId.of(flowEntry.treatment().tableTransition().tableId());
771 log.debug("Flow Entry has transition to table Id {}", tableId);
772 flows.add(flowEntry);
773 } else {
774 //table has no transition so it means that it's an output rule if on the last table
775 log.debug("Flow Entry has no transition to table, treating as last rule {}", flowEntry);
776 flows.add(flowEntry);
777 outputFlows.add(flowEntry);
778 output = true;
779 }
Andrea Campanella8292ba62018-01-31 16:43:23 +0100780 //update the packet according to the immediate actions of this flow rule.
781 packet = updatePacket(packet, flowEntry.treatment().immediate()).build();
782
783 //save the deferred rules for later
784 deferredInstructions.addAll(flowEntry.treatment().deferred());
785
786 //If the flow requires to clear deferred actions we do so for all the ones we encountered.
787 if (flowEntry.treatment().clearedDeferred()) {
788 deferredInstructions.clear();
789 }
790
Andrea Campanella94c594a2018-02-06 18:58:40 +0100791 //On table 10 OFDPA needs two rules to apply the vlan if none and then to transition to the next table.
792 if (needsSecondTable10Flow(flowEntry, isOfdpaHardware)) {
793
794 //Let's get the packet vlanId instruction
795 VlanIdCriterion packetVlanIdCriterion =
796 (VlanIdCriterion) packet.getCriterion(Criterion.Type.VLAN_VID);
797
798 //Let's get the flow entry vlan mod instructions
799 ModVlanIdInstruction entryModVlanIdInstruction = (ModVlanIdInstruction) flowEntry.treatment()
800 .immediate().stream()
801 .filter(instruction -> instruction instanceof ModVlanIdInstruction)
802 .findFirst().orElse(null);
803
804 //If the entry modVlan is not null we need to make sure that the packet has been updated and there
805 // is a flow rule that matches on same criteria and with updated vlanId
806 if (entryModVlanIdInstruction != null) {
807
808 FlowEntry secondVlanFlow = getSecondFlowEntryOnTable10(packet, in,
809 packetVlanIdCriterion, entryModVlanIdInstruction);
810
811 //We found the flow that we expected
812 if (secondVlanFlow != null) {
813 flows.add(secondVlanFlow);
814 } else {
815 trace.addResultMessage("Missing forwarding rule for tagged packet on " + in);
816 return trace;
817 }
818 }
819
820 }
821
Andrea Campanellae4084402017-12-15 15:27:31 +0100822 }
823 }
824
825 //Creating a modifiable builder for the output packet
Andrea Campanella8292ba62018-01-31 16:43:23 +0100826 Builder builder = DefaultTrafficSelector.builder();
Andrea Campanellae4084402017-12-15 15:27:31 +0100827 packet.criteria().forEach(builder::add);
Andrea Campanella8292ba62018-01-31 16:43:23 +0100828
Andrea Campanellae4084402017-12-15 15:27:31 +0100829 //Adding all the flows to the trace
Andrea Campanella54923d62018-01-23 12:46:04 +0100830 trace.addFlowsForDevice(in.deviceId(), ImmutableList.copyOf(flows));
Andrea Campanellae4084402017-12-15 15:27:31 +0100831
Andrea Campanellae4084402017-12-15 15:27:31 +0100832 List<PortNumber> outputPorts = new ArrayList<>();
Andrea Campanella08d07e12018-03-07 14:27:54 -0800833 List<FlowEntry> outputFlowEntries = handleFlows(trace, packet, in, outputFlows, builder, outputPorts);
Andrea Campanellae4084402017-12-15 15:27:31 +0100834
Andrea Campanella08d07e12018-03-07 14:27:54 -0800835
836 log.debug("Handling Groups");
837 //Analyze Groups
838 List<Group> groups = new ArrayList<>();
839
840 Collection<FlowEntry> nonOutputFlows = flows;
841 nonOutputFlows.removeAll(outputFlowEntries);
842
843 //Handling groups pointed at by immediate instructions
844 for (FlowEntry entry : flows) {
845 getGroupsFromInstructions(trace, groups, entry.treatment().immediate(),
846 entry.deviceId(), builder, outputPorts, in);
847 }
848
849 //If we have deferred instructions at this point we handle them.
850 if (deferredInstructions.size() > 0) {
851 builder = handleDeferredActions(trace, packet, in, deferredInstructions, outputPorts, groups);
852
853 }
854 packet = builder.build();
855
856 log.debug("Output Packet {}", packet);
857 return trace;
858 }
859
860 private List<FlowEntry> handleFlows(StaticPacketTrace trace, TrafficSelector packet, ConnectPoint in,
861 List<FlowEntry> outputFlows, Builder builder, List<PortNumber> outputPorts) {
Andrea Campanella54923d62018-01-23 12:46:04 +0100862 //TODO optimization
Andrea Campanella54923d62018-01-23 12:46:04 +0100863 //outputFlows contains also last rule of device, so we need filtering for OUTPUT instructions.
864 List<FlowEntry> outputFlowEntries = outputFlows.stream().filter(flow -> flow.treatment()
865 .allInstructions().stream().filter(instruction -> instruction.type()
866 .equals(Instruction.Type.OUTPUT)).count() > 0).collect(Collectors.toList());
Andrea Campanellae4084402017-12-15 15:27:31 +0100867
Andrea Campanella54923d62018-01-23 12:46:04 +0100868 if (outputFlowEntries.size() > 1) {
869 trace.addResultMessage("More than one flow rule with OUTPUT instruction");
870 log.warn("There cannot be more than one flow entry with OUTPUT instruction for {}", packet);
Andrea Campanellae4084402017-12-15 15:27:31 +0100871 }
Andrea Campanella54923d62018-01-23 12:46:04 +0100872
873 if (outputFlowEntries.size() == 1) {
874
875 OutputInstruction outputInstruction = (OutputInstruction) outputFlowEntries.get(0).treatment()
876 .allInstructions().stream()
877 .filter(instruction -> {
878 return instruction.type().equals(Instruction.Type.OUTPUT);
879 }).findFirst().get();
880
881 //FIXME using GroupsInDevice for output even if flows.
882 buildOutputFromDevice(trace, in, builder, outputPorts, outputInstruction, ImmutableList.of());
883
884 }
Andrea Campanella08d07e12018-03-07 14:27:54 -0800885 return outputFlowEntries;
886 }
Andrea Campanella54923d62018-01-23 12:46:04 +0100887
Andrea Campanella08d07e12018-03-07 14:27:54 -0800888 private boolean multipleRoutes(StaticPacketTrace trace) {
889 boolean multipleRoutes = false;
890 IPCriterion ipCriterion = ((IPCriterion) trace.getInitialPacket().getCriterion(Criterion.Type.IPV4_DST));
891 IpAddress ip = null;
892 if (ipCriterion != null) {
893 ip = ipCriterion.ip().address();
894 } else if (trace.getInitialPacket().getCriterion(Criterion.Type.IPV6_DST) != null) {
895 ip = ((IPCriterion) trace.getInitialPacket().getCriterion(Criterion.Type.IPV6_DST)).ip().address();
Andrea Campanella54923d62018-01-23 12:46:04 +0100896 }
Andrea Campanella8292ba62018-01-31 16:43:23 +0100897
Andrea Campanella08d07e12018-03-07 14:27:54 -0800898 Optional<ResolvedRoute> optionalRoute = routeService.longestPrefixLookup(ip);
899 if (ip != null && optionalRoute.isPresent()) {
900 ResolvedRoute route = optionalRoute.get();
901 route.prefix();
902 multipleRoutes = routeService.getAllResolvedRoutes(route.prefix()).size() > 1;
Andrea Campanella8292ba62018-01-31 16:43:23 +0100903 }
Andrea Campanella08d07e12018-03-07 14:27:54 -0800904 return multipleRoutes;
Andrea Campanellae4084402017-12-15 15:27:31 +0100905 }
906
Andrea Campanella1445f7a2018-02-07 12:00:12 +0100907 /**
908 * Handles the specific case where the Input is the controller.
909 * Note that the in port is used as a convenience to store the port of the controller even if the packet in
910 * from a controller should not have a physical input port. The in port from the Controller is used to make sure
911 * the flood to all active physical ports of the device.
912 *
913 * @param trace the trace
914 * @param in the controller port
915 * @return the augmented trace.
916 */
917 private StaticPacketTrace inputFromController(StaticPacketTrace trace, ConnectPoint in) {
918 EthTypeCriterion ethTypeCriterion = (EthTypeCriterion) trace.getInitialPacket()
919 .getCriterion(Criterion.Type.ETH_TYPE);
920 //If the packet is LLDP or BDDP we flood it on all active ports of the switch.
921 if (ethTypeCriterion != null && (ethTypeCriterion.ethType().equals(EtherType.LLDP.ethType())
922 || ethTypeCriterion.ethType().equals(EtherType.BDDP.ethType()))) {
923 //get the active ports
924 List<Port> enabledPorts = deviceService.getPorts(in.deviceId()).stream()
925 .filter(Port::isEnabled)
926 .collect(Collectors.toList());
927 //build an output from each one
928 enabledPorts.forEach(port -> {
929 GroupsInDevice output = new GroupsInDevice(new ConnectPoint(port.element().id(), port.number()),
930 ImmutableList.of(), trace.getInitialPacket());
931 trace.addGroupOutputPath(in.deviceId(), output);
932 });
933 return trace;
934 }
935 return null;
936 }
937
Andrea Campanella94c594a2018-02-06 18:58:40 +0100938 private boolean needsSecondTable10Flow(FlowEntry flowEntry, boolean isOfdpaHardware) {
939 return isOfdpaHardware && flowEntry.table().equals(IndexTableId.of(10))
940 && flowEntry.selector().getCriterion(Criterion.Type.VLAN_VID) != null
941 && ((VlanIdCriterion) flowEntry.selector().getCriterion(Criterion.Type.VLAN_VID))
942 .vlanId().equals(VlanId.NONE);
943 }
944
945 /**
946 * Method that finds a flow rule on table 10 that matches the packet and the VLAN of the already
947 * found rule on table 10. This is because OFDPA needs two rules on table 10, first to apply the rule,
948 * second to transition to following table
949 *
950 * @param packet the incoming packet
951 * @param in the input connect point
952 * @param packetVlanIdCriterion the vlan criterion from the packet
953 * @param entryModVlanIdInstruction the entry vlan instruction
954 * @return the second flow entry that matched
955 */
956 private FlowEntry getSecondFlowEntryOnTable10(TrafficSelector packet, ConnectPoint in,
957 VlanIdCriterion packetVlanIdCriterion,
958 ModVlanIdInstruction entryModVlanIdInstruction) {
959 FlowEntry secondVlanFlow = null;
960 //Check the packet has been update from the first rule.
961 if (packetVlanIdCriterion.vlanId().equals(entryModVlanIdInstruction.vlanId())) {
962 //find a rule on the same table that matches the vlan and
963 // also all the other elements of the flow such as input port
964 secondVlanFlow = Lists.newArrayList(flowRuleService.getFlowEntries(in.deviceId()).iterator())
965 .stream()
966 .filter(entry -> {
967 return entry.table().equals(IndexTableId.of(10));
968 })
969 .filter(entry -> {
970 VlanIdCriterion criterion = (VlanIdCriterion) entry.selector()
971 .getCriterion(Criterion.Type.VLAN_VID);
972 return criterion != null && match(packet, entry)
973 && criterion.vlanId().equals(entryModVlanIdInstruction.vlanId());
974 }).findFirst().orElse(null);
975
976 }
977 return secondVlanFlow;
978 }
979
Andrea Campanella8292ba62018-01-31 16:43:23 +0100980
Andrea Campanellae4084402017-12-15 15:27:31 +0100981 /**
Andrea Campanellae4084402017-12-15 15:27:31 +0100982 * Handles table 27 in Ofpda which is a fixed table not visible to any controller that handles Mpls Labels.
983 *
984 * @param packet the incoming packet
985 * @return the updated packet
986 */
987 private TrafficSelector handleOfdpa27FixedTable(StaticPacketTrace trace, TrafficSelector packet) {
988 log.debug("Handling table 27 on OFDPA, removing mpls ETH Type and change mpls label");
989 Criterion mplsCriterion = packet.getCriterion(Criterion.Type.ETH_TYPE);
990 ImmutableList.Builder<Instruction> builder = ImmutableList.builder();
991
992 //If the pakcet comes in with the expected elements we update it as per OFDPA spec.
993 if (mplsCriterion != null && ((EthTypeCriterion) mplsCriterion).ethType()
994 .equals(EtherType.MPLS_UNICAST.ethType())) {
Andrea Campanella3970e472018-01-25 16:44:04 +0100995 //TODO update with parsing with eth MPLS pop Instruction for treating label an bos
Andrea Campanellae4084402017-12-15 15:27:31 +0100996 Instruction ethInstruction = Instructions.popMpls(((EthTypeCriterion) trace.getInitialPacket()
997 .getCriterion(Criterion.Type.ETH_TYPE)).ethType());
998 //FIXME what do we use as L3_Unicast mpls Label ?
Andrea Campanella3970e472018-01-25 16:44:04 +0100999 //translateInstruction(builder, ethInstruction);
Andrea Campanellae4084402017-12-15 15:27:31 +01001000 builder.add(ethInstruction);
1001 }
1002 packet = updatePacket(packet, builder.build()).build();
1003 return packet;
1004 }
1005
1006 /**
1007 * Finds the flow entry with the minimun next table Id.
1008 *
1009 * @param deviceId the device to search
1010 * @param currentId the current id. the search will use this as minimum
1011 * @return the flow entry with the minimum table Id after the given one.
1012 */
1013 private FlowEntry findNextTableIdEntry(DeviceId deviceId, int currentId) {
1014
1015 final Comparator<FlowEntry> comparator = Comparator.comparing((FlowEntry f) -> ((IndexTableId) f.table()).id());
1016
1017 return Lists.newArrayList(flowRuleService.getFlowEntries(deviceId).iterator())
1018 .stream().filter(f -> ((IndexTableId) f.table()).id() > currentId).min(comparator).orElse(null);
1019 }
1020
Andrea Campanella8292ba62018-01-31 16:43:23 +01001021 private Builder handleDeferredActions(StaticPacketTrace trace, TrafficSelector packet,
1022 ConnectPoint in, List<Instruction> deferredInstructions,
1023 List<PortNumber> outputPorts, List<Group> groups) {
1024
1025 //Update the packet with the deferred instructions
1026 Builder builder = updatePacket(packet, deferredInstructions);
1027
1028 //Gather any output instructions from the deferred instruction
1029 List<Instruction> outputFlowInstruction = deferredInstructions.stream().filter(instruction -> {
1030 return instruction.type().equals(Instruction.Type.OUTPUT);
1031 }).collect(Collectors.toList());
1032
1033 //We are considering deferred instructions from flows, there can only be one output.
1034 if (outputFlowInstruction.size() > 1) {
1035 trace.addResultMessage("More than one flow rule with OUTPUT instruction");
1036 log.warn("There cannot be more than one flow entry with OUTPUT instruction for {}", packet);
1037 }
1038 //If there is one output let's go through that
1039 if (outputFlowInstruction.size() == 1) {
1040 buildOutputFromDevice(trace, in, builder, outputPorts, (OutputInstruction) outputFlowInstruction.get(0),
1041 ImmutableList.of());
1042 }
1043 //If there is no output let's see if there any deferred instruction point to groups.
1044 if (outputFlowInstruction.size() == 0) {
1045 getGroupsFromInstructions(trace, groups, deferredInstructions,
1046 in.deviceId(), builder, outputPorts, in);
1047 }
1048 return builder;
1049 }
1050
Andrea Campanellae4084402017-12-15 15:27:31 +01001051 /**
1052 * Gets group information from instructions.
1053 *
1054 * @param trace the trace we are building
1055 * @param groupsForDevice the set of groups for this device
1056 * @param instructions the set of instructions we are searching for groups.
1057 * @param deviceId the device we are considering
1058 * @param builder the builder of the input packet
1059 * @param outputPorts the output ports for that packet
1060 */
1061 private void getGroupsFromInstructions(StaticPacketTrace trace, List<Group> groupsForDevice,
1062 List<Instruction> instructions, DeviceId deviceId,
Andrea Campanella8292ba62018-01-31 16:43:23 +01001063 Builder builder, List<PortNumber> outputPorts,
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001064 ConnectPoint in) {
Andrea Campanellae4084402017-12-15 15:27:31 +01001065 List<Instruction> groupInstructionlist = new ArrayList<>();
1066 for (Instruction instruction : instructions) {
1067 log.debug("Considering Instruction {}", instruction);
1068 //if the instruction is not group we need to update the packet or add the output
1069 //to the possible outputs for this packet
1070 if (!instruction.type().equals(Instruction.Type.GROUP)) {
1071 //if the instruction is not group we need to update the packet or add the output
1072 //to the possible outputs for this packet
1073 if (instruction.type().equals(Instruction.Type.OUTPUT)) {
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001074 buildOutputFromDevice(trace, in, builder, outputPorts,
Andrea Campanella573d4b92018-02-19 17:03:46 +01001075 (OutputInstruction) instruction, ImmutableList.copyOf(groupsForDevice));
1076 //clearing the groups because we start from the top.
1077 groupsForDevice.clear();
Andrea Campanellae4084402017-12-15 15:27:31 +01001078 } else {
1079 builder = translateInstruction(builder, instruction);
1080 }
1081 } else {
1082 //if the instuction is pointing to a group we need to get the group
1083 groupInstructionlist.add(instruction);
1084 }
1085 }
1086 //handle all the internal instructions pointing to a group.
1087 for (Instruction instr : groupInstructionlist) {
1088 GroupInstruction groupInstruction = (GroupInstruction) instr;
1089 Group group = Lists.newArrayList(groupService.getGroups(deviceId)).stream().filter(groupInternal -> {
1090 return groupInternal.id().equals(groupInstruction.groupId());
1091 }).findAny().orElse(null);
1092 if (group == null) {
1093 trace.addResultMessage("Null group for Instruction " + instr);
1094 break;
1095 }
Andrea Campanella94dfb9e2018-02-27 12:36:00 +01001096 if (group.buckets().buckets().size() == 0) {
1097 trace.addResultMessage("Group " + group.id() + "has no buckets");
1098 break;
1099 }
Andrea Campanella573d4b92018-02-19 17:03:46 +01001100
Andrea Campanellae4084402017-12-15 15:27:31 +01001101 //Cycle in each of the group's buckets and add them to the groups for this Device.
1102 for (GroupBucket bucket : group.buckets().buckets()) {
Andrea Campanella573d4b92018-02-19 17:03:46 +01001103
1104 //add the group to the traversed groups
1105 if (!groupsForDevice.contains(group)) {
1106 groupsForDevice.add(group);
1107 }
1108
Andrea Campanellae4084402017-12-15 15:27:31 +01001109 getGroupsFromInstructions(trace, groupsForDevice, bucket.treatment().allInstructions(),
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001110 deviceId, builder, outputPorts, in);
Andrea Campanellae4084402017-12-15 15:27:31 +01001111 }
1112 }
1113 }
1114
1115 /**
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001116 * Check if the output is the input port, if so adds a dop result message, otherwise builds
1117 * a possible output from this device.
1118 *
1119 * @param trace the trace
1120 * @param in the input connect point
1121 * @param builder the packet builder
1122 * @param outputPorts the list of output ports for this device
1123 * @param outputInstruction the output instruction
Andrea Campanella8292ba62018-01-31 16:43:23 +01001124 * @param groupsForDevice the groups we output from
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001125 */
Andrea Campanella8292ba62018-01-31 16:43:23 +01001126 private void buildOutputFromDevice(StaticPacketTrace trace, ConnectPoint in, Builder builder,
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001127 List<PortNumber> outputPorts, OutputInstruction outputInstruction,
1128 List<Group> groupsForDevice) {
Andrea Campanella54923d62018-01-23 12:46:04 +01001129 ConnectPoint output = new ConnectPoint(in.deviceId(), outputInstruction.port());
Andrea Campanella1445f7a2018-02-07 12:00:12 +01001130
Andrea Campanella2ff88a92018-03-06 15:21:09 -08001131 outputPorts.add(outputInstruction.port());
1132
1133 GroupsInDevice device = new GroupsInDevice(output, groupsForDevice, builder.build());
1134 if (trace.getGroupOuputs(output.deviceId()) != null
1135 && trace.getGroupOuputs(output.deviceId()).contains(device)) {
1136 return;
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001137 }
Andrea Campanella2ff88a92018-03-06 15:21:09 -08001138 trace.addGroupOutputPath(in.deviceId(),
1139 new GroupsInDevice(output, groupsForDevice, builder.build()));
Andrea Campanella7d3cf652018-01-22 15:10:30 +01001140 }
1141
1142 /**
Andrea Campanellae4084402017-12-15 15:27:31 +01001143 * Applies all give instructions to the input packet.
1144 *
1145 * @param packet the input packet
1146 * @param instructions the set of instructions
1147 * @return the packet with the applied instructions
1148 */
Andrea Campanella8292ba62018-01-31 16:43:23 +01001149 private Builder updatePacket(TrafficSelector packet, List<Instruction> instructions) {
1150 Builder newSelector = DefaultTrafficSelector.builder();
Andrea Campanellae4084402017-12-15 15:27:31 +01001151 packet.criteria().forEach(newSelector::add);
Andrea Campanella3970e472018-01-25 16:44:04 +01001152 //FIXME optimize
1153 for (Instruction instruction : instructions) {
1154 newSelector = translateInstruction(newSelector, instruction);
1155 }
Andrea Campanellae4084402017-12-15 15:27:31 +01001156 return newSelector;
1157 }
1158
1159 /**
1160 * Applies an instruction to the packet in the form of a selector.
1161 *
1162 * @param newSelector the packet selector
1163 * @param instruction the instruction to be translated
1164 * @return the new selector with the applied instruction
1165 */
Andrea Campanella8292ba62018-01-31 16:43:23 +01001166 private Builder translateInstruction(Builder newSelector, Instruction instruction) {
Andrea Campanellae4084402017-12-15 15:27:31 +01001167 log.debug("Translating instruction {}", instruction);
Andrea Campanella3970e472018-01-25 16:44:04 +01001168 log.debug("New Selector {}", newSelector.build());
Andrea Campanellae4084402017-12-15 15:27:31 +01001169 //TODO add as required
1170 Criterion criterion = null;
1171 switch (instruction.type()) {
1172 case L2MODIFICATION:
1173 L2ModificationInstruction l2Instruction = (L2ModificationInstruction) instruction;
1174 switch (l2Instruction.subtype()) {
1175 case VLAN_ID:
Andrea Campanella94c594a2018-02-06 18:58:40 +01001176 ModVlanIdInstruction vlanIdInstruction =
1177 (ModVlanIdInstruction) instruction;
Andrea Campanellae4084402017-12-15 15:27:31 +01001178 VlanId id = vlanIdInstruction.vlanId();
1179 criterion = Criteria.matchVlanId(id);
1180 break;
1181 case VLAN_POP:
1182 criterion = Criteria.matchVlanId(VlanId.NONE);
1183 break;
1184 case MPLS_PUSH:
Andrea Campanella94c594a2018-02-06 18:58:40 +01001185 ModMplsHeaderInstruction mplsEthInstruction =
1186 (ModMplsHeaderInstruction) instruction;
Andrea Campanellae4084402017-12-15 15:27:31 +01001187 criterion = Criteria.matchEthType(mplsEthInstruction.ethernetType().toShort());
1188 break;
1189 case MPLS_POP:
Andrea Campanella94c594a2018-02-06 18:58:40 +01001190 ModMplsHeaderInstruction mplsPopInstruction =
1191 (ModMplsHeaderInstruction) instruction;
Andrea Campanellae4084402017-12-15 15:27:31 +01001192 criterion = Criteria.matchEthType(mplsPopInstruction.ethernetType().toShort());
Andrea Campanella3970e472018-01-25 16:44:04 +01001193
1194 //When popping MPLS we remove label and BOS
1195 TrafficSelector temporaryPacket = newSelector.build();
1196 if (temporaryPacket.getCriterion(Criterion.Type.MPLS_LABEL) != null) {
Andrea Campanella8292ba62018-01-31 16:43:23 +01001197 Builder noMplsSelector = DefaultTrafficSelector.builder();
Andrea Campanella3970e472018-01-25 16:44:04 +01001198 temporaryPacket.criteria().stream().filter(c -> {
1199 return !c.type().equals(Criterion.Type.MPLS_LABEL) &&
1200 !c.type().equals(Criterion.Type.MPLS_BOS);
1201 }).forEach(noMplsSelector::add);
1202 newSelector = noMplsSelector;
1203 }
1204
Andrea Campanellae4084402017-12-15 15:27:31 +01001205 break;
1206 case MPLS_LABEL:
Andrea Campanella94c594a2018-02-06 18:58:40 +01001207 ModMplsLabelInstruction mplsLabelInstruction =
1208 (ModMplsLabelInstruction) instruction;
Andrea Campanellae4084402017-12-15 15:27:31 +01001209 criterion = Criteria.matchMplsLabel(mplsLabelInstruction.label());
Andrea Campanella3970e472018-01-25 16:44:04 +01001210 newSelector.matchMplsBos(true);
Andrea Campanellae4084402017-12-15 15:27:31 +01001211 break;
1212 case ETH_DST:
Andrea Campanella94c594a2018-02-06 18:58:40 +01001213 ModEtherInstruction modEtherDstInstruction =
1214 (ModEtherInstruction) instruction;
Andrea Campanellae4084402017-12-15 15:27:31 +01001215 criterion = Criteria.matchEthDst(modEtherDstInstruction.mac());
1216 break;
1217 case ETH_SRC:
Andrea Campanella94c594a2018-02-06 18:58:40 +01001218 ModEtherInstruction modEtherSrcInstruction =
1219 (ModEtherInstruction) instruction;
Andrea Campanellae4084402017-12-15 15:27:31 +01001220 criterion = Criteria.matchEthSrc(modEtherSrcInstruction.mac());
1221 break;
1222 default:
1223 log.debug("Unsupported L2 Instruction");
1224 break;
1225 }
1226 break;
1227 default:
1228 log.debug("Unsupported Instruction");
1229 break;
1230 }
1231 if (criterion != null) {
1232 log.debug("Adding criterion {}", criterion);
1233 newSelector.add(criterion);
1234 }
1235 return newSelector;
1236 }
1237
1238 /**
1239 * Finds the rule in the device that mathces the input packet and has the highest priority.
1240 *
1241 * @param packet the input packet
1242 * @param in the connect point the packet comes in from
1243 * @param tableId the table to search
1244 * @return the flow entry
1245 */
1246 private FlowEntry matchHighestPriority(TrafficSelector packet, ConnectPoint in, TableId tableId) {
1247 //Computing the possible match rules.
1248 final Comparator<FlowEntry> comparator = Comparator.comparing(FlowRule::priority);
1249 return Lists.newArrayList(flowRuleService.getFlowEntries(in.deviceId()).iterator())
1250 .stream()
1251 .filter(flowEntry -> {
1252 return flowEntry.table().equals(tableId);
1253 })
1254 .filter(flowEntry -> {
1255 return match(packet, flowEntry);
1256 }).max(comparator).orElse(null);
1257 }
1258
1259 /**
1260 * Matches the packet with the given flow entry.
1261 *
1262 * @param packet the packet to match
1263 * @param flowEntry the flow entry to match the packet against
1264 * @return true if the packet matches the flow.
1265 */
1266 private boolean match(TrafficSelector packet, FlowEntry flowEntry) {
Andrea Campanellae4084402017-12-15 15:27:31 +01001267 return flowEntry.selector().criteria().stream().allMatch(criterion -> {
1268 Criterion.Type type = criterion.type();
Andrea Campanella128d9c62018-01-31 12:20:48 +01001269 //If the criterion has IP we need to do LPM to establish matching.
Andrea Campanellae4084402017-12-15 15:27:31 +01001270 if (type.equals(Criterion.Type.IPV4_SRC) || type.equals(Criterion.Type.IPV4_DST) ||
1271 type.equals(Criterion.Type.IPV6_SRC) || type.equals(Criterion.Type.IPV6_DST)) {
Andrea Campanella4c6170a2018-01-17 16:34:51 +01001272 return matchIp(packet, (IPCriterion) criterion);
Andrea Campanellae4084402017-12-15 15:27:31 +01001273 //we check that the packet contains the criterion provided by the flow rule.
Andrea Campanella4c6170a2018-01-17 16:34:51 +01001274 } else if (type.equals(Criterion.Type.ETH_SRC_MASKED)) {
1275 return matchMac(packet, (EthCriterion) criterion, false);
1276 } else if (type.equals(Criterion.Type.ETH_DST_MASKED)) {
1277 return matchMac(packet, (EthCriterion) criterion, true);
Andrea Campanellae4084402017-12-15 15:27:31 +01001278 } else {
1279 return packet.criteria().contains(criterion);
1280 }
1281 });
Simon Hunt026a2872017-11-13 17:09:43 -08001282 }
Andrea Campanella4c6170a2018-01-17 16:34:51 +01001283
1284 /**
1285 * Checks if the packet has an dst or src IP and if that IP matches the subnet of the ip criterion.
1286 *
1287 * @param packet the incoming packet
1288 * @param criterion the criterion to match
1289 * @return true if match
1290 */
1291 private boolean matchIp(TrafficSelector packet, IPCriterion criterion) {
1292 IPCriterion matchCriterion = (IPCriterion) packet.getCriterion(criterion.type());
1293 //if the packet does not have an IPv4 or IPv6 criterion we return true
1294 if (matchCriterion == null) {
1295 return false;
1296 }
1297 try {
1298 log.debug("Checking if {} is under {}", matchCriterion.ip(), criterion.ip());
1299 Subnet subnet = Subnet.createInstance(criterion.ip().toString());
1300 return subnet.isInSubnet(matchCriterion.ip().address().toInetAddress());
1301 } catch (UnknownHostException e) {
1302 return false;
1303 }
1304 }
1305
1306 /**
1307 * Checks if the packet has a dst or src MAC and if that Mac matches the mask of the mac criterion.
1308 *
1309 * @param packet the incoming packet
1310 * @param hitCriterion the criterion to match
1311 * @param dst true if we are checking DST MAC
1312 * @return true if match
1313 */
1314 private boolean matchMac(TrafficSelector packet, EthCriterion hitCriterion, boolean dst) {
1315 //Packet can have only one EthCriterion
1316 EthCriterion matchCriterion;
1317 if (dst) {
1318 matchCriterion = (EthCriterion) packet.criteria().stream().filter(criterion1 -> {
1319 return criterion1.type().equals(Criterion.Type.ETH_DST_MASKED) ||
1320 criterion1.type().equals(Criterion.Type.ETH_DST);
1321 }).findFirst().orElse(null);
1322 } else {
1323 matchCriterion = (EthCriterion) packet.criteria().stream().filter(criterion1 -> {
1324 return criterion1.type().equals(Criterion.Type.ETH_SRC_MASKED) ||
1325 criterion1.type().equals(Criterion.Type.ETH_SRC);
1326 }).findFirst().orElse(null);
1327 }
1328 //if the packet does not have an ETH criterion we return true
1329 if (matchCriterion == null) {
1330 return true;
1331 }
1332 log.debug("Checking if {} is under {}/{}", matchCriterion.mac(), hitCriterion.mac(), hitCriterion.mask());
1333 return compareMac(matchCriterion.mac(), hitCriterion.mac(), hitCriterion.mask());
1334 }
Simon Hunt026a2872017-11-13 17:09:43 -08001335}