blob: e933d3e964fd8cd3f0f294865ec8e4e59fd4fa83 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Pier Ventre229fd0b2016-10-31 16:49:19 -070018import com.google.common.collect.Lists;
Charles Chan051490d2018-01-11 11:48:18 -080019import com.google.common.collect.Sets;
Charles Chan61c086d2019-07-26 17:46:15 -070020import org.apache.commons.lang3.tuple.ImmutablePair;
Saurav Das4c35fc42015-11-20 15:27:53 -080021import org.onlab.packet.EthType;
sangho80f11cb2015-04-01 13:05:26 -070022import org.onlab.packet.Ethernet;
Charles Chanef8d12e2017-12-05 21:07:38 -080023import org.onlab.packet.IPv6;
sangho80f11cb2015-04-01 13:05:26 -070024import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080025import org.onlab.packet.Ip6Address;
26import org.onlab.packet.IpAddress;
sangho80f11cb2015-04-01 13:05:26 -070027import org.onlab.packet.IpPrefix;
28import org.onlab.packet.MacAddress;
sangho80f11cb2015-04-01 13:05:26 -070029import org.onlab.packet.MplsLabel;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070030import org.onlab.packet.VlanId;
Charles Chanb7f75ac2016-01-11 18:28:54 -080031import org.onosproject.net.ConnectPoint;
Saurav Das9bf49582018-08-13 15:34:26 -070032import org.onosproject.net.Device;
Charles Chanf17fade2020-03-08 18:07:19 -070033import org.onosproject.net.Host;
Charles Chan1eaf4802016-04-18 13:44:03 -070034import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080035import org.onosproject.net.flowobjective.Objective;
Charles Chan1eaf4802016-04-18 13:44:03 -070036import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080037import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -070038import org.onosproject.net.intf.Interface;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080039import org.onosproject.net.packet.PacketPriority;
Charles Chan319d1a22015-11-03 10:42:14 -080040import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
Saurav Das62ae6792017-05-15 15:34:25 -070041import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070042import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sangho80f11cb2015-04-01 13:05:26 -070043import org.onosproject.net.DeviceId;
Saurav Das7c305372015-10-28 12:39:42 -070044import org.onosproject.net.Port;
sangho80f11cb2015-04-01 13:05:26 -070045import org.onosproject.net.PortNumber;
sangho80f11cb2015-04-01 13:05:26 -070046import org.onosproject.net.flow.DefaultTrafficSelector;
47import org.onosproject.net.flow.DefaultTrafficTreatment;
sangho80f11cb2015-04-01 13:05:26 -070048import org.onosproject.net.flow.TrafficSelector;
49import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070050import org.onosproject.net.flow.criteria.Criteria;
51import org.onosproject.net.flowobjective.DefaultFilteringObjective;
52import org.onosproject.net.flowobjective.DefaultForwardingObjective;
53import org.onosproject.net.flowobjective.FilteringObjective;
54import org.onosproject.net.flowobjective.ForwardingObjective;
55import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
Saurav Das9f1c42e2015-10-23 10:51:11 -070056import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
sangho80f11cb2015-04-01 13:05:26 -070057import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
60import java.util.ArrayList;
Pier Ventre229fd0b2016-10-31 16:49:19 -070061import java.util.Collection;
62import java.util.Collections;
Saurav Das261c3002017-06-13 15:35:54 -070063import java.util.HashMap;
Saurav Dasc28b3432015-10-30 17:45:38 -070064import java.util.HashSet;
sangho80f11cb2015-04-01 13:05:26 -070065import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070066import java.util.Map;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080067import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070068import java.util.Set;
Charles Chan12a8a842020-02-14 13:23:57 -080069import java.util.concurrent.CompletableFuture;
pierventrea3989be2021-01-08 16:43:17 +010070import java.util.concurrent.ExecutionException;
sanghofb7c7292015-04-13 15:15:58 -070071import java.util.concurrent.atomic.AtomicLong;
Charles Chanf17f66b2018-02-26 21:33:25 -080072import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -070073
74import static com.google.common.base.Preconditions.checkNotNull;
Pier Luigib9632ba2017-01-12 18:14:58 -080075import static org.onlab.packet.Ethernet.TYPE_ARP;
76import static org.onlab.packet.Ethernet.TYPE_IPV6;
Charles Chan051490d2018-01-11 11:48:18 -080077import static org.onlab.packet.ICMP6.NEIGHBOR_ADVERTISEMENT;
Pier Luigib9632ba2017-01-12 18:14:58 -080078import static org.onlab.packet.ICMP6.NEIGHBOR_SOLICITATION;
Charles Chan051490d2018-01-11 11:48:18 -080079import static org.onlab.packet.ICMP6.ROUTER_ADVERTISEMENT;
80import static org.onlab.packet.ICMP6.ROUTER_SOLICITATION;
Pier Luigib9632ba2017-01-12 18:14:58 -080081import static org.onlab.packet.IPv6.PROTOCOL_ICMP6;
sangho80f11cb2015-04-01 13:05:26 -070082
Charles Chanb7f75ac2016-01-11 18:28:54 -080083/**
84 * Populator of segment routing flow rules.
85 */
sangho80f11cb2015-04-01 13:05:26 -070086public class RoutingRulePopulator {
Charles Chanef8d12e2017-12-05 21:07:38 -080087 private static final Logger log = LoggerFactory.getLogger(RoutingRulePopulator.class);
88
89 private static final int ARP_NDP_PRIORITY = 30000;
sangho80f11cb2015-04-01 13:05:26 -070090
sanghofb7c7292015-04-13 15:15:58 -070091 private AtomicLong rulePopulationCounter;
sangho9b169e32015-04-14 16:27:13 -070092 private SegmentRoutingManager srManager;
93 private DeviceConfiguration config;
psneha86e60d32019-03-26 06:31:41 -040094 private RouteSimplifierUtils routeSimplifierUtils;
Saurav Das9f1c42e2015-10-23 10:51:11 -070095
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -070096 // used for signalling the driver to remove vlan table and tmac entry also
97 private static final long CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES = 1;
pierventrea3989be2021-01-08 16:43:17 +010098 // used for signalling the driver when not remove tmac entries
99 private static final long INTERFACE_CONFIG_UPDATE = 2;
100 private static final long METADATA_MASK = 0xffffffffffffffffL;
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -0700101
sangho80f11cb2015-04-01 13:05:26 -0700102 /**
103 * Creates a RoutingRulePopulator object.
104 *
Thomas Vachuska8a075092015-04-15 18:20:08 -0700105 * @param srManager segment routing manager reference
sangho80f11cb2015-04-01 13:05:26 -0700106 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700107 RoutingRulePopulator(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700108 this.srManager = srManager;
sangho9b169e32015-04-14 16:27:13 -0700109 this.config = checkNotNull(srManager.deviceConfiguration);
sanghofb7c7292015-04-13 15:15:58 -0700110 this.rulePopulationCounter = new AtomicLong(0);
psneha86e60d32019-03-26 06:31:41 -0400111 this.routeSimplifierUtils = new RouteSimplifierUtils(srManager);
sanghofb7c7292015-04-13 15:15:58 -0700112 }
113
114 /**
115 * Resets the population counter.
116 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700117 void resetCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700118 rulePopulationCounter.set(0);
119 }
120
121 /**
122 * Returns the number of rules populated.
Thomas Vachuska7cfc6202015-04-30 18:13:25 -0700123 *
124 * @return number of rules
sanghofb7c7292015-04-13 15:15:58 -0700125 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700126 long getCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700127 return rulePopulationCounter.get();
sangho80f11cb2015-04-01 13:05:26 -0700128 }
129
130 /**
Charles Chand66d6712018-03-29 16:03:41 -0700131 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
132 * output to given port.
133 *
134 * @param deviceId device ID
135 * @param port port
136 * @param mac mac address
137 * @param vlanId VLAN ID
Charles Chan12a8a842020-02-14 13:23:57 -0800138 * @return future that carries the flow objective if succeeded, null if otherwise
Charles Chand66d6712018-03-29 16:03:41 -0700139 */
Charles Chan12a8a842020-02-14 13:23:57 -0800140 CompletableFuture<Objective> populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
Charles Chand66d6712018-03-29 16:03:41 -0700141 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
142 if (fob == null) {
143 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
Charles Chan12a8a842020-02-14 13:23:57 -0800144 return CompletableFuture.completedFuture(null);
Charles Chand66d6712018-03-29 16:03:41 -0700145 }
146
Charles Chan12a8a842020-02-14 13:23:57 -0800147 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chand66d6712018-03-29 16:03:41 -0700148 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800149 (objective) -> {
150 log.debug("Brigding rule for {}/{} populated", mac, vlanId);
151 future.complete(objective);
152 },
153 (objective, error) -> {
154 log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error);
155 future.complete(null);
156 });
Charles Chand66d6712018-03-29 16:03:41 -0700157 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
Charles Chan12a8a842020-02-14 13:23:57 -0800158 return future;
Charles Chand66d6712018-03-29 16:03:41 -0700159 }
160
161 /**
162 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
163 * output to given port.
164 *
165 * @param deviceId device ID
166 * @param port port
167 * @param mac mac address
168 * @param vlanId VLAN ID
Charles Chan12a8a842020-02-14 13:23:57 -0800169 * @return future that carries the flow objective if succeeded, null if otherwise
Charles Chand66d6712018-03-29 16:03:41 -0700170 */
Charles Chan12a8a842020-02-14 13:23:57 -0800171 CompletableFuture<Objective> revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
Charles Chand66d6712018-03-29 16:03:41 -0700172 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
173 if (fob == null) {
174 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
Charles Chan12a8a842020-02-14 13:23:57 -0800175 return CompletableFuture.completedFuture(null);
Charles Chand66d6712018-03-29 16:03:41 -0700176 }
177
Charles Chan12a8a842020-02-14 13:23:57 -0800178 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chand66d6712018-03-29 16:03:41 -0700179 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800180 (objective) -> {
181 log.debug("Brigding rule for {}/{} revoked", mac, vlanId);
182 future.complete(objective);
183 },
184 (objective, error) -> {
185 log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error);
186 future.complete(null);
187 });
Charles Chand66d6712018-03-29 16:03:41 -0700188 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
Charles Chan12a8a842020-02-14 13:23:57 -0800189 return future;
Charles Chand66d6712018-03-29 16:03:41 -0700190 }
191
192 /**
193 * Generates a forwarding objective builder for bridging rules.
194 * <p>
195 * The forwarding objective bridges packets destined to a given MAC to
196 * given port on given device.
197 *
198 * @param deviceId Device that host attaches to
199 * @param mac MAC address of the host
200 * @param hostVlanId VLAN ID of the host
201 * @param outport Port that host attaches to
202 * @param revoke true if forwarding objective is meant to revoke forwarding rule
203 * @return Forwarding objective builder
204 */
205 private ForwardingObjective.Builder bridgingFwdObjBuilder(
206 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
207 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan098ca202018-05-01 11:50:20 -0700208 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
209 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
210 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chand66d6712018-03-29 16:03:41 -0700211
212 // Create host selector
213 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
214 sbuilder.matchEthDst(mac);
215
216 // Create host treatment
217 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
218 tbuilder.immediate().setOutput(outport);
219
220 // Create host meta
221 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
222
223 // Adjust the selector, treatment and meta according to VLAN configuration
224 if (taggedVlans.contains(hostVlanId)) {
225 sbuilder.matchVlanId(hostVlanId);
226 mbuilder.matchVlanId(hostVlanId);
227 } else if (hostVlanId.equals(VlanId.NONE)) {
228 if (untaggedVlan != null) {
229 sbuilder.matchVlanId(untaggedVlan);
230 mbuilder.matchVlanId(untaggedVlan);
231 tbuilder.immediate().popVlan();
232 } else if (nativeVlan != null) {
233 sbuilder.matchVlanId(nativeVlan);
234 mbuilder.matchVlanId(nativeVlan);
235 tbuilder.immediate().popVlan();
236 } else {
pierventrea3989be2021-01-08 16:43:17 +0100237 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native " +
Charles Chand66d6712018-03-29 16:03:41 -0700238 "vlan config", mac, hostVlanId, connectPoint);
239 return null;
240 }
241 } else {
242 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
243 mac, hostVlanId, connectPoint);
244 return null;
245 }
246
247 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
248 // If the objective is to revoke an existing rule, and for some reason
249 // the next-objective does not exist, then a new one should not be created
250 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
251 tbuilder.build(), mbuilder.build(), !revoke);
252 if (portNextObjId == -1) {
253 // Warning log will come from getPortNextObjective method
254 return null;
255 }
256
257 return DefaultForwardingObjective.builder()
258 .withFlag(ForwardingObjective.Flag.SPECIFIC)
259 .withSelector(sbuilder.build())
260 .nextStep(portNextObjId)
261 .withPriority(100)
262 .fromApp(srManager.appId)
263 .makePermanent();
264 }
265
266 /**
267 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
268 * and hostMAC connected to given port, and output to given port only when
269 * vlan information is valid.
270 *
271 * @param deviceId device ID that host attaches to
272 * @param portNum port number that host attaches to
273 * @param hostMac mac address of the host connected to the switch port
274 * @param vlanId Vlan ID configured on the switch port
275 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
276 * @param install true to populate the objective, false to revoke
pierventrea3989be2021-01-08 16:43:17 +0100277 * @return a completable future that completes when the update of the bridging rule completes
Charles Chand66d6712018-03-29 16:03:41 -0700278 */
279 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
280 // revokeBridging and bridgingFwdObjBuilder.
pierventrea3989be2021-01-08 16:43:17 +0100281 CompletableFuture<Objective> updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
Charles Chand66d6712018-03-29 16:03:41 -0700282 VlanId vlanId, boolean popVlan, boolean install) {
283 // Create host selector
284 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
285 sbuilder.matchEthDst(hostMac);
286
287 // Create host meta
288 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
289
290 sbuilder.matchVlanId(vlanId);
291 mbuilder.matchVlanId(vlanId);
292
293 // Create host treatment
294 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
295 tbuilder.immediate().setOutput(portNum);
296
297 if (popVlan) {
298 tbuilder.immediate().popVlan();
299 }
300
301 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
302 tbuilder.build(), mbuilder.build(), install);
pierventrea3989be2021-01-08 16:43:17 +0100303 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chand66d6712018-03-29 16:03:41 -0700304 if (portNextObjId != -1) {
305 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
306 .withFlag(ForwardingObjective.Flag.SPECIFIC)
307 .withSelector(sbuilder.build())
308 .nextStep(portNextObjId)
309 .withPriority(100)
310 .fromApp(srManager.appId)
311 .makePermanent();
312
313 ObjectiveContext context = new DefaultObjectiveContext(
pierventrea3989be2021-01-08 16:43:17 +0100314 (objective) -> {
315 log.debug("Brigding rule for {}/{} {}", hostMac, vlanId, install ? "populated" : "revoked");
316 future.complete(objective);
317 },
318 (objective, error) -> {
319 log.warn("Failed to {} bridging rule for {}/{}: {}", install ? "populate" : "revoke",
320 hostMac, vlanId, error);
321 future.complete(null);
322 });
Charles Chand66d6712018-03-29 16:03:41 -0700323 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
324 } else {
325 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
pierventrea3989be2021-01-08 16:43:17 +0100326 return CompletableFuture.completedFuture(null);
Charles Chand66d6712018-03-29 16:03:41 -0700327 }
pierventrea3989be2021-01-08 16:43:17 +0100328 return future;
Charles Chand66d6712018-03-29 16:03:41 -0700329 }
330
331 /**
332 * Populates IP rules for a route that has direct connection to the switch.
333 * This method should not be invoked directly without going through DefaultRoutingHandler.
sangho80f11cb2015-04-01 13:05:26 -0700334 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700335 * @param deviceId device ID of the device that next hop attaches to
336 * @param prefix IP prefix of the route
337 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800338 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700339 * @param outPort port where the next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000340 * @param directHost host is of type direct or indirect
Charles Chan12a8a842020-02-14 13:23:57 -0800341 * @return future that carries the flow objective if succeeded, null if otherwise
sangho80f11cb2015-04-01 13:05:26 -0700342 */
Charles Chan12a8a842020-02-14 13:23:57 -0800343 CompletableFuture<Objective> populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000344 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Saurav Das261c3002017-06-13 15:35:54 -0700345 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chanddac7fd2016-10-27 14:19:48 -0700346 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800347 ForwardingObjective.Builder fwdBuilder;
Charles Chan319d1a22015-11-03 10:42:14 -0800348 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700349 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -0700350 hostVlanId, outPort, null, null, directHost, false);
Charles Chan319d1a22015-11-03 10:42:14 -0800351 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -0700352 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan12a8a842020-02-14 13:23:57 -0800353 return CompletableFuture.completedFuture(null);
Charles Chan319d1a22015-11-03 10:42:14 -0800354 }
Saurav Das07c74602016-04-27 18:35:50 -0700355 if (fwdBuilder == null) {
Saurav Das368cf212017-03-15 15:15:14 -0700356 log.warn("Aborting host routing table entry due "
Charles Chanddac7fd2016-10-27 14:19:48 -0700357 + "to error for dev:{} route:{}", deviceId, prefix);
Charles Chan12a8a842020-02-14 13:23:57 -0800358 return CompletableFuture.completedFuture(null);
Saurav Das07c74602016-04-27 18:35:50 -0700359 }
Charles Chan910be6a2017-08-23 14:46:43 -0700360
361 int nextId = fwdBuilder.add().nextId();
Charles Chan12a8a842020-02-14 13:23:57 -0800362 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chan1eaf4802016-04-18 13:44:03 -0700363 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800364 (objective) -> {
365 log.debug("Direct routing rule for route {} populated. nextId={}", prefix, nextId);
366 future.complete(objective);
367 },
368 (objective, error) -> {
369 log.warn("Failed to populate direct routing rule for route {}: {}", prefix, error);
370 future.complete(null);
371 });
Charles Chan1eaf4802016-04-18 13:44:03 -0700372 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chanf4586112015-11-09 16:37:23 -0800373 rulePopulationCounter.incrementAndGet();
Charles Chan12a8a842020-02-14 13:23:57 -0800374 return future;
Charles Chanf4586112015-11-09 16:37:23 -0800375 }
376
Charles Chanb7f75ac2016-01-11 18:28:54 -0800377 /**
Charles Chanddac7fd2016-10-27 14:19:48 -0700378 * Removes IP rules for a route when the next hop is gone.
Charles Chand66d6712018-03-29 16:03:41 -0700379 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800380 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700381 * @param deviceId device ID of the device that next hop attaches to
382 * @param prefix IP prefix of the route
383 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800384 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700385 * @param outPort port that next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000386 * @param directHost host is of type direct or indirect
Charles Chan12a8a842020-02-14 13:23:57 -0800387 * @return future that carries the flow objective if succeeded, null if otherwise
Charles Chanb7f75ac2016-01-11 18:28:54 -0800388 */
Charles Chan12a8a842020-02-14 13:23:57 -0800389 CompletableFuture<Objective> revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000390 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chanddac7fd2016-10-27 14:19:48 -0700391 log.debug("Revoke IP table entry for route {} at {}:{}",
392 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800393 ForwardingObjective.Builder fwdBuilder;
394 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700395 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -0700396 hostVlanId, outPort, null, null, directHost, true);
Charles Chanf4586112015-11-09 16:37:23 -0800397 } catch (DeviceConfigNotFoundException e) {
398 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
Charles Chan12a8a842020-02-14 13:23:57 -0800399 return CompletableFuture.completedFuture(null);
Charles Chanf4586112015-11-09 16:37:23 -0800400 }
Charles Chanea702b12016-11-30 11:55:05 -0800401 if (fwdBuilder == null) {
402 log.warn("Aborting host routing table entries due "
403 + "to error for dev:{} route:{}", deviceId, prefix);
Charles Chan12a8a842020-02-14 13:23:57 -0800404 return CompletableFuture.completedFuture(null);
Charles Chanea702b12016-11-30 11:55:05 -0800405 }
Charles Chan12a8a842020-02-14 13:23:57 -0800406
407 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chan1eaf4802016-04-18 13:44:03 -0700408 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800409 (objective) -> {
410 log.debug("IP rule for route {} revoked", prefix);
411 future.complete(objective);
412 },
413 (objective, error) -> {
414 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error);
415 future.complete(null);
416 });
Charles Chan1eaf4802016-04-18 13:44:03 -0700417 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chan12a8a842020-02-14 13:23:57 -0800418 return future;
Charles Chanf4586112015-11-09 16:37:23 -0800419 }
420
Charles Chanddac7fd2016-10-27 14:19:48 -0700421 /**
Charles Chan18fa4252017-02-08 16:10:40 -0800422 * Returns a forwarding objective builder for routing rules.
423 * <p>
424 * The forwarding objective routes packets destined to a given prefix to
425 * given port on given device with given destination MAC.
Charles Chanddac7fd2016-10-27 14:19:48 -0700426 *
427 * @param deviceId device ID
428 * @param prefix prefix that need to be routed
429 * @param hostMac MAC address of the nexthop
Charles Chan90772a72017-02-08 15:52:08 -0800430 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700431 * @param outPort port where the nexthop attaches to
Saurav Das2cb38292017-03-29 19:09:17 -0700432 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000433 * @param directHost host is direct or indirect
Charles Chanddac7fd2016-10-27 14:19:48 -0700434 * @return forwarding objective builder
435 * @throws DeviceConfigNotFoundException if given device is not configured
436 */
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000437
Charles Chan61c086d2019-07-26 17:46:15 -0700438 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700439 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700440 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
Charles Chan61c086d2019-07-26 17:46:15 -0700441 VlanId innerVlan, EthType outerTpid,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000442 boolean directHost, boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800443 throws DeviceConfigNotFoundException {
Charles Chan61c086d2019-07-26 17:46:15 -0700444 int nextObjId;
445 if (directHost) {
446 // if the objective is to revoke an existing rule, and for some reason
447 // the next-objective does not exist, then a new one should not be created
448 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta =
449 getTreatmentAndMeta(deviceId, hostMac, hostVlanId, outPort, innerVlan, outerTpid);
450 if (treatmentAndMeta == null) {
451 // Warning log will come from getTreatmentAndMeta method
452 return null;
453 }
454 nextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
455 treatmentAndMeta.getLeft(), treatmentAndMeta.getRight(), !revoke);
456 } else {
457 // if the objective is to revoke an existing rule, and for some reason
458 // the next-objective does not exist, then a new one should not be created
459 nextObjId = srManager.getMacVlanNextObjectiveId(deviceId, hostMac, hostVlanId,
460 outPort, !revoke);
461 }
462 if (nextObjId == -1) {
463 // Warning log will come from getMacVlanNextObjective method
464 return null;
465 }
466
467 return DefaultForwardingObjective.builder()
468 .withSelector(buildIpSelectorFromIpPrefix(prefix).build())
469 .nextStep(nextObjId)
470 .fromApp(srManager.appId).makePermanent()
471 .withPriority(getPriorityFromPrefix(prefix))
472 .withFlag(ForwardingObjective.Flag.SPECIFIC);
473 }
474
475 private ImmutablePair<TrafficTreatment, TrafficSelector> getTreatmentAndMeta(
476 DeviceId deviceId, MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
477 VlanId innerVlan, EthType outerTpid)
478 throws DeviceConfigNotFoundException {
479 MacAddress routerMac;
480 routerMac = config.getDeviceMac(deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800481
Charles Chan90772a72017-02-08 15:52:08 -0800482 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700483 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
484 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
485 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700486
Charles Chan90772a72017-02-08 15:52:08 -0800487 // Create route treatment
pierventre50e1bb82020-12-14 19:31:03 +0100488 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder()
489 .deferred()
sangho27462c62015-05-14 00:39:53 -0700490 .setEthDst(hostMac)
Charles Chan61c086d2019-07-26 17:46:15 -0700491 .setEthSrc(routerMac)
sangho80f11cb2015-04-01 13:05:26 -0700492 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800493
Charles Chan90772a72017-02-08 15:52:08 -0800494 // Create route meta
495 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800496
Charles Chan61c086d2019-07-26 17:46:15 -0700497 // Adjust treatment and meta according to VLAN configuration
Charles Chan90772a72017-02-08 15:52:08 -0800498 if (taggedVlans.contains(hostVlanId)) {
pierventre50e1bb82020-12-14 19:31:03 +0100499 mbuilder.matchVlanId(hostVlanId);
Charles Chan90772a72017-02-08 15:52:08 -0800500 tbuilder.setVlanId(hostVlanId);
501 } else if (hostVlanId.equals(VlanId.NONE)) {
502 if (untaggedVlan != null) {
503 mbuilder.matchVlanId(untaggedVlan);
pierventre50e1bb82020-12-14 19:31:03 +0100504 tbuilder.popVlan();
Charles Chan90772a72017-02-08 15:52:08 -0800505 } else if (nativeVlan != null) {
506 mbuilder.matchVlanId(nativeVlan);
pierventre50e1bb82020-12-14 19:31:03 +0100507 tbuilder.popVlan();
Charles Chan90772a72017-02-08 15:52:08 -0800508 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700509 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
510 hostMac, hostVlanId, connectPoint);
511 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800512 }
513 } else {
Charles Chan61c086d2019-07-26 17:46:15 -0700514 // Double tagged hosts
515 if (innerVlan == null || outerTpid == null) {
516 log.warn("Failed to construct NextObj for double tagged hosts {}/{}. {} {}",
517 hostMac, hostVlanId,
518 (innerVlan == null) ? "innerVlan = null." : "",
519 (outerTpid == null) ? "outerTpid = null." : "");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700520 return null;
521 }
Charles Chan61c086d2019-07-26 17:46:15 -0700522 tbuilder.setVlanId(innerVlan);
523 tbuilder.pushVlan(outerTpid);
524 tbuilder.setVlanId(hostVlanId);
525 mbuilder.matchVlanId(VlanId.ANY);
Saurav Das07c74602016-04-27 18:35:50 -0700526 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000527
Charles Chan61c086d2019-07-26 17:46:15 -0700528 return ImmutablePair.of(tbuilder.build(), mbuilder.build());
sangho80f11cb2015-04-01 13:05:26 -0700529 }
530
531 /**
Saurav Das261c3002017-06-13 15:35:54 -0700532 * Populates IP flow rules for all the given prefixes reachable from the
533 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700534 *
Saurav Das261c3002017-06-13 15:35:54 -0700535 * @param targetSw switch where rules are to be programmed
536 * @param subnets subnets/prefixes being added
537 * @param destSw1 destination switch where the prefixes are reachable
538 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
539 * Should be null if there is no paired destination switch (by config)
540 * or if the given prefixes are reachable only via destSw1
541 * @param nextHops a map containing a set of next-hops for each destination switch.
542 * If destSw2 is not null, then this map must contain an
543 * entry for destSw2 with its next-hops from the targetSw
544 * (although the next-hop set may be empty in certain scenarios).
545 * If destSw2 is null, there should not be an entry in this
546 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700547 * @return true if all rules are set successfully, false otherwise
548 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700549 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700550 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
psneha86e60d32019-03-26 06:31:41 -0400551 // Get pair device of the target switch
552 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
553 // Route simplification will be off in case of the nexthop location at target switch is down
554 // (routing through spine case)
555 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
piera9941192019-04-24 16:12:47 +0200556 // Iterates over the routes. Checking:
psneha86e60d32019-03-26 06:31:41 -0400557 // If route simplification is enabled
558 // If the target device is another leaf in the network
559 if (srManager.routeSimplification && !routeSimplOff) {
piera9941192019-04-24 16:12:47 +0200560 Set<IpPrefix> subnetsToBePopulated = Sets.newHashSet();
psneha86e60d32019-03-26 06:31:41 -0400561 for (IpPrefix subnet : subnets) {
562 // Skip route programming on the target device
563 // If route simplification applies
564 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
565 // XXX route simplification assumes that source of the traffic
566 // towards the nexthops are co-located with the nexthops. In different
567 // scenarios will not work properly.
568 continue;
569 }
570 // populate the route in the remaning scenarios
piera9941192019-04-24 16:12:47 +0200571 subnetsToBePopulated.add(subnet);
psneha86e60d32019-03-26 06:31:41 -0400572 }
piera9941192019-04-24 16:12:47 +0200573 subnets = subnetsToBePopulated;
sangho80f11cb2015-04-01 13:05:26 -0700574 }
piera9941192019-04-24 16:12:47 +0200575 // populate the remaining routes in the target switch
576 return populateIpRulesForRouter(targetSw, subnets, destSw1, destSw2, nextHops);
Charles Chanc22cef32016-04-29 14:38:22 -0700577 }
sangho80f11cb2015-04-01 13:05:26 -0700578
Charles Chanc22cef32016-04-29 14:38:22 -0700579 /**
Charles Chand66d6712018-03-29 16:03:41 -0700580 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700581 *
Charles Chand66d6712018-03-29 16:03:41 -0700582 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700583 * @param subnets subnet being removed
584 * @return true if all rules are removed successfully, false otherwise
585 */
Charles Chand66d6712018-03-29 16:03:41 -0700586 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700587 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700588 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700589 return false;
590 }
591 }
sangho80f11cb2015-04-01 13:05:26 -0700592 return true;
593 }
594
595 /**
piera9941192019-04-24 16:12:47 +0200596 * Populates IP flow rules for a set of IP prefix in the target device.
597 * The prefix are reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700598 *
Saurav Das261c3002017-06-13 15:35:54 -0700599 * @param targetSw target device ID to set the rules
piera9941192019-04-24 16:12:47 +0200600 * @param subnets the set of IP prefix
Saurav Das261c3002017-06-13 15:35:54 -0700601 * @param destSw1 destination switch where the prefixes are reachable
602 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
603 * Should be null if there is no paired destination switch (by config)
604 * or if the given prefixes are reachable only via destSw1
605 * @param nextHops map of destination switches and their next-hops.
606 * Should only contain destination switches that are
607 * actually meant to be routed to. If destSw2 is null, there
608 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700609 * @return true if all rules are set successfully, false otherwise
610 */
piera9941192019-04-24 16:12:47 +0200611 private boolean populateIpRulesForRouter(DeviceId targetSw,
612 Set<IpPrefix> subnets,
613 DeviceId destSw1, DeviceId destSw2,
614 Map<DeviceId, Set<DeviceId>> nextHops) {
615 // pre-compute the needed information
616 int segmentIdIPv41, segmentIdIPv42 = -1;
617 int segmentIdIPv61, segmentIdIPv62 = -1;
618 TrafficTreatment treatment = null;
619 DestinationSet dsIPv4, dsIPv6;
620 TrafficSelector metaIpv4Selector, metaIpv6Selector = null;
621 int nextIdIPv4, nextIdIPv6, nextId;
622 TrafficSelector selector;
623 // start with MPLS SIDs
Charles Chan319d1a22015-11-03 10:42:14 -0800624 try {
piera9941192019-04-24 16:12:47 +0200625 segmentIdIPv41 = config.getIPv4SegmentId(destSw1);
626 segmentIdIPv61 = config.getIPv6SegmentId(destSw1);
627 if (destSw2 != null) {
628 segmentIdIPv42 = config.getIPv4SegmentId(destSw2);
629 segmentIdIPv62 = config.getIPv6SegmentId(destSw2);
Pier Ventreadb4ae62016-11-23 09:57:42 -0800630 }
Charles Chan319d1a22015-11-03 10:42:14 -0800631 } catch (DeviceConfigNotFoundException e) {
632 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
633 return false;
634 }
piera9941192019-04-24 16:12:47 +0200635 // build the IPv4 and IPv6 destination set
Saurav Das261c3002017-06-13 15:35:54 -0700636 if (destSw2 == null) {
637 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800638 // If the next hop is the same as the final destination, then MPLS
639 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700640 Set<DeviceId> nhd1 = nextHops.get(destSw1);
641 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
piera9941192019-04-24 16:12:47 +0200642 dsIPv4 = DestinationSet.createTypePushNone(destSw1);
643 dsIPv6 = DestinationSet.createTypePushNone(destSw1);
644 treatment = DefaultTrafficTreatment.builder()
645 .immediate()
646 .decNwTtl()
647 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700648 } else {
piera9941192019-04-24 16:12:47 +0200649 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1);
650 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700651 }
652 } else {
653 // dst pair - IP rules for dst-pairs are always from other edge nodes
654 // the destination set needs to have both destinations, even if there
655 // are no next hops to one of them
piera9941192019-04-24 16:12:47 +0200656 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1, segmentIdIPv42, destSw2);
657 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1, segmentIdIPv62, destSw2);
sangho80f11cb2015-04-01 13:05:26 -0700658 }
659
Saurav Das4c35fc42015-11-20 15:27:53 -0800660 // setup metadata to pass to nextObjective - indicate the vlan on egress
661 // if needed by the switch pipeline. Since neighbor sets are always to
662 // other neighboring routers, there is no subnet assigned on those ports.
piera9941192019-04-24 16:12:47 +0200663 metaIpv4Selector = buildIpv4Selector()
664 .matchVlanId(srManager.getDefaultInternalVlan())
665 .build();
666 metaIpv6Selector = buildIpv6Selector()
667 .matchVlanId(srManager.getDefaultInternalVlan())
668 .build();
669 // get the group handler of the target switch
Saurav Das261c3002017-06-13 15:35:54 -0700670 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700671 if (grpHandler == null) {
672 log.warn("populateIPRuleForRouter: groupHandler for device {} "
piera9941192019-04-24 16:12:47 +0200673 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700674 return false;
675 }
piera9941192019-04-24 16:12:47 +0200676 // get next id
677 nextIdIPv4 = grpHandler.getNextObjectiveId(dsIPv4, nextHops, metaIpv4Selector, false);
678 if (nextIdIPv4 <= 0) {
679 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv4);
sangho2165d222015-05-01 09:38:25 -0700680 return false;
681 }
piera9941192019-04-24 16:12:47 +0200682 nextIdIPv6 = grpHandler.getNextObjectiveId(dsIPv6, nextHops, metaIpv6Selector, false);
683 if (nextIdIPv6 <= 0) {
684 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv6);
685 return false;
Charles Chanf4586112015-11-09 16:37:23 -0800686 }
piera9941192019-04-24 16:12:47 +0200687 // build all the flow rules and send to the device
688 for (IpPrefix subnet : subnets) {
689 selector = buildIpSelectorFromIpPrefix(subnet).build();
690 if (subnet.isIp4()) {
691 nextId = nextIdIPv4;
692 } else {
693 nextId = nextIdIPv6;
694 }
695 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
696 .builder()
697 .fromApp(srManager.appId)
698 .makePermanent()
699 .nextStep(nextId)
700 .withSelector(selector)
701 .withPriority(getPriorityFromPrefix(subnet))
702 .withFlag(ForwardingObjective.Flag.SPECIFIC);
703 if (treatment != null) {
704 fwdBuilder.withTreatment(treatment);
705 }
706 log.debug("Installing {} forwarding objective for router IP/subnet {} "
707 + "in switch {} with nextId: {}", subnet.isIp4() ? "IPv4" : "IPv6",
708 subnet, targetSw, nextId);
709 ObjectiveContext context = new DefaultObjectiveContext(
710 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
711 subnet, targetSw),
712 (objective, error) -> log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
713 subnet, error, targetSw));
714 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
715 }
716 rulePopulationCounter.addAndGet(subnets.size());
sangho80f11cb2015-04-01 13:05:26 -0700717 return true;
718 }
719
sangho80f11cb2015-04-01 13:05:26 -0700720 /**
Charles Chand66d6712018-03-29 16:03:41 -0700721 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700722 *
Charles Chand66d6712018-03-29 16:03:41 -0700723 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700724 * @param ipPrefix the IP address of the destination router
725 * @return true if all rules are removed successfully, false otherwise
726 */
Charles Chand66d6712018-03-29 16:03:41 -0700727 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800728 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700729 TrafficSelector selector = sbuilder.build();
730 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
731
732 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
733 .builder()
734 .fromApp(srManager.appId)
735 .makePermanent()
736 .withSelector(selector)
737 .withTreatment(dummyTreatment)
738 .withPriority(getPriorityFromPrefix(ipPrefix))
739 .withFlag(ForwardingObjective.Flag.SPECIFIC);
740
Charles Chand66d6712018-03-29 16:03:41 -0700741 ObjectiveContext context = new DefaultObjectiveContext(
742 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
743 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
744 ipPrefix, targetSw, error));
745 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700746
747 return true;
748 }
749
750 /**
Saurav Das97241862018-02-14 14:14:54 -0800751 * Populates MPLS flow rules in the target device to point towards the
752 * destination device.
753 *
754 * @param targetSwId target device ID of the switch to set the rules
755 * @param destSwId destination switch device ID
756 * @param nextHops next hops switch ID list
757 * @param routerIp the router ip of the destination switch
758 * @return true if all rules are set successfully, false otherwise
759 */
760 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
761 Set<DeviceId> nextHops, IpAddress routerIp) {
762 int segmentId;
763 try {
764 if (routerIp.isIp4()) {
765 segmentId = config.getIPv4SegmentId(destSwId);
766 } else {
767 segmentId = config.getIPv6SegmentId(destSwId);
768 }
769 } catch (DeviceConfigNotFoundException e) {
770 log.warn(e.getMessage() + " Aborting populateMplsRule.");
771 return false;
772 }
773
774 List<ForwardingObjective> fwdObjs = new ArrayList<>();
775 Collection<ForwardingObjective> fwdObjsMpls;
776 // Generates the transit rules used by the standard "routing".
777 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
778 routerIp, true);
779 if (fwdObjsMpls.isEmpty()) {
780 return false;
781 }
782 fwdObjs.addAll(fwdObjsMpls);
783
784 // Generates the transit rules used by the MPLS Pwaas.
785 int pwSrLabel;
786 try {
787 pwSrLabel = config.getPWRoutingLabel(destSwId);
788 } catch (DeviceConfigNotFoundException e) {
789 log.warn(e.getMessage()
790 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
791 return false;
792 }
793 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
794 routerIp, false);
795 if (fwdObjsMpls.isEmpty()) {
796 return false;
797 }
798 fwdObjs.addAll(fwdObjsMpls);
799
800 for (ForwardingObjective fwdObj : fwdObjs) {
801 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
802 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
803 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
804 rulePopulationCounter.incrementAndGet();
805 }
806
807 return true;
808 }
809
810 /**
811 * Differentiates between popping and swapping labels when building an MPLS
812 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700813 *
814 * @param targetSwId the target sw
815 * @param destSwId the destination sw
816 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800817 * @param segmentId the segmentId to match representing the destination
818 * switch
819 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700820 * @return a collection of fwdobjective
821 */
Saurav Das261c3002017-06-13 15:35:54 -0700822 private Collection<ForwardingObjective> handleMpls(
823 DeviceId targetSwId,
824 DeviceId destSwId,
825 Set<DeviceId> nextHops,
826 int segmentId,
827 IpAddress routerIp,
828 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700829
830 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
831 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800832 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700833 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
834 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
835 sbuilder.matchMplsBos(isMplsBos);
836 TrafficSelector selector = sbuilder.build();
837
838 // setup metadata to pass to nextObjective - indicate the vlan on egress
839 // if needed by the switch pipeline. Since mpls next-hops are always to
840 // other neighboring routers, there is no subnet assigned on those ports.
841 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700842 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre229fd0b2016-10-31 16:49:19 -0700843
844 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
845 // If the next hop is the destination router for the segment, do pop
846 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700847 + "label {} in switch {} with pop to next-hops {}",
848 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700849 ForwardingObjective.Builder fwdObjNoBosBuilder =
850 getMplsForwardingObjective(targetSwId,
851 nextHops,
852 true,
853 isMplsBos,
854 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700855 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800856 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700857 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700858 // Error case, we cannot handle, exit.
859 if (fwdObjNoBosBuilder == null) {
860 return Collections.emptyList();
861 }
862 fwdObjBuilders.add(fwdObjNoBosBuilder);
863
864 } else {
Saurav Das97241862018-02-14 14:14:54 -0800865 // next hop is not destination, irrespective of the number of next
866 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700867 log.debug("Installing MPLS forwarding objective for "
868 + "label {} in switch {} without pop to next-hops {}",
869 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700870 ForwardingObjective.Builder fwdObjNoBosBuilder =
871 getMplsForwardingObjective(targetSwId,
872 nextHops,
873 false,
874 isMplsBos,
875 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700876 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800877 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700878 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700879 // Error case, we cannot handle, exit.
880 if (fwdObjNoBosBuilder == null) {
881 return Collections.emptyList();
882 }
883 fwdObjBuilders.add(fwdObjNoBosBuilder);
884
885 }
886
887 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
888 // We add the final property to the fwdObjs.
889 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700890 ((Builder) ((Builder) fwdObjBuilder
891 .fromApp(srManager.appId)
892 .makePermanent())
893 .withSelector(selector)
894 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
895 .withFlag(ForwardingObjective.Flag.SPECIFIC);
896
897 ObjectiveContext context = new DefaultObjectiveContext(
898 (objective) ->
899 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
900 objective.id(), segmentId, targetSwId),
901 (objective, error) ->
902 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
903 objective.id(), segmentId, error, targetSwId));
904
905 ForwardingObjective fob = fwdObjBuilder.add(context);
906 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700907 }
908
909 return fwdObjs;
910 }
911
912 /**
Saurav Das97241862018-02-14 14:14:54 -0800913 * Returns a Forwarding Objective builder for the MPLS rule that references
914 * the desired Next Objective. Creates a DestinationSet that allows the
915 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700916 *
Saurav Das97241862018-02-14 14:14:54 -0800917 * @param targetSw the target sw
918 * @param nextHops the set of next hops
919 * @param phpRequired true if penultimate-hop-popping is required
920 * @param isBos true if matched label is bottom-of-stack
921 * @param meta metadata for creating next objective
922 * @param routerIp the router ip representing the destination switch
923 * @param destSw the destination sw
924 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700925 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800926 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700927 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800928 Set<DeviceId> nextHops,
929 boolean phpRequired,
930 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800931 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700932 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800933 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700934 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800935
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700936 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
937 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700938
939 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800940 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700941 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800942 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700943 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800944 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700945 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700946 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700947 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800948 if (routerIp.isIp4()) {
949 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
950 } else {
951 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
952 }
953 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800954 // standard case -> BoS == True; pop results in IP packet and forwarding
955 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700956 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700957 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800958 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
959 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800960 // double-label case -> BoS == False, pop results in MPLS packet
961 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700962 ds = DestinationSet.createTypePopNotBos(destSw);
963 if (!srManager.getMplsEcmp()) {
964 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800965 }
sangho80f11cb2015-04-01 13:05:26 -0700966 }
967 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800968 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800969 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700970 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800971 // swap results in MPLS packet with same BoS bit regardless of bit value
972 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700973 // differentiate here between swap with not bos or swap with bos
974 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
975 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
976 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800977 simple = true;
978 }
sangho80f11cb2015-04-01 13:05:26 -0700979 }
980
Saurav Das4c35fc42015-11-20 15:27:53 -0800981 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800982 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
983 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700984 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
985 if (gh == null) {
986 log.warn("getNextObjectiveId query - groupHandler for device {} "
987 + "not found", targetSw);
988 return null;
989 }
Saurav Das97241862018-02-14 14:14:54 -0800990
Saurav Das261c3002017-06-13 15:35:54 -0700991 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
992 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800993 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800994 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800995 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800996 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700997 } else {
Saurav Das97241862018-02-14 14:14:54 -0800998 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
999 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -07001000 }
1001
Saurav Das4c35fc42015-11-20 15:27:53 -08001002 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -07001003 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -07001004 }
1005
1006 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001007 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -07001008 * dstMac corresponding to the router's MAC address. For those pipelines
1009 * that need to internally assign vlans to untagged packets, this method
1010 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -07001011 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -08001012 * Note that the vlan assignment and filter programming should only be done by
1013 * the master for a switch. This method is typically called at deviceAdd and
1014 * programs filters only for the enabled ports of the device. For port-updates,
1015 * that enable/disable ports after device add, singlePortFilter methods should
1016 * be called.
sangho80f11cb2015-04-01 13:05:26 -07001017 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001018 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -08001019 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -07001020 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001021 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -07001022 log.debug("Installing per-port filtering objective for untagged "
1023 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -08001024
Saurav Das07c74602016-04-27 18:35:50 -07001025 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -08001026 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -07001027 log.warn("Device {} ports not available. Unable to add MacVlan filters",
1028 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -08001029 return null;
Saurav Das07c74602016-04-27 18:35:50 -07001030 }
Saurav Dasf9332192017-02-18 14:05:44 -08001031 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -07001032 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -07001033 if (!port.isEnabled()) {
1034 disabledPorts++;
1035 continue;
1036 }
Charles Chan43be46b2017-02-26 22:59:35 -08001037 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001038 filteredPorts++;
1039 } else {
1040 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -07001041 }
Saurav Das7c305372015-10-28 12:39:42 -07001042 }
Charles Chan077314e2017-06-22 14:27:17 -07001043 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -08001044 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan9d2dd552018-06-19 20:56:33 -07001045 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Dasf9332192017-02-18 14:05:44 -08001046 }
1047
1048 /**
Charles Chan43be46b2017-02-26 22:59:35 -08001049 * Creates or removes filtering objectives for a single port. Should only be
1050 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -08001051 *
1052 * @param deviceId device identifier
1053 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -08001054 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -08001055 * @return true if no errors occurred during the build of the filtering objective
1056 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001057 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -08001058 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -07001059 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
1060 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
1061 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -08001062
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001063 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -08001064 if (taggedVlans.size() != 0) {
1065 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -07001066 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
pierventrea3989be2021-01-08 16:43:17 +01001067 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId,
1068 install, false))) {
Charles Chan90772a72017-02-08 15:52:08 -08001069 return false;
1070 }
1071 if (nativeVlan != null) {
1072 // Filter for native vlan
pierventrea3989be2021-01-08 16:43:17 +01001073 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan,
1074 install, false)) {
Charles Chan90772a72017-02-08 15:52:08 -08001075 return false;
1076 }
1077 }
1078 } else if (untaggedVlan != null) {
1079 // Filter for untagged vlan
pierventrea3989be2021-01-08 16:43:17 +01001080 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan,
1081 install, false)) {
Charles Chan90772a72017-02-08 15:52:08 -08001082 return false;
1083 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001084 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001085 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das9bf49582018-08-13 15:34:26 -07001086 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1087 srManager.getDefaultInternalVlan(),
pierventrea3989be2021-01-08 16:43:17 +01001088 install, false)) {
Charles Chan90772a72017-02-08 15:52:08 -08001089 return false;
1090 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001091 // Filter for receiveing pseudowire traffic
Saurav Das9bf49582018-08-13 15:34:26 -07001092 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1093 srManager.getPwTransportVlan(),
pierventrea3989be2021-01-08 16:43:17 +01001094 install, false)) {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001095 return false;
1096 }
Charles Chan90772a72017-02-08 15:52:08 -08001097 }
1098 return true;
1099 }
1100
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001101 /**
1102 * Updates filtering objectives for a single port. Should only be called by
1103 * the master for a switch
1104 * @param deviceId device identifier
1105 * @param portNum port identifier for port to be filtered
1106 * @param pushVlan true to push vlan, false otherwise
1107 * @param vlanId vlan identifier
1108 * @param install true to install the filtering objective, false to remove
1109 */
1110 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1111 boolean pushVlan, VlanId vlanId, boolean install) {
pierventrea3989be2021-01-08 16:43:17 +01001112 // NOTE: update port filters is used only when the vlan configuration
1113 // has been updated. Port configuration is never removed here.
1114 // For pipeline sharing the TMAC entry among different vlans
1115 // there is no need to push or remove the TMAC entry
1116 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install, true)) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001117 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1118 deviceId, portNum, vlanId);
1119 }
1120 }
1121
Charles Chan43be46b2017-02-26 22:59:35 -08001122 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
pierventrea3989be2021-01-08 16:43:17 +01001123 boolean pushVlan, VlanId vlanId, boolean install,
1124 boolean update) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001125 boolean doTMAC = true;
1126
1127 if (!pushVlan) {
1128 // Skip the tagged vlans belonging to an interface without an IP address
1129 Set<Interface> ifaces = srManager.interfaceService
1130 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1131 .stream()
1132 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1133 .collect(Collectors.toSet());
1134 if (!ifaces.isEmpty()) {
1135 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1136 vlanId, deviceId, portnum);
1137 doTMAC = false;
1138 }
1139 }
1140
pierventrea3989be2021-01-08 16:43:17 +01001141 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC, update);
Saurav Dasf9332192017-02-18 14:05:44 -08001142 if (fob == null) {
1143 // error encountered during build
1144 return false;
1145 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001146 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001147 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001148 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001149 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001150 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001151 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001152 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001153 if (install) {
1154 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1155 } else {
1156 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001157 }
Charles Chan90772a72017-02-08 15:52:08 -08001158 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001159 }
1160
Charles Chan90772a72017-02-08 15:52:08 -08001161 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
pierventrea3989be2021-01-08 16:43:17 +01001162 boolean pushVlan, VlanId vlanId,
1163 boolean doTMAC, boolean update) {
Saurav Dasf9332192017-02-18 14:05:44 -08001164 MacAddress deviceMac;
1165 try {
1166 deviceMac = config.getDeviceMac(deviceId);
1167 } catch (DeviceConfigNotFoundException e) {
1168 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1169 return null;
1170 }
Saurav Dasf9332192017-02-18 14:05:44 -08001171 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001172
1173 if (doTMAC) {
1174 fob.withKey(Criteria.matchInPort(portnum))
1175 .addCondition(Criteria.matchEthDst(deviceMac))
1176 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1177 } else {
1178 fob.withKey(Criteria.matchInPort(portnum))
1179 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1180 }
Charles Chan90772a72017-02-08 15:52:08 -08001181
Charles Chan17ca2202017-12-19 19:55:57 -08001182 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1183
Charles Chan90772a72017-02-08 15:52:08 -08001184 if (pushVlan) {
1185 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001186 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001187 } else {
1188 fob.addCondition(Criteria.matchVlanId(vlanId));
1189 }
1190
Charles Chan17ca2202017-12-19 19:55:57 -08001191 // NOTE: Some switch hardware share the same filtering flow among different ports.
1192 // We use this metadata to let the driver know that there is no more enabled port
1193 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001194 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001195 tBuilder.wipeDeferred();
1196 }
1197
pierventrea3989be2021-01-08 16:43:17 +01001198 // NOTE: Some switch hardware share the same tmac flow among different vlans.
1199 // We use this metadata to let the driver know that there is still a vlan
1200 // configuration associated to that port
1201 if (update) {
1202 tBuilder.writeMetadata(INTERFACE_CONFIG_UPDATE, METADATA_MASK);
1203 }
1204
Charles Chan17ca2202017-12-19 19:55:57 -08001205 fob.withMeta(tBuilder.build());
1206
Saurav Dasf9332192017-02-18 14:05:44 -08001207 fob.permit().fromApp(srManager.appId);
1208 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001209 }
1210
1211 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001212 * Creates or removes filtering objectives for a double-tagged host on a port.
1213 *
1214 * @param deviceId device identifier
1215 * @param portNum port identifier for port to be filtered
1216 * @param outerVlan outer VLAN ID
1217 * @param innerVlan inner VLAN ID
1218 * @param install true to install the filtering objective, false to remove
1219 */
1220 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1221 VlanId innerVlan, boolean install) {
Daniele Moro8fc37b42019-10-29 18:48:35 -07001222 // We should trigger the removal of double tagged rules only when removing
1223 // the filtering objective and no other hosts are connected to the same device port.
Charles Chanf17fade2020-03-08 18:07:19 -07001224 boolean cleanupDoubleTaggedRules = !anyDoubleTaggedHost(deviceId, portNum) && !install;
Daniele Moro8fc37b42019-10-29 18:48:35 -07001225 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum,
1226 outerVlan, innerVlan,
1227 cleanupDoubleTaggedRules);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001228 if (fob == null) {
1229 // error encountered during build
1230 return;
1231 }
1232 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1233 install ? "Installing" : "Removing", deviceId, portNum);
1234 ObjectiveContext context = new DefaultObjectiveContext(
1235 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1236 install ? "installed" : "removed"),
1237 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1238 install ? "install" : "remove", deviceId, portNum, error));
1239 if (install) {
1240 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1241 } else {
1242 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1243 }
1244 }
1245
Charles Chanf17fade2020-03-08 18:07:19 -07001246 /**
1247 * Checks if there is any double tagged host attached to given location.
1248 * This method will match on the effective location of a host.
1249 * That is, it will match on auxLocations when auxLocations is not null. Otherwise, it will match on locations.
1250 *
1251 * @param deviceId device ID
1252 * @param portNum port number
1253 * @return true if there is any host attached to given location.
1254 */
1255 private boolean anyDoubleTaggedHost(DeviceId deviceId, PortNumber portNum) {
1256 ConnectPoint cp = new ConnectPoint(deviceId, portNum);
1257 Set<Host> connectedHosts = srManager.hostService.getConnectedHosts(cp, false);
1258 Set<Host> auxConnectedHosts = srManager.hostService.getConnectedHosts(cp, true);
1259 return !auxConnectedHosts.isEmpty() ||
1260 connectedHosts.stream().anyMatch(host -> host.auxLocations() == null);
1261 }
1262
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001263 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001264 VlanId outerVlan, VlanId innerVlan,
1265 boolean cleanupDoubleTaggedRules) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001266 MacAddress deviceMac;
1267 try {
1268 deviceMac = config.getDeviceMac(deviceId);
1269 } catch (DeviceConfigNotFoundException e) {
1270 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1271 return null;
1272 }
1273 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1274 // Outer vlan id match should be appeared before inner vlan id match.
1275 fob.withKey(Criteria.matchInPort(portNum))
1276 .addCondition(Criteria.matchEthDst(deviceMac))
1277 .addCondition(Criteria.matchVlanId(outerVlan))
Daniele Moro998f2df2019-07-12 17:58:54 -07001278 .addCondition(Criteria.matchInnerVlanId(innerVlan))
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001279 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1280
1281 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1282 // Pop outer vlan
1283 tBuilder.popVlan();
1284
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001285 // special metadata for driver
1286 if (cleanupDoubleTaggedRules) {
pierventrea3989be2021-01-08 16:43:17 +01001287 tBuilder.writeMetadata(CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES, METADATA_MASK);
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001288 } else {
pierventrea3989be2021-01-08 16:43:17 +01001289 tBuilder.writeMetadata(0, METADATA_MASK);
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001290 }
1291
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001292 // NOTE: Some switch hardware share the same filtering flow among different ports.
1293 // We use this metadata to let the driver know that there is no more enabled port
1294 // within the same VLAN on this device.
1295 if (noMoreEnabledPort(deviceId, outerVlan)) {
1296 tBuilder.wipeDeferred();
1297 }
1298
1299 fob.withMeta(tBuilder.build());
1300
1301 fob.permit().fromApp(srManager.appId);
1302 return fob;
1303 }
1304
1305 /**
Danny Chang44a7b952020-09-08 15:27:04 -07001306 * Creates packet requests to punt all IP packets for the router.
1307 * @param deviceId the switch dpid for the router
1308 */
1309 void populateIpPunts(DeviceId deviceId) {
1310 manageIpPunts(deviceId, true);
1311 }
1312
1313 /**
1314 * Creates a packet request to punt all IP packets, destined to the
1315 * specified IP address, which should be router's port IP address.
1316 *
1317 * @param deviceId the switch dpid for the router
1318 * @param ipAddress the IP address of the router's port
1319 */
1320 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1321 manageSingleIpPunts(deviceId, ipAddress, true);
1322 }
1323
1324 /**
1325 * Revokes packet requests for all devices.
1326 */
1327 void revokePacketsPunts() {
1328 srManager.deviceService.getDevices().forEach(device -> {
1329 manageIpPunts(device.id(), false);
1330 });
1331 }
1332
1333 /**
1334 * Revokes the packet request to punt all IP packets, destined to the
1335 * router's port IP address, except for the router's IP address.
1336 *
1337 * @param deviceId the switch dpid for the router
1338 * @param ipAddress the IP address of the router's port
1339 */
1340 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1341 try {
1342 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1343 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1344 manageSingleIpPunts(deviceId, ipAddress, false);
1345 }
1346 } catch (DeviceConfigNotFoundException e) {
1347 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
1348 }
1349 }
1350
1351 /**
1352 * Creates or removes forwarding objectives ( packet-requests ) to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001353 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001354 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001355 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001356 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001357 * @param deviceId the switch dpid for the router
Danny Chang44a7b952020-09-08 15:27:04 -07001358 * @param request true to create a packet request, false to remove
sangho80f11cb2015-04-01 13:05:26 -07001359 */
Danny Chang44a7b952020-09-08 15:27:04 -07001360 void manageIpPunts(DeviceId deviceId, boolean request) {
Saurav Das261c3002017-06-13 15:35:54 -07001361 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001362 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001363 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001364 routerIpv4 = config.getRouterIpv4(deviceId);
1365 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001366 routerLinkLocalIpv6 = Ip6Address.valueOf(
1367 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1368
Saurav Das261c3002017-06-13 15:35:54 -07001369 if (config.isPairedEdge(deviceId)) {
1370 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1371 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1372 }
Charles Chan319d1a22015-11-03 10:42:14 -08001373 } catch (DeviceConfigNotFoundException e) {
Danny Chang44a7b952020-09-08 15:27:04 -07001374 log.warn(e.getMessage() + " Aborting manageIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001375 return;
1376 }
1377
Danny Chang44a7b952020-09-08 15:27:04 -07001378 if (request && !srManager.mastershipService.isLocalMaster(deviceId)) {
Saurav Dasc28b3432015-10-30 17:45:38 -07001379 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1380 deviceId);
1381 return;
1382 }
Danny Chang44a7b952020-09-08 15:27:04 -07001383
Pier Ventreadb4ae62016-11-23 09:57:42 -08001384 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1385 allIps.add(routerIpv4);
1386 if (routerIpv6 != null) {
1387 allIps.add(routerIpv6);
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001388 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001389 }
Saurav Das261c3002017-06-13 15:35:54 -07001390 if (pairRouterIpv4 != null) {
1391 allIps.add(pairRouterIpv4);
1392 }
1393 if (pairRouterIpv6 != null) {
1394 allIps.add(pairRouterIpv6);
1395 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001396 for (IpAddress ipaddr : allIps) {
Danny Chang44a7b952020-09-08 15:27:04 -07001397 manageSingleIpPunts(deviceId, ipaddr, request);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001398 }
1399 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001400
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001401 /**
Danny Chang44a7b952020-09-08 15:27:04 -07001402 * Creates or removes a forwarding objective ( packet-request ) to punt all IP packets, destined to the
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001403 * specified IP address, which should be router's port IP address.
1404 *
1405 * @param deviceId the switch dpid for the router
1406 * @param ipAddress the IP address of the router's port
Danny Chang44a7b952020-09-08 15:27:04 -07001407 * @param request true to create a packet request, false to remove
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001408 */
Danny Chang44a7b952020-09-08 15:27:04 -07001409 void manageSingleIpPunts(DeviceId deviceId, IpAddress ipAddress, boolean request) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001410 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1411 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1412
Danny Chang44a7b952020-09-08 15:27:04 -07001413 if (request) {
1414 srManager.packetService.requestPackets(sbuilder.build(),
1415 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1416 } else {
1417 srManager.packetService.cancelPackets(sbuilder.build(),
1418 PacketPriority.CONTROL, srManager.appId, optDeviceId);
Saurav Das9f1c42e2015-10-23 10:51:11 -07001419 }
sangho80f11cb2015-04-01 13:05:26 -07001420 }
1421
piera9941192019-04-24 16:12:47 +02001422 // Method for building an IPv4 selector
1423 private TrafficSelector.Builder buildIpv4Selector() {
1424 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1425 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1426 return selectorBuilder;
1427 }
1428
1429 // Method for building an IPv6 selector
1430 private TrafficSelector.Builder buildIpv6Selector() {
1431 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1432 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1433 return selectorBuilder;
1434 }
1435
1436 // Method for building an IPv4 or IPv6 selector from an IP address
Pier Ventreadb4ae62016-11-23 09:57:42 -08001437 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1438 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1439 }
1440
piera9941192019-04-24 16:12:47 +02001441 // Method for building an IPv4 or IPv6 selector from an IP prefix
Pier Ventreadb4ae62016-11-23 09:57:42 -08001442 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1443 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001444 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001445 if (prefixToMatch.isIp4()) {
1446 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1447 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1448 return selectorBuilder;
1449 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001450 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001451 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1452 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1453 return selectorBuilder;
1454 }
1455
1456 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001457 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1458 * Furthermore, these are applied only by the master instance. Deferred actions
1459 * are not cleared such that packets can be flooded in the cross connect use case
1460 *
1461 * @param deviceId the switch dpid for the router
1462 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001463 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001464 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001465 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1466 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1467 deviceId);
1468 return;
1469 }
1470
Charles Chan3ed34d82017-06-22 18:03:14 -07001471 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001472 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001473 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001474 .add(new ObjectiveContext() {
1475 @Override
1476 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001477 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001478 deviceId, error);
1479 }
1480 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001481 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001482
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001483 if (isIpv6Configured(deviceId)) {
1484 // We punt all NDP packets towards the controller.
1485 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1486 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1487 @Override
1488 public void onError(Objective objective, ObjectiveError error) {
1489 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1490 deviceId, error);
1491 }
1492 });
1493 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan051490d2018-01-11 11:48:18 -08001494 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001495 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001496
Saurav Dasec683dc2018-04-27 18:42:30 -07001497 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001498 ForwardingObjective pairFwdObj;
1499 // Do not punt ARP packets from pair port
1500 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1501 .add(new ObjectiveContext() {
1502 @Override
1503 public void onError(Objective objective, ObjectiveError error) {
1504 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1505 deviceId, error);
1506 }
1507 });
1508 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1509
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001510 if (isIpv6Configured(deviceId)) {
1511 // Do not punt NDP packets from pair port
1512 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1513 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan3ed34d82017-06-22 18:03:14 -07001514 @Override
1515 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001516 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan3ed34d82017-06-22 18:03:14 -07001517 deviceId, error);
1518 }
1519 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001520 srManager.flowObjectiveService.forward(deviceId, obj);
1521 });
1522
1523 // Do not forward DAD packets from pair port
1524 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1525 .add(new ObjectiveContext() {
1526 @Override
1527 public void onError(Objective objective, ObjectiveError error) {
1528 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1529 deviceId, error);
1530 }
1531 });
1532 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1533 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001534 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001535 }
1536
Charles Chan3ed34d82017-06-22 18:03:14 -07001537 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1538 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001539 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001540 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001541 .withSelector(selector)
1542 .fromApp(srManager.appId)
1543 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001544 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001545 .makePermanent();
1546 }
1547
Charles Chan3ed34d82017-06-22 18:03:14 -07001548 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001549 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1550 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001551 if (port != null) {
1552 sBuilder.matchInPort(port);
1553 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001554
Charles Chan3ed34d82017-06-22 18:03:14 -07001555 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1556 if (punt) {
1557 tBuilder.punt();
Charles Chan90dd9322021-06-07 18:52:48 -07001558 } else {
1559 tBuilder.wipeDeferred();
Charles Chan3ed34d82017-06-22 18:03:14 -07001560 }
1561 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001562 }
1563
Charles Chan051490d2018-01-11 11:48:18 -08001564 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1565 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001566
Charles Chan051490d2018-01-11 11:48:18 -08001567 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1568 .forEach(type -> {
1569 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1570 sBuilder.matchEthType(TYPE_IPV6)
1571 .matchIPProtocol(PROTOCOL_ICMP6)
1572 .matchIcmpv6Type(type);
1573 if (port != null) {
1574 sBuilder.matchInPort(port);
1575 }
1576
1577 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1578 if (punt) {
1579 tBuilder.punt();
Charles Chan90dd9322021-06-07 18:52:48 -07001580 } else {
1581 tBuilder.wipeDeferred();
Charles Chan051490d2018-01-11 11:48:18 -08001582 }
1583
1584 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1585 });
1586
1587 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001588 }
1589
1590 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1591 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1592 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001593 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1594 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1595 // .matchIPProtocol(PROTOCOL_ICMP6)
1596 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001597 if (port != null) {
1598 sBuilder.matchInPort(port);
1599 }
1600
1601 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1602 tBuilder.wipeDeferred();
1603 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001604 }
1605
1606 /**
Charles Chan155ec442018-09-16 14:30:19 -07001607 * Block given prefix in routing table.
Charles Chanf4586112015-11-09 16:37:23 -08001608 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001609 * @param address the address to block
1610 * @param deviceId switch ID to set the rules
1611 */
1612 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1613 updateDefaultRouteBlackhole(deviceId, address, true);
1614 }
1615
1616 /**
Charles Chan155ec442018-09-16 14:30:19 -07001617 * Unblock given prefix in routing table.
Andrea Campanella60ce2222018-04-30 11:48:55 +02001618 *
1619 * @param address the address to block
1620 * @param deviceId switch ID to set the rules
1621 */
1622 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1623 updateDefaultRouteBlackhole(deviceId, address, false);
1624 }
1625
1626 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1627 try {
1628 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1629
1630 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1631 if (address.isIp4()) {
1632 sbuilder.matchIPDst(address);
1633 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1634 } else {
1635 sbuilder.matchIPv6Dst(address);
1636 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1637 }
1638
1639 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
Andrea Campanella60ce2222018-04-30 11:48:55 +02001640 tBuilder.wipeDeferred();
1641
1642 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1643 fob.withFlag(Flag.SPECIFIC)
1644 .withSelector(sbuilder.build())
1645 .withTreatment(tBuilder.build())
1646 .withPriority(getPriorityFromPrefix(address))
1647 .fromApp(srManager.appId)
1648 .makePermanent();
1649
1650 log.debug("{} blackhole forwarding objectives for dev: {}",
1651 install ? "Installing" : "Removing", deviceId);
1652 ObjectiveContext context = new DefaultObjectiveContext(
1653 (objective) -> log.debug("Forward for {} {}", deviceId,
1654 install ? "installed" : "removed"),
1655 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1656 install ? "install" : "remove", deviceId, error));
1657 if (install) {
1658 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1659 } else {
1660 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1661 }
1662 }
1663 } catch (DeviceConfigNotFoundException e) {
1664 log.info("Not populating blackhole for un-configured device {}", deviceId);
1665 }
1666
1667 }
1668
1669 /**
1670 * Populates a forwarding objective to send packets that miss other high
1671 * priority Bridging Table entries to a group that contains all ports of
1672 * its subnet.
1673 *
Charles Chanf4586112015-11-09 16:37:23 -08001674 * @param deviceId switch ID to set the rules
1675 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001676 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001677 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001678 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001679 });
1680 }
1681
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001682 /**
1683 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1684 * @param deviceId switch ID to set the rule
1685 * @param vlanId vlan ID to specify the subnet
1686 * @param install true to install the rule, false to revoke the rule
1687 */
1688 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1689 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1690
1691 if (nextId < 0) {
1692 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1693 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1694 return;
1695 }
1696
1697 // Driver should treat objective with MacAddress.NONE as the
1698 // subnet broadcast rule
1699 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1700 sbuilder.matchVlanId(vlanId);
1701 sbuilder.matchEthDst(MacAddress.NONE);
1702
1703 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1704 fob.withFlag(Flag.SPECIFIC)
1705 .withSelector(sbuilder.build())
1706 .nextStep(nextId)
1707 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1708 .fromApp(srManager.appId)
1709 .makePermanent();
1710 ObjectiveContext context = new DefaultObjectiveContext(
pierventrea3989be2021-01-08 16:43:17 +01001711 (objective) -> log.debug("Vlan broadcast rule for {} {}", vlanId, install ?
1712 "populated" : "removed"),
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001713 (objective, error) ->
pierventrea3989be2021-01-08 16:43:17 +01001714 log.warn("Failed to {} vlan broadcast rule for {}: {}", install ? "populate" : "remove",
1715 vlanId, error));
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001716
1717 if (install) {
1718 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1719 } else {
1720 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1721 }
1722 }
1723
Charles Chan82ab1932016-01-30 23:22:37 -08001724 private int getPriorityFromPrefix(IpPrefix prefix) {
1725 return (prefix.isIp4()) ?
1726 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1727 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001728 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001729
1730 /**
1731 * Update Forwarding objective for each host and IP address connected to given port.
1732 * And create corresponding Simple Next objective if it does not exist.
1733 * Applied only when populating Forwarding objective
1734 * @param deviceId switch ID to set the rule
1735 * @param portNumber port number
1736 * @param prefix IP prefix of the route
1737 * @param hostMac MAC address of the next hop
1738 * @param vlanId Vlan ID of the port
1739 * @param popVlan true to pop vlan tag in TrafficTreatment
1740 * @param install true to populate the forwarding objective, false to revoke
pierventrea3989be2021-01-08 16:43:17 +01001741 * @return a completable future that completes when the fwdobj completes. In case of removal,
1742 * the completable future completes when also the nextobj completes.
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001743 */
pierventrea3989be2021-01-08 16:43:17 +01001744 CompletableFuture<Objective> updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix,
1745 MacAddress hostMac, VlanId vlanId, boolean popVlan, boolean install) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001746 ForwardingObjective.Builder fob;
1747 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1748 MacAddress deviceMac;
1749 try {
1750 deviceMac = config.getDeviceMac(deviceId);
1751 } catch (DeviceConfigNotFoundException e) {
1752 log.warn(e.getMessage() + " Aborting updateFwdObj.");
pierventrea3989be2021-01-08 16:43:17 +01001753 return CompletableFuture.completedFuture(null);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001754 }
1755
1756 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1757 tbuilder.deferred()
1758 .setEthDst(hostMac)
1759 .setEthSrc(deviceMac)
1760 .setOutput(portNumber);
1761
1762 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1763
1764 if (!popVlan) {
pierventre50e1bb82020-12-14 19:31:03 +01001765 mbuilder.matchVlanId(vlanId);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001766 tbuilder.setVlanId(vlanId);
1767 } else {
1768 mbuilder.matchVlanId(vlanId);
pierventre50e1bb82020-12-14 19:31:03 +01001769 tbuilder.popVlan();
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001770 }
1771
1772 // if the objective is to revoke an existing rule, and for some reason
1773 // the next-objective does not exist, then a new one should not be created
1774 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1775 tbuilder.build(), mbuilder.build(), install);
pierventrea3989be2021-01-08 16:43:17 +01001776 CompletableFuture<Objective> future = new CompletableFuture<>();
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001777 if (portNextObjId == -1) {
1778 // Warning log will come from getPortNextObjective method
pierventrea3989be2021-01-08 16:43:17 +01001779 return CompletableFuture.completedFuture(null);
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001780 }
1781
1782 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1783 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1784 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1785
1786 ObjectiveContext context = new DefaultObjectiveContext(
pierventrea3989be2021-01-08 16:43:17 +01001787 (objective) -> {
1788 log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked");
1789 future.complete(objective);
1790 },
1791 (objective, error) -> {
1792 log.warn("Failed to {} IP rule for route {}: {}", install ? "install" : "revoke",
1793 prefix, error);
1794 future.complete(null);
1795 });
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001796 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1797
1798 if (!install) {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08001799 if (!srManager.getVlanPortMap(deviceId).containsKey(vlanId) ||
1800 !srManager.getVlanPortMap(deviceId).get(vlanId).contains(portNumber)) {
1801 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1802 if (grpHandler == null) {
1803 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1804 } else {
pierventrea3989be2021-01-08 16:43:17 +01001805 // Before moving forward we have to be sure flow has been removed;
1806 try {
1807 future.get();
1808 } catch (InterruptedException | ExecutionException e) {
1809 log.warn("Exception caught when executing IP rule removal for route {}", prefix);
1810 }
1811 // Remove L3UG for the given port and host and return the future
1812 // Flow future has been already consumed (normally or exceptionally)
1813 return grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08001814 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001815 }
1816 }
pierventrea3989be2021-01-08 16:43:17 +01001817 return future;
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001818 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001819
1820 /**
1821 * Checks if there is other enabled port within the given VLAN on the given device.
1822 *
1823 * @param deviceId device ID
1824 * @param vlanId VLAN ID
1825 * @return true if there is no more port enabled within the given VLAN on the given device
1826 */
1827 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1828 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1829 .filter(Port::isEnabled)
1830 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1831 .collect(Collectors.toSet());
1832
1833 return enabledPorts.stream().noneMatch(cp ->
1834 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001835 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
pieraac79e92019-10-04 15:40:34 +02001836 // Given vlanId is INTERNAL_VLAN or PSEUDOWIRE_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001837 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
pieraac79e92019-10-04 15:40:34 +02001838 (vlanId.equals(srManager.getDefaultInternalVlan()) || vlanId.equals(srManager.getPwTransportVlan()))) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001839 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1840 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1841 );
1842 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001843
1844 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001845 * Populates IP rules for a route that has double-tagged next hop.
1846 *
1847 * @param deviceId device ID of the device that next hop attaches to
1848 * @param prefix IP prefix of the route
1849 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001850 * @param innerVlan inner Vlan ID of the next hop
1851 * @param outerVlan outer Vlan ID of the next hop
1852 * @param outerTpid outer TPID of the next hop
1853 * @param outPort port where the next hop attaches to
1854 */
Charles Chan61c086d2019-07-26 17:46:15 -07001855 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001856 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1857 ForwardingObjective.Builder fwdBuilder;
1858 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1859 prefix, deviceId, outPort);
1860
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001861 try {
Charles Chan61c086d2019-07-26 17:46:15 -07001862 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1863 true, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001864 } catch (DeviceConfigNotFoundException e) {
1865 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1866 return;
1867 }
1868 if (fwdBuilder == null) {
1869 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1870 deviceId, prefix);
1871 return;
1872 }
1873
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001874 int nextId = fwdBuilder.add().nextId();
1875 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1876 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001877 }, (objective, error) ->
1878 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1879 );
1880 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1881 rulePopulationCounter.incrementAndGet();
1882 }
1883
1884 /**
1885 * Revokes IP rules for a route that has double-tagged next hop.
1886 *
1887 * @param deviceId device ID of the device that next hop attaches to
1888 * @param prefix IP prefix of the route
1889 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001890 * @param innerVlan inner Vlan ID of the next hop
1891 * @param outerVlan outer Vlan ID of the next hop
1892 * @param outerTpid outer TPID of the next hop
1893 * @param outPort port where the next hop attaches to
1894 */
1895 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -07001896 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1897 ForwardingObjective.Builder fwdBuilder;
1898 log.debug("Revoking direct routing entry for double-tagged host route {} at {}:{}",
1899 prefix, deviceId, outPort);
Charles Chan61c086d2019-07-26 17:46:15 -07001900 try {
1901 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1902 true, true);
1903 } catch (DeviceConfigNotFoundException e) {
1904 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001905 return;
1906 }
Charles Chan61c086d2019-07-26 17:46:15 -07001907 if (fwdBuilder == null) {
1908 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1909 deviceId, prefix);
1910 return;
1911 }
1912
1913 int nextId = fwdBuilder.remove().nextId();
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001914 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
Charles Chan61c086d2019-07-26 17:46:15 -07001915 log.debug("Direct routing rule for double-tagged host route {} revoked. nextId={}", prefix, nextId);
Charles Chan61c086d2019-07-26 17:46:15 -07001916 // Try to remove next objective as well
1917 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta;
1918 try {
1919 treatmentAndMeta = getTreatmentAndMeta(deviceId, hostMac, outerVlan, outPort, innerVlan, outerTpid);
1920 } catch (DeviceConfigNotFoundException e) {
1921 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
1922 return;
1923 }
Charles Chan61c086d2019-07-26 17:46:15 -07001924 if (treatmentAndMeta == null) {
1925 // Warning log will come from getTreatmentAndMeta method
1926 return;
1927 }
Charles Chan61c086d2019-07-26 17:46:15 -07001928 DefaultGroupHandler groupHandler = srManager.getGroupHandler(deviceId);
1929 if (groupHandler == null) {
1930 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: " +
1931 "group handler not found for {}", prefix, deviceId);
1932 return;
1933 }
1934 groupHandler.removeGroupFromPort(outPort, treatmentAndMeta.getLeft(), treatmentAndMeta.getRight());
1935
1936 }, (objective, error) ->
1937 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: {}", prefix, error)
1938 );
1939 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001940 }
1941
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001942 /**
1943 * Checks whether the specified port has IP configuration or not.
1944 *
1945 * @param cp ConnectPoint to check the existance of IP configuration
1946 * @return true if the port has IP configuration; false otherwise.
1947 */
1948 private boolean hasIPConfiguration(ConnectPoint cp) {
1949 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1950 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1951 }
Saurav Das9bf49582018-08-13 15:34:26 -07001952
1953 /**
1954 * Updates filtering rules for unconfigured ports on all devices for which
1955 * this controller instance is master.
1956 *
1957 * @param pushVlan true if the filtering rule requires a push vlan action
1958 * @param oldVlanId the vlanId to be removed
1959 * @param newVlanId the vlanId to be added
1960 */
1961 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1962 VlanId newVlanId) {
1963 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1964 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1965 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1966 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1967 && p.isEnabled()) {
1968 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1969 oldVlanId, false);
1970 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1971 newVlanId, true);
1972 }
1973 }
1974 }
1975 }
1976 }
1977
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001978 private boolean isIpv6Configured(DeviceId deviceId) {
1979 boolean isIpv6Configured;
1980 try {
1981 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1982 } catch (DeviceConfigNotFoundException e) {
1983 isIpv6Configured = false;
1984 }
1985 return isIpv6Configured;
1986 }
sangho80f11cb2015-04-01 13:05:26 -07001987}