blob: a6f6e326481d8608a87ee51e5444eee4d1c42c57 [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;
41import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070042import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070043import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sangho80f11cb2015-04-01 13:05:26 -070044import org.onosproject.net.DeviceId;
Saurav Das7c305372015-10-28 12:39:42 -070045import org.onosproject.net.Port;
sangho80f11cb2015-04-01 13:05:26 -070046import org.onosproject.net.PortNumber;
sangho80f11cb2015-04-01 13:05:26 -070047import org.onosproject.net.flow.DefaultTrafficSelector;
48import org.onosproject.net.flow.DefaultTrafficTreatment;
sangho80f11cb2015-04-01 13:05:26 -070049import org.onosproject.net.flow.TrafficSelector;
50import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070051import org.onosproject.net.flow.criteria.Criteria;
52import org.onosproject.net.flowobjective.DefaultFilteringObjective;
53import org.onosproject.net.flowobjective.DefaultForwardingObjective;
54import org.onosproject.net.flowobjective.FilteringObjective;
55import org.onosproject.net.flowobjective.ForwardingObjective;
56import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
Saurav Das9f1c42e2015-10-23 10:51:11 -070057import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
sangho80f11cb2015-04-01 13:05:26 -070058import org.slf4j.Logger;
59import org.slf4j.LoggerFactory;
60
61import java.util.ArrayList;
Pier Ventre229fd0b2016-10-31 16:49:19 -070062import java.util.Collection;
63import java.util.Collections;
Saurav Das261c3002017-06-13 15:35:54 -070064import java.util.HashMap;
Saurav Dasc28b3432015-10-30 17:45:38 -070065import java.util.HashSet;
sangho80f11cb2015-04-01 13:05:26 -070066import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070067import java.util.Map;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080068import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070069import java.util.Set;
Charles Chan12a8a842020-02-14 13:23:57 -080070import java.util.concurrent.CompletableFuture;
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;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070082import static org.onosproject.segmentrouting.SegmentRoutingService.DEFAULT_PRIORITY;
sangho80f11cb2015-04-01 13:05:26 -070083
Charles Chanb7f75ac2016-01-11 18:28:54 -080084/**
85 * Populator of segment routing flow rules.
86 */
sangho80f11cb2015-04-01 13:05:26 -070087public class RoutingRulePopulator {
Charles Chanef8d12e2017-12-05 21:07:38 -080088 private static final Logger log = LoggerFactory.getLogger(RoutingRulePopulator.class);
89
90 private static final int ARP_NDP_PRIORITY = 30000;
sangho80f11cb2015-04-01 13:05:26 -070091
sanghofb7c7292015-04-13 15:15:58 -070092 private AtomicLong rulePopulationCounter;
sangho9b169e32015-04-14 16:27:13 -070093 private SegmentRoutingManager srManager;
94 private DeviceConfiguration config;
psneha86e60d32019-03-26 06:31:41 -040095 private RouteSimplifierUtils routeSimplifierUtils;
Saurav Das9f1c42e2015-10-23 10:51:11 -070096
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -070097 // used for signalling the driver to remove vlan table and tmac entry also
98 private static final long CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES = 1;
99 private static final long DOUBLE_TAGGED_METADATA_MASK = 0xffffffffffffffffL;
100
sangho80f11cb2015-04-01 13:05:26 -0700101 /**
102 * Creates a RoutingRulePopulator object.
103 *
Thomas Vachuska8a075092015-04-15 18:20:08 -0700104 * @param srManager segment routing manager reference
sangho80f11cb2015-04-01 13:05:26 -0700105 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700106 RoutingRulePopulator(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700107 this.srManager = srManager;
sangho9b169e32015-04-14 16:27:13 -0700108 this.config = checkNotNull(srManager.deviceConfiguration);
sanghofb7c7292015-04-13 15:15:58 -0700109 this.rulePopulationCounter = new AtomicLong(0);
psneha86e60d32019-03-26 06:31:41 -0400110 this.routeSimplifierUtils = new RouteSimplifierUtils(srManager);
sanghofb7c7292015-04-13 15:15:58 -0700111 }
112
113 /**
114 * Resets the population counter.
115 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700116 void resetCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700117 rulePopulationCounter.set(0);
118 }
119
120 /**
121 * Returns the number of rules populated.
Thomas Vachuska7cfc6202015-04-30 18:13:25 -0700122 *
123 * @return number of rules
sanghofb7c7292015-04-13 15:15:58 -0700124 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700125 long getCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700126 return rulePopulationCounter.get();
sangho80f11cb2015-04-01 13:05:26 -0700127 }
128
129 /**
Charles Chand66d6712018-03-29 16:03:41 -0700130 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
131 * output to given port.
132 *
133 * @param deviceId device ID
134 * @param port port
135 * @param mac mac address
136 * @param vlanId VLAN ID
Charles Chan12a8a842020-02-14 13:23:57 -0800137 * @return future that carries the flow objective if succeeded, null if otherwise
Charles Chand66d6712018-03-29 16:03:41 -0700138 */
Charles Chan12a8a842020-02-14 13:23:57 -0800139 CompletableFuture<Objective> populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
Charles Chand66d6712018-03-29 16:03:41 -0700140 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
141 if (fob == null) {
142 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
Charles Chan12a8a842020-02-14 13:23:57 -0800143 return CompletableFuture.completedFuture(null);
Charles Chand66d6712018-03-29 16:03:41 -0700144 }
145
Charles Chan12a8a842020-02-14 13:23:57 -0800146 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chand66d6712018-03-29 16:03:41 -0700147 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800148 (objective) -> {
149 log.debug("Brigding rule for {}/{} populated", mac, vlanId);
150 future.complete(objective);
151 },
152 (objective, error) -> {
153 log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error);
154 future.complete(null);
155 });
Charles Chand66d6712018-03-29 16:03:41 -0700156 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
Charles Chan12a8a842020-02-14 13:23:57 -0800157 return future;
Charles Chand66d6712018-03-29 16:03:41 -0700158 }
159
160 /**
161 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
162 * output to given port.
163 *
164 * @param deviceId device ID
165 * @param port port
166 * @param mac mac address
167 * @param vlanId VLAN ID
Charles Chan12a8a842020-02-14 13:23:57 -0800168 * @return future that carries the flow objective if succeeded, null if otherwise
Charles Chand66d6712018-03-29 16:03:41 -0700169 */
Charles Chan12a8a842020-02-14 13:23:57 -0800170 CompletableFuture<Objective> revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
Charles Chand66d6712018-03-29 16:03:41 -0700171 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
172 if (fob == null) {
173 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
Charles Chan12a8a842020-02-14 13:23:57 -0800174 return CompletableFuture.completedFuture(null);
Charles Chand66d6712018-03-29 16:03:41 -0700175 }
176
Charles Chan12a8a842020-02-14 13:23:57 -0800177 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chand66d6712018-03-29 16:03:41 -0700178 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800179 (objective) -> {
180 log.debug("Brigding rule for {}/{} revoked", mac, vlanId);
181 future.complete(objective);
182 },
183 (objective, error) -> {
184 log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error);
185 future.complete(null);
186 });
Charles Chand66d6712018-03-29 16:03:41 -0700187 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
Charles Chan12a8a842020-02-14 13:23:57 -0800188 return future;
Charles Chand66d6712018-03-29 16:03:41 -0700189 }
190
191 /**
192 * Generates a forwarding objective builder for bridging rules.
193 * <p>
194 * The forwarding objective bridges packets destined to a given MAC to
195 * given port on given device.
196 *
197 * @param deviceId Device that host attaches to
198 * @param mac MAC address of the host
199 * @param hostVlanId VLAN ID of the host
200 * @param outport Port that host attaches to
201 * @param revoke true if forwarding objective is meant to revoke forwarding rule
202 * @return Forwarding objective builder
203 */
204 private ForwardingObjective.Builder bridgingFwdObjBuilder(
205 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
206 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan098ca202018-05-01 11:50:20 -0700207 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
208 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
209 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chand66d6712018-03-29 16:03:41 -0700210
211 // Create host selector
212 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
213 sbuilder.matchEthDst(mac);
214
215 // Create host treatment
216 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
217 tbuilder.immediate().setOutput(outport);
218
219 // Create host meta
220 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
221
222 // Adjust the selector, treatment and meta according to VLAN configuration
223 if (taggedVlans.contains(hostVlanId)) {
224 sbuilder.matchVlanId(hostVlanId);
225 mbuilder.matchVlanId(hostVlanId);
226 } else if (hostVlanId.equals(VlanId.NONE)) {
227 if (untaggedVlan != null) {
228 sbuilder.matchVlanId(untaggedVlan);
229 mbuilder.matchVlanId(untaggedVlan);
230 tbuilder.immediate().popVlan();
231 } else if (nativeVlan != null) {
232 sbuilder.matchVlanId(nativeVlan);
233 mbuilder.matchVlanId(nativeVlan);
234 tbuilder.immediate().popVlan();
235 } else {
236 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
237 "vlan config", mac, hostVlanId, connectPoint);
238 return null;
239 }
240 } else {
241 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
242 mac, hostVlanId, connectPoint);
243 return null;
244 }
245
246 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
247 // If the objective is to revoke an existing rule, and for some reason
248 // the next-objective does not exist, then a new one should not be created
249 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
250 tbuilder.build(), mbuilder.build(), !revoke);
251 if (portNextObjId == -1) {
252 // Warning log will come from getPortNextObjective method
253 return null;
254 }
255
256 return DefaultForwardingObjective.builder()
257 .withFlag(ForwardingObjective.Flag.SPECIFIC)
258 .withSelector(sbuilder.build())
259 .nextStep(portNextObjId)
260 .withPriority(100)
261 .fromApp(srManager.appId)
262 .makePermanent();
263 }
264
265 /**
266 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
267 * and hostMAC connected to given port, and output to given port only when
268 * vlan information is valid.
269 *
270 * @param deviceId device ID that host attaches to
271 * @param portNum port number that host attaches to
272 * @param hostMac mac address of the host connected to the switch port
273 * @param vlanId Vlan ID configured on the switch port
274 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
275 * @param install true to populate the objective, false to revoke
276 */
277 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
278 // revokeBridging and bridgingFwdObjBuilder.
279 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
280 VlanId vlanId, boolean popVlan, boolean install) {
281 // Create host selector
282 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
283 sbuilder.matchEthDst(hostMac);
284
285 // Create host meta
286 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
287
288 sbuilder.matchVlanId(vlanId);
289 mbuilder.matchVlanId(vlanId);
290
291 // Create host treatment
292 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
293 tbuilder.immediate().setOutput(portNum);
294
295 if (popVlan) {
296 tbuilder.immediate().popVlan();
297 }
298
299 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
300 tbuilder.build(), mbuilder.build(), install);
301 if (portNextObjId != -1) {
302 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
303 .withFlag(ForwardingObjective.Flag.SPECIFIC)
304 .withSelector(sbuilder.build())
305 .nextStep(portNextObjId)
306 .withPriority(100)
307 .fromApp(srManager.appId)
308 .makePermanent();
309
310 ObjectiveContext context = new DefaultObjectiveContext(
311 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
312 install ? "populated" : "revoked"),
313 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
314 install ? "populate" : "revoke", hostMac, vlanId, error));
315 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
316 } else {
317 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
318 }
319 }
320
321 /**
322 * Populates IP rules for a route that has direct connection to the switch.
323 * This method should not be invoked directly without going through DefaultRoutingHandler.
sangho80f11cb2015-04-01 13:05:26 -0700324 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700325 * @param deviceId device ID of the device that next hop attaches to
326 * @param prefix IP prefix of the route
327 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800328 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700329 * @param outPort port where the next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000330 * @param directHost host is of type direct or indirect
Charles Chan12a8a842020-02-14 13:23:57 -0800331 * @return future that carries the flow objective if succeeded, null if otherwise
sangho80f11cb2015-04-01 13:05:26 -0700332 */
Charles Chan12a8a842020-02-14 13:23:57 -0800333 CompletableFuture<Objective> populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000334 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Saurav Das261c3002017-06-13 15:35:54 -0700335 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chanddac7fd2016-10-27 14:19:48 -0700336 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800337 ForwardingObjective.Builder fwdBuilder;
Charles Chan319d1a22015-11-03 10:42:14 -0800338 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700339 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -0700340 hostVlanId, outPort, null, null, directHost, false);
Charles Chan319d1a22015-11-03 10:42:14 -0800341 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -0700342 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan12a8a842020-02-14 13:23:57 -0800343 return CompletableFuture.completedFuture(null);
Charles Chan319d1a22015-11-03 10:42:14 -0800344 }
Saurav Das07c74602016-04-27 18:35:50 -0700345 if (fwdBuilder == null) {
Saurav Das368cf212017-03-15 15:15:14 -0700346 log.warn("Aborting host routing table entry due "
Charles Chanddac7fd2016-10-27 14:19:48 -0700347 + "to error for dev:{} route:{}", deviceId, prefix);
Charles Chan12a8a842020-02-14 13:23:57 -0800348 return CompletableFuture.completedFuture(null);
Saurav Das07c74602016-04-27 18:35:50 -0700349 }
Charles Chan910be6a2017-08-23 14:46:43 -0700350
351 int nextId = fwdBuilder.add().nextId();
Charles Chan12a8a842020-02-14 13:23:57 -0800352 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chan1eaf4802016-04-18 13:44:03 -0700353 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800354 (objective) -> {
355 log.debug("Direct routing rule for route {} populated. nextId={}", prefix, nextId);
356 future.complete(objective);
357 },
358 (objective, error) -> {
359 log.warn("Failed to populate direct routing rule for route {}: {}", prefix, error);
360 future.complete(null);
361 });
Charles Chan1eaf4802016-04-18 13:44:03 -0700362 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chanf4586112015-11-09 16:37:23 -0800363 rulePopulationCounter.incrementAndGet();
Charles Chan12a8a842020-02-14 13:23:57 -0800364 return future;
Charles Chanf4586112015-11-09 16:37:23 -0800365 }
366
Charles Chanb7f75ac2016-01-11 18:28:54 -0800367 /**
Charles Chanddac7fd2016-10-27 14:19:48 -0700368 * Removes IP rules for a route when the next hop is gone.
Charles Chand66d6712018-03-29 16:03:41 -0700369 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800370 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700371 * @param deviceId device ID of the device that next hop attaches to
372 * @param prefix IP prefix of the route
373 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800374 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700375 * @param outPort port that next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000376 * @param directHost host is of type direct or indirect
Charles Chan12a8a842020-02-14 13:23:57 -0800377 * @return future that carries the flow objective if succeeded, null if otherwise
Charles Chanb7f75ac2016-01-11 18:28:54 -0800378 */
Charles Chan12a8a842020-02-14 13:23:57 -0800379 CompletableFuture<Objective> revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000380 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chanddac7fd2016-10-27 14:19:48 -0700381 log.debug("Revoke IP table entry for route {} at {}:{}",
382 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800383 ForwardingObjective.Builder fwdBuilder;
384 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700385 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -0700386 hostVlanId, outPort, null, null, directHost, true);
Charles Chanf4586112015-11-09 16:37:23 -0800387 } catch (DeviceConfigNotFoundException e) {
388 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
Charles Chan12a8a842020-02-14 13:23:57 -0800389 return CompletableFuture.completedFuture(null);
Charles Chanf4586112015-11-09 16:37:23 -0800390 }
Charles Chanea702b12016-11-30 11:55:05 -0800391 if (fwdBuilder == null) {
392 log.warn("Aborting host routing table entries due "
393 + "to error for dev:{} route:{}", deviceId, prefix);
Charles Chan12a8a842020-02-14 13:23:57 -0800394 return CompletableFuture.completedFuture(null);
Charles Chanea702b12016-11-30 11:55:05 -0800395 }
Charles Chan12a8a842020-02-14 13:23:57 -0800396
397 CompletableFuture<Objective> future = new CompletableFuture<>();
Charles Chan1eaf4802016-04-18 13:44:03 -0700398 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan12a8a842020-02-14 13:23:57 -0800399 (objective) -> {
400 log.debug("IP rule for route {} revoked", prefix);
401 future.complete(objective);
402 },
403 (objective, error) -> {
404 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error);
405 future.complete(null);
406 });
Charles Chan1eaf4802016-04-18 13:44:03 -0700407 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chan12a8a842020-02-14 13:23:57 -0800408 return future;
Charles Chanf4586112015-11-09 16:37:23 -0800409 }
410
Charles Chanddac7fd2016-10-27 14:19:48 -0700411 /**
Charles Chan18fa4252017-02-08 16:10:40 -0800412 * Returns a forwarding objective builder for routing rules.
413 * <p>
414 * The forwarding objective routes packets destined to a given prefix to
415 * given port on given device with given destination MAC.
Charles Chanddac7fd2016-10-27 14:19:48 -0700416 *
417 * @param deviceId device ID
418 * @param prefix prefix that need to be routed
419 * @param hostMac MAC address of the nexthop
Charles Chan90772a72017-02-08 15:52:08 -0800420 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700421 * @param outPort port where the nexthop attaches to
Saurav Das2cb38292017-03-29 19:09:17 -0700422 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000423 * @param directHost host is direct or indirect
Charles Chanddac7fd2016-10-27 14:19:48 -0700424 * @return forwarding objective builder
425 * @throws DeviceConfigNotFoundException if given device is not configured
426 */
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000427
Charles Chan61c086d2019-07-26 17:46:15 -0700428 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700429 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700430 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
Charles Chan61c086d2019-07-26 17:46:15 -0700431 VlanId innerVlan, EthType outerTpid,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000432 boolean directHost, boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800433 throws DeviceConfigNotFoundException {
Charles Chan61c086d2019-07-26 17:46:15 -0700434 int nextObjId;
435 if (directHost) {
436 // if the objective is to revoke an existing rule, and for some reason
437 // the next-objective does not exist, then a new one should not be created
438 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta =
439 getTreatmentAndMeta(deviceId, hostMac, hostVlanId, outPort, innerVlan, outerTpid);
440 if (treatmentAndMeta == null) {
441 // Warning log will come from getTreatmentAndMeta method
442 return null;
443 }
444 nextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
445 treatmentAndMeta.getLeft(), treatmentAndMeta.getRight(), !revoke);
446 } else {
447 // if the objective is to revoke an existing rule, and for some reason
448 // the next-objective does not exist, then a new one should not be created
449 nextObjId = srManager.getMacVlanNextObjectiveId(deviceId, hostMac, hostVlanId,
450 outPort, !revoke);
451 }
452 if (nextObjId == -1) {
453 // Warning log will come from getMacVlanNextObjective method
454 return null;
455 }
456
457 return DefaultForwardingObjective.builder()
458 .withSelector(buildIpSelectorFromIpPrefix(prefix).build())
459 .nextStep(nextObjId)
460 .fromApp(srManager.appId).makePermanent()
461 .withPriority(getPriorityFromPrefix(prefix))
462 .withFlag(ForwardingObjective.Flag.SPECIFIC);
463 }
464
465 private ImmutablePair<TrafficTreatment, TrafficSelector> getTreatmentAndMeta(
466 DeviceId deviceId, MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
467 VlanId innerVlan, EthType outerTpid)
468 throws DeviceConfigNotFoundException {
469 MacAddress routerMac;
470 routerMac = config.getDeviceMac(deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800471
Charles Chan90772a72017-02-08 15:52:08 -0800472 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700473 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
474 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
475 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700476
Charles Chan90772a72017-02-08 15:52:08 -0800477 // Create route treatment
Charles Chanddac7fd2016-10-27 14:19:48 -0700478 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho27462c62015-05-14 00:39:53 -0700479 tbuilder.deferred()
480 .setEthDst(hostMac)
Charles Chan61c086d2019-07-26 17:46:15 -0700481 .setEthSrc(routerMac)
sangho80f11cb2015-04-01 13:05:26 -0700482 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800483
Charles Chan90772a72017-02-08 15:52:08 -0800484 // Create route meta
485 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800486
Charles Chan61c086d2019-07-26 17:46:15 -0700487 // Adjust treatment and meta according to VLAN configuration
Charles Chan90772a72017-02-08 15:52:08 -0800488 if (taggedVlans.contains(hostVlanId)) {
489 tbuilder.setVlanId(hostVlanId);
490 } else if (hostVlanId.equals(VlanId.NONE)) {
491 if (untaggedVlan != null) {
492 mbuilder.matchVlanId(untaggedVlan);
493 } else if (nativeVlan != null) {
494 mbuilder.matchVlanId(nativeVlan);
495 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700496 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
497 hostMac, hostVlanId, connectPoint);
498 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800499 }
500 } else {
Charles Chan61c086d2019-07-26 17:46:15 -0700501 // Double tagged hosts
502 if (innerVlan == null || outerTpid == null) {
503 log.warn("Failed to construct NextObj for double tagged hosts {}/{}. {} {}",
504 hostMac, hostVlanId,
505 (innerVlan == null) ? "innerVlan = null." : "",
506 (outerTpid == null) ? "outerTpid = null." : "");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700507 return null;
508 }
Charles Chan61c086d2019-07-26 17:46:15 -0700509 tbuilder.setVlanId(innerVlan);
510 tbuilder.pushVlan(outerTpid);
511 tbuilder.setVlanId(hostVlanId);
512 mbuilder.matchVlanId(VlanId.ANY);
Saurav Das07c74602016-04-27 18:35:50 -0700513 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000514
Charles Chan61c086d2019-07-26 17:46:15 -0700515 return ImmutablePair.of(tbuilder.build(), mbuilder.build());
sangho80f11cb2015-04-01 13:05:26 -0700516 }
517
518 /**
Saurav Das261c3002017-06-13 15:35:54 -0700519 * Populates IP flow rules for all the given prefixes reachable from the
520 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700521 *
Saurav Das261c3002017-06-13 15:35:54 -0700522 * @param targetSw switch where rules are to be programmed
523 * @param subnets subnets/prefixes being added
524 * @param destSw1 destination switch where the prefixes are reachable
525 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
526 * Should be null if there is no paired destination switch (by config)
527 * or if the given prefixes are reachable only via destSw1
528 * @param nextHops a map containing a set of next-hops for each destination switch.
529 * If destSw2 is not null, then this map must contain an
530 * entry for destSw2 with its next-hops from the targetSw
531 * (although the next-hop set may be empty in certain scenarios).
532 * If destSw2 is null, there should not be an entry in this
533 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700534 * @return true if all rules are set successfully, false otherwise
535 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700536 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700537 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
psneha86e60d32019-03-26 06:31:41 -0400538 // Get pair device of the target switch
539 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
540 // Route simplification will be off in case of the nexthop location at target switch is down
541 // (routing through spine case)
542 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
piera9941192019-04-24 16:12:47 +0200543 // Iterates over the routes. Checking:
psneha86e60d32019-03-26 06:31:41 -0400544 // If route simplification is enabled
545 // If the target device is another leaf in the network
546 if (srManager.routeSimplification && !routeSimplOff) {
piera9941192019-04-24 16:12:47 +0200547 Set<IpPrefix> subnetsToBePopulated = Sets.newHashSet();
psneha86e60d32019-03-26 06:31:41 -0400548 for (IpPrefix subnet : subnets) {
549 // Skip route programming on the target device
550 // If route simplification applies
551 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
552 // XXX route simplification assumes that source of the traffic
553 // towards the nexthops are co-located with the nexthops. In different
554 // scenarios will not work properly.
555 continue;
556 }
557 // populate the route in the remaning scenarios
piera9941192019-04-24 16:12:47 +0200558 subnetsToBePopulated.add(subnet);
psneha86e60d32019-03-26 06:31:41 -0400559 }
piera9941192019-04-24 16:12:47 +0200560 subnets = subnetsToBePopulated;
sangho80f11cb2015-04-01 13:05:26 -0700561 }
piera9941192019-04-24 16:12:47 +0200562 // populate the remaining routes in the target switch
563 return populateIpRulesForRouter(targetSw, subnets, destSw1, destSw2, nextHops);
Charles Chanc22cef32016-04-29 14:38:22 -0700564 }
sangho80f11cb2015-04-01 13:05:26 -0700565
Charles Chanc22cef32016-04-29 14:38:22 -0700566 /**
Charles Chand66d6712018-03-29 16:03:41 -0700567 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700568 *
Charles Chand66d6712018-03-29 16:03:41 -0700569 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700570 * @param subnets subnet being removed
571 * @return true if all rules are removed successfully, false otherwise
572 */
Charles Chand66d6712018-03-29 16:03:41 -0700573 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700574 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700575 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700576 return false;
577 }
578 }
sangho80f11cb2015-04-01 13:05:26 -0700579 return true;
580 }
581
582 /**
piera9941192019-04-24 16:12:47 +0200583 * Populates IP flow rules for a set of IP prefix in the target device.
584 * The prefix are reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700585 *
Saurav Das261c3002017-06-13 15:35:54 -0700586 * @param targetSw target device ID to set the rules
piera9941192019-04-24 16:12:47 +0200587 * @param subnets the set of IP prefix
Saurav Das261c3002017-06-13 15:35:54 -0700588 * @param destSw1 destination switch where the prefixes are reachable
589 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
590 * Should be null if there is no paired destination switch (by config)
591 * or if the given prefixes are reachable only via destSw1
592 * @param nextHops map of destination switches and their next-hops.
593 * Should only contain destination switches that are
594 * actually meant to be routed to. If destSw2 is null, there
595 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700596 * @return true if all rules are set successfully, false otherwise
597 */
piera9941192019-04-24 16:12:47 +0200598 private boolean populateIpRulesForRouter(DeviceId targetSw,
599 Set<IpPrefix> subnets,
600 DeviceId destSw1, DeviceId destSw2,
601 Map<DeviceId, Set<DeviceId>> nextHops) {
602 // pre-compute the needed information
603 int segmentIdIPv41, segmentIdIPv42 = -1;
604 int segmentIdIPv61, segmentIdIPv62 = -1;
605 TrafficTreatment treatment = null;
606 DestinationSet dsIPv4, dsIPv6;
607 TrafficSelector metaIpv4Selector, metaIpv6Selector = null;
608 int nextIdIPv4, nextIdIPv6, nextId;
609 TrafficSelector selector;
610 // start with MPLS SIDs
Charles Chan319d1a22015-11-03 10:42:14 -0800611 try {
piera9941192019-04-24 16:12:47 +0200612 segmentIdIPv41 = config.getIPv4SegmentId(destSw1);
613 segmentIdIPv61 = config.getIPv6SegmentId(destSw1);
614 if (destSw2 != null) {
615 segmentIdIPv42 = config.getIPv4SegmentId(destSw2);
616 segmentIdIPv62 = config.getIPv6SegmentId(destSw2);
Pier Ventreadb4ae62016-11-23 09:57:42 -0800617 }
Charles Chan319d1a22015-11-03 10:42:14 -0800618 } catch (DeviceConfigNotFoundException e) {
619 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
620 return false;
621 }
piera9941192019-04-24 16:12:47 +0200622 // build the IPv4 and IPv6 destination set
Saurav Das261c3002017-06-13 15:35:54 -0700623 if (destSw2 == null) {
624 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800625 // If the next hop is the same as the final destination, then MPLS
626 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700627 Set<DeviceId> nhd1 = nextHops.get(destSw1);
628 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
piera9941192019-04-24 16:12:47 +0200629 dsIPv4 = DestinationSet.createTypePushNone(destSw1);
630 dsIPv6 = DestinationSet.createTypePushNone(destSw1);
631 treatment = DefaultTrafficTreatment.builder()
632 .immediate()
633 .decNwTtl()
634 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700635 } else {
piera9941192019-04-24 16:12:47 +0200636 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1);
637 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700638 }
639 } else {
640 // dst pair - IP rules for dst-pairs are always from other edge nodes
641 // the destination set needs to have both destinations, even if there
642 // are no next hops to one of them
piera9941192019-04-24 16:12:47 +0200643 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1, segmentIdIPv42, destSw2);
644 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1, segmentIdIPv62, destSw2);
sangho80f11cb2015-04-01 13:05:26 -0700645 }
646
Saurav Das4c35fc42015-11-20 15:27:53 -0800647 // setup metadata to pass to nextObjective - indicate the vlan on egress
648 // if needed by the switch pipeline. Since neighbor sets are always to
649 // other neighboring routers, there is no subnet assigned on those ports.
piera9941192019-04-24 16:12:47 +0200650 metaIpv4Selector = buildIpv4Selector()
651 .matchVlanId(srManager.getDefaultInternalVlan())
652 .build();
653 metaIpv6Selector = buildIpv6Selector()
654 .matchVlanId(srManager.getDefaultInternalVlan())
655 .build();
656 // get the group handler of the target switch
Saurav Das261c3002017-06-13 15:35:54 -0700657 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700658 if (grpHandler == null) {
659 log.warn("populateIPRuleForRouter: groupHandler for device {} "
piera9941192019-04-24 16:12:47 +0200660 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700661 return false;
662 }
piera9941192019-04-24 16:12:47 +0200663 // get next id
664 nextIdIPv4 = grpHandler.getNextObjectiveId(dsIPv4, nextHops, metaIpv4Selector, false);
665 if (nextIdIPv4 <= 0) {
666 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv4);
sangho2165d222015-05-01 09:38:25 -0700667 return false;
668 }
piera9941192019-04-24 16:12:47 +0200669 nextIdIPv6 = grpHandler.getNextObjectiveId(dsIPv6, nextHops, metaIpv6Selector, false);
670 if (nextIdIPv6 <= 0) {
671 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv6);
672 return false;
Charles Chanf4586112015-11-09 16:37:23 -0800673 }
piera9941192019-04-24 16:12:47 +0200674 // build all the flow rules and send to the device
675 for (IpPrefix subnet : subnets) {
676 selector = buildIpSelectorFromIpPrefix(subnet).build();
677 if (subnet.isIp4()) {
678 nextId = nextIdIPv4;
679 } else {
680 nextId = nextIdIPv6;
681 }
682 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
683 .builder()
684 .fromApp(srManager.appId)
685 .makePermanent()
686 .nextStep(nextId)
687 .withSelector(selector)
688 .withPriority(getPriorityFromPrefix(subnet))
689 .withFlag(ForwardingObjective.Flag.SPECIFIC);
690 if (treatment != null) {
691 fwdBuilder.withTreatment(treatment);
692 }
693 log.debug("Installing {} forwarding objective for router IP/subnet {} "
694 + "in switch {} with nextId: {}", subnet.isIp4() ? "IPv4" : "IPv6",
695 subnet, targetSw, nextId);
696 ObjectiveContext context = new DefaultObjectiveContext(
697 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
698 subnet, targetSw),
699 (objective, error) -> log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
700 subnet, error, targetSw));
701 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
702 }
703 rulePopulationCounter.addAndGet(subnets.size());
sangho80f11cb2015-04-01 13:05:26 -0700704 return true;
705 }
706
sangho80f11cb2015-04-01 13:05:26 -0700707 /**
Charles Chand66d6712018-03-29 16:03:41 -0700708 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700709 *
Charles Chand66d6712018-03-29 16:03:41 -0700710 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700711 * @param ipPrefix the IP address of the destination router
712 * @return true if all rules are removed successfully, false otherwise
713 */
Charles Chand66d6712018-03-29 16:03:41 -0700714 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800715 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700716 TrafficSelector selector = sbuilder.build();
717 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
718
719 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
720 .builder()
721 .fromApp(srManager.appId)
722 .makePermanent()
723 .withSelector(selector)
724 .withTreatment(dummyTreatment)
725 .withPriority(getPriorityFromPrefix(ipPrefix))
726 .withFlag(ForwardingObjective.Flag.SPECIFIC);
727
Charles Chand66d6712018-03-29 16:03:41 -0700728 ObjectiveContext context = new DefaultObjectiveContext(
729 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
730 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
731 ipPrefix, targetSw, error));
732 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700733
734 return true;
735 }
736
737 /**
Saurav Das97241862018-02-14 14:14:54 -0800738 * Populates MPLS flow rules in the target device to point towards the
739 * destination device.
740 *
741 * @param targetSwId target device ID of the switch to set the rules
742 * @param destSwId destination switch device ID
743 * @param nextHops next hops switch ID list
744 * @param routerIp the router ip of the destination switch
745 * @return true if all rules are set successfully, false otherwise
746 */
747 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
748 Set<DeviceId> nextHops, IpAddress routerIp) {
749 int segmentId;
750 try {
751 if (routerIp.isIp4()) {
752 segmentId = config.getIPv4SegmentId(destSwId);
753 } else {
754 segmentId = config.getIPv6SegmentId(destSwId);
755 }
756 } catch (DeviceConfigNotFoundException e) {
757 log.warn(e.getMessage() + " Aborting populateMplsRule.");
758 return false;
759 }
760
761 List<ForwardingObjective> fwdObjs = new ArrayList<>();
762 Collection<ForwardingObjective> fwdObjsMpls;
763 // Generates the transit rules used by the standard "routing".
764 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
765 routerIp, true);
766 if (fwdObjsMpls.isEmpty()) {
767 return false;
768 }
769 fwdObjs.addAll(fwdObjsMpls);
770
771 // Generates the transit rules used by the MPLS Pwaas.
772 int pwSrLabel;
773 try {
774 pwSrLabel = config.getPWRoutingLabel(destSwId);
775 } catch (DeviceConfigNotFoundException e) {
776 log.warn(e.getMessage()
777 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
778 return false;
779 }
780 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
781 routerIp, false);
782 if (fwdObjsMpls.isEmpty()) {
783 return false;
784 }
785 fwdObjs.addAll(fwdObjsMpls);
786
787 for (ForwardingObjective fwdObj : fwdObjs) {
788 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
789 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
790 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
791 rulePopulationCounter.incrementAndGet();
792 }
793
794 return true;
795 }
796
797 /**
798 * Differentiates between popping and swapping labels when building an MPLS
799 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700800 *
801 * @param targetSwId the target sw
802 * @param destSwId the destination sw
803 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800804 * @param segmentId the segmentId to match representing the destination
805 * switch
806 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700807 * @return a collection of fwdobjective
808 */
Saurav Das261c3002017-06-13 15:35:54 -0700809 private Collection<ForwardingObjective> handleMpls(
810 DeviceId targetSwId,
811 DeviceId destSwId,
812 Set<DeviceId> nextHops,
813 int segmentId,
814 IpAddress routerIp,
815 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700816
817 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
818 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800819 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700820 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
821 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
822 sbuilder.matchMplsBos(isMplsBos);
823 TrafficSelector selector = sbuilder.build();
824
825 // setup metadata to pass to nextObjective - indicate the vlan on egress
826 // if needed by the switch pipeline. Since mpls next-hops are always to
827 // other neighboring routers, there is no subnet assigned on those ports.
828 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700829 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre229fd0b2016-10-31 16:49:19 -0700830
831 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
832 // If the next hop is the destination router for the segment, do pop
833 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700834 + "label {} in switch {} with pop to next-hops {}",
835 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700836 ForwardingObjective.Builder fwdObjNoBosBuilder =
837 getMplsForwardingObjective(targetSwId,
838 nextHops,
839 true,
840 isMplsBos,
841 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700842 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800843 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700844 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700845 // Error case, we cannot handle, exit.
846 if (fwdObjNoBosBuilder == null) {
847 return Collections.emptyList();
848 }
849 fwdObjBuilders.add(fwdObjNoBosBuilder);
850
851 } else {
Saurav Das97241862018-02-14 14:14:54 -0800852 // next hop is not destination, irrespective of the number of next
853 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700854 log.debug("Installing MPLS forwarding objective for "
855 + "label {} in switch {} without pop to next-hops {}",
856 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700857 ForwardingObjective.Builder fwdObjNoBosBuilder =
858 getMplsForwardingObjective(targetSwId,
859 nextHops,
860 false,
861 isMplsBos,
862 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700863 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800864 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700865 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700866 // Error case, we cannot handle, exit.
867 if (fwdObjNoBosBuilder == null) {
868 return Collections.emptyList();
869 }
870 fwdObjBuilders.add(fwdObjNoBosBuilder);
871
872 }
873
874 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
875 // We add the final property to the fwdObjs.
876 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700877 ((Builder) ((Builder) fwdObjBuilder
878 .fromApp(srManager.appId)
879 .makePermanent())
880 .withSelector(selector)
881 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
882 .withFlag(ForwardingObjective.Flag.SPECIFIC);
883
884 ObjectiveContext context = new DefaultObjectiveContext(
885 (objective) ->
886 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
887 objective.id(), segmentId, targetSwId),
888 (objective, error) ->
889 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
890 objective.id(), segmentId, error, targetSwId));
891
892 ForwardingObjective fob = fwdObjBuilder.add(context);
893 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700894 }
895
896 return fwdObjs;
897 }
898
899 /**
Saurav Das97241862018-02-14 14:14:54 -0800900 * Returns a Forwarding Objective builder for the MPLS rule that references
901 * the desired Next Objective. Creates a DestinationSet that allows the
902 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700903 *
Saurav Das97241862018-02-14 14:14:54 -0800904 * @param targetSw the target sw
905 * @param nextHops the set of next hops
906 * @param phpRequired true if penultimate-hop-popping is required
907 * @param isBos true if matched label is bottom-of-stack
908 * @param meta metadata for creating next objective
909 * @param routerIp the router ip representing the destination switch
910 * @param destSw the destination sw
911 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700912 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800913 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700914 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800915 Set<DeviceId> nextHops,
916 boolean phpRequired,
917 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800918 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700919 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800920 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700921 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800922
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700923 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
924 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700925
926 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800927 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700928 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800929 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700930 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800931 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700932 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700933 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700934 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800935 if (routerIp.isIp4()) {
936 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
937 } else {
938 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
939 }
940 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800941 // standard case -> BoS == True; pop results in IP packet and forwarding
942 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700943 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700944 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800945 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
946 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800947 // double-label case -> BoS == False, pop results in MPLS packet
948 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700949 ds = DestinationSet.createTypePopNotBos(destSw);
950 if (!srManager.getMplsEcmp()) {
951 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800952 }
sangho80f11cb2015-04-01 13:05:26 -0700953 }
954 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800955 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800956 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700957 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800958 // swap results in MPLS packet with same BoS bit regardless of bit value
959 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700960 // differentiate here between swap with not bos or swap with bos
961 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
962 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
963 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800964 simple = true;
965 }
sangho80f11cb2015-04-01 13:05:26 -0700966 }
967
Saurav Das4c35fc42015-11-20 15:27:53 -0800968 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800969 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
970 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700971 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
972 if (gh == null) {
973 log.warn("getNextObjectiveId query - groupHandler for device {} "
974 + "not found", targetSw);
975 return null;
976 }
Saurav Das97241862018-02-14 14:14:54 -0800977
Saurav Das261c3002017-06-13 15:35:54 -0700978 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
979 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800980 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800981 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800982 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800983 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700984 } else {
Saurav Das97241862018-02-14 14:14:54 -0800985 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
986 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -0700987 }
988
Saurav Das4c35fc42015-11-20 15:27:53 -0800989 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700990 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -0700991 }
992
993 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -0700994 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -0700995 * dstMac corresponding to the router's MAC address. For those pipelines
996 * that need to internally assign vlans to untagged packets, this method
997 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -0700998 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -0800999 * Note that the vlan assignment and filter programming should only be done by
1000 * the master for a switch. This method is typically called at deviceAdd and
1001 * programs filters only for the enabled ports of the device. For port-updates,
1002 * that enable/disable ports after device add, singlePortFilter methods should
1003 * be called.
sangho80f11cb2015-04-01 13:05:26 -07001004 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001005 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -08001006 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -07001007 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001008 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -07001009 log.debug("Installing per-port filtering objective for untagged "
1010 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -08001011
Saurav Das07c74602016-04-27 18:35:50 -07001012 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -08001013 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -07001014 log.warn("Device {} ports not available. Unable to add MacVlan filters",
1015 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -08001016 return null;
Saurav Das07c74602016-04-27 18:35:50 -07001017 }
Saurav Dasf9332192017-02-18 14:05:44 -08001018 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -07001019 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -07001020 if (!port.isEnabled()) {
1021 disabledPorts++;
1022 continue;
1023 }
Charles Chan43be46b2017-02-26 22:59:35 -08001024 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001025 filteredPorts++;
1026 } else {
1027 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -07001028 }
Saurav Das7c305372015-10-28 12:39:42 -07001029 }
Charles Chan077314e2017-06-22 14:27:17 -07001030 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -08001031 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan9d2dd552018-06-19 20:56:33 -07001032 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Dasf9332192017-02-18 14:05:44 -08001033 }
1034
1035 /**
Charles Chan43be46b2017-02-26 22:59:35 -08001036 * Creates or removes filtering objectives for a single port. Should only be
1037 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -08001038 *
1039 * @param deviceId device identifier
1040 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -08001041 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -08001042 * @return true if no errors occurred during the build of the filtering objective
1043 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001044 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -08001045 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -07001046 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
1047 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
1048 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -08001049
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001050 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -08001051 if (taggedVlans.size() != 0) {
1052 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -07001053 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan43be46b2017-02-26 22:59:35 -08001054 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan90772a72017-02-08 15:52:08 -08001055 return false;
1056 }
1057 if (nativeVlan != null) {
1058 // Filter for native vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001059 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001060 return false;
1061 }
1062 }
1063 } else if (untaggedVlan != null) {
1064 // Filter for untagged vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001065 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001066 return false;
1067 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001068 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001069 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das9bf49582018-08-13 15:34:26 -07001070 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1071 srManager.getDefaultInternalVlan(),
1072 install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001073 return false;
1074 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001075 // Filter for receiveing pseudowire traffic
Saurav Das9bf49582018-08-13 15:34:26 -07001076 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1077 srManager.getPwTransportVlan(),
1078 install)) {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001079 return false;
1080 }
Charles Chan90772a72017-02-08 15:52:08 -08001081 }
1082 return true;
1083 }
1084
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001085 /**
1086 * Updates filtering objectives for a single port. Should only be called by
1087 * the master for a switch
1088 * @param deviceId device identifier
1089 * @param portNum port identifier for port to be filtered
1090 * @param pushVlan true to push vlan, false otherwise
1091 * @param vlanId vlan identifier
1092 * @param install true to install the filtering objective, false to remove
1093 */
1094 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1095 boolean pushVlan, VlanId vlanId, boolean install) {
1096 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
1097 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1098 deviceId, portNum, vlanId);
1099 }
1100 }
1101
Charles Chan43be46b2017-02-26 22:59:35 -08001102 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1103 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001104 boolean doTMAC = true;
1105
1106 if (!pushVlan) {
1107 // Skip the tagged vlans belonging to an interface without an IP address
1108 Set<Interface> ifaces = srManager.interfaceService
1109 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1110 .stream()
1111 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1112 .collect(Collectors.toSet());
1113 if (!ifaces.isEmpty()) {
1114 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1115 vlanId, deviceId, portnum);
1116 doTMAC = false;
1117 }
1118 }
1119
1120 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Dasf9332192017-02-18 14:05:44 -08001121 if (fob == null) {
1122 // error encountered during build
1123 return false;
1124 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001125 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001126 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001127 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001128 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001129 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001130 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001131 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001132 if (install) {
1133 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1134 } else {
1135 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001136 }
Charles Chan90772a72017-02-08 15:52:08 -08001137 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001138 }
1139
Charles Chan90772a72017-02-08 15:52:08 -08001140 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001141 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Dasf9332192017-02-18 14:05:44 -08001142 MacAddress deviceMac;
1143 try {
1144 deviceMac = config.getDeviceMac(deviceId);
1145 } catch (DeviceConfigNotFoundException e) {
1146 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1147 return null;
1148 }
Saurav Dasf9332192017-02-18 14:05:44 -08001149 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001150
1151 if (doTMAC) {
1152 fob.withKey(Criteria.matchInPort(portnum))
1153 .addCondition(Criteria.matchEthDst(deviceMac))
1154 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1155 } else {
1156 fob.withKey(Criteria.matchInPort(portnum))
1157 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1158 }
Charles Chan90772a72017-02-08 15:52:08 -08001159
Charles Chan17ca2202017-12-19 19:55:57 -08001160 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1161
Charles Chan90772a72017-02-08 15:52:08 -08001162 if (pushVlan) {
1163 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001164 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001165 } else {
1166 fob.addCondition(Criteria.matchVlanId(vlanId));
1167 }
1168
Charles Chan17ca2202017-12-19 19:55:57 -08001169 // NOTE: Some switch hardware share the same filtering flow among different ports.
1170 // We use this metadata to let the driver know that there is no more enabled port
1171 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001172 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001173 tBuilder.wipeDeferred();
1174 }
1175
1176 fob.withMeta(tBuilder.build());
1177
Saurav Dasf9332192017-02-18 14:05:44 -08001178 fob.permit().fromApp(srManager.appId);
1179 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001180 }
1181
1182 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001183 * Creates or removes filtering objectives for a double-tagged host on a port.
1184 *
1185 * @param deviceId device identifier
1186 * @param portNum port identifier for port to be filtered
1187 * @param outerVlan outer VLAN ID
1188 * @param innerVlan inner VLAN ID
1189 * @param install true to install the filtering objective, false to remove
1190 */
1191 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1192 VlanId innerVlan, boolean install) {
Daniele Moro8fc37b42019-10-29 18:48:35 -07001193 // We should trigger the removal of double tagged rules only when removing
1194 // the filtering objective and no other hosts are connected to the same device port.
Charles Chanf17fade2020-03-08 18:07:19 -07001195 boolean cleanupDoubleTaggedRules = !anyDoubleTaggedHost(deviceId, portNum) && !install;
Daniele Moro8fc37b42019-10-29 18:48:35 -07001196 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum,
1197 outerVlan, innerVlan,
1198 cleanupDoubleTaggedRules);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001199 if (fob == null) {
1200 // error encountered during build
1201 return;
1202 }
1203 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1204 install ? "Installing" : "Removing", deviceId, portNum);
1205 ObjectiveContext context = new DefaultObjectiveContext(
1206 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1207 install ? "installed" : "removed"),
1208 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1209 install ? "install" : "remove", deviceId, portNum, error));
1210 if (install) {
1211 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1212 } else {
1213 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1214 }
1215 }
1216
Charles Chanf17fade2020-03-08 18:07:19 -07001217 /**
1218 * Checks if there is any double tagged host attached to given location.
1219 * This method will match on the effective location of a host.
1220 * That is, it will match on auxLocations when auxLocations is not null. Otherwise, it will match on locations.
1221 *
1222 * @param deviceId device ID
1223 * @param portNum port number
1224 * @return true if there is any host attached to given location.
1225 */
1226 private boolean anyDoubleTaggedHost(DeviceId deviceId, PortNumber portNum) {
1227 ConnectPoint cp = new ConnectPoint(deviceId, portNum);
1228 Set<Host> connectedHosts = srManager.hostService.getConnectedHosts(cp, false);
1229 Set<Host> auxConnectedHosts = srManager.hostService.getConnectedHosts(cp, true);
1230 return !auxConnectedHosts.isEmpty() ||
1231 connectedHosts.stream().anyMatch(host -> host.auxLocations() == null);
1232 }
1233
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001234 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001235 VlanId outerVlan, VlanId innerVlan,
1236 boolean cleanupDoubleTaggedRules) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001237 MacAddress deviceMac;
1238 try {
1239 deviceMac = config.getDeviceMac(deviceId);
1240 } catch (DeviceConfigNotFoundException e) {
1241 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1242 return null;
1243 }
1244 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1245 // Outer vlan id match should be appeared before inner vlan id match.
1246 fob.withKey(Criteria.matchInPort(portNum))
1247 .addCondition(Criteria.matchEthDst(deviceMac))
1248 .addCondition(Criteria.matchVlanId(outerVlan))
Daniele Moro998f2df2019-07-12 17:58:54 -07001249 .addCondition(Criteria.matchInnerVlanId(innerVlan))
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001250 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1251
1252 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1253 // Pop outer vlan
1254 tBuilder.popVlan();
1255
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001256 // special metadata for driver
1257 if (cleanupDoubleTaggedRules) {
1258 tBuilder.writeMetadata(CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES, DOUBLE_TAGGED_METADATA_MASK);
1259 } else {
1260 tBuilder.writeMetadata(0, DOUBLE_TAGGED_METADATA_MASK);
1261 }
1262
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001263 // NOTE: Some switch hardware share the same filtering flow among different ports.
1264 // We use this metadata to let the driver know that there is no more enabled port
1265 // within the same VLAN on this device.
1266 if (noMoreEnabledPort(deviceId, outerVlan)) {
1267 tBuilder.wipeDeferred();
1268 }
1269
1270 fob.withMeta(tBuilder.build());
1271
1272 fob.permit().fromApp(srManager.appId);
1273 return fob;
1274 }
1275
1276 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001277 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001278 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001279 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001280 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001281 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001282 * @param deviceId the switch dpid for the router
sangho80f11cb2015-04-01 13:05:26 -07001283 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001284 void populateIpPunts(DeviceId deviceId) {
Saurav Das261c3002017-06-13 15:35:54 -07001285 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001286 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001287 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001288 routerIpv4 = config.getRouterIpv4(deviceId);
1289 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001290 routerLinkLocalIpv6 = Ip6Address.valueOf(
1291 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1292
Saurav Das261c3002017-06-13 15:35:54 -07001293 if (config.isPairedEdge(deviceId)) {
1294 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1295 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1296 }
Charles Chan319d1a22015-11-03 10:42:14 -08001297 } catch (DeviceConfigNotFoundException e) {
Charles Chan18fa4252017-02-08 16:10:40 -08001298 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001299 return;
1300 }
1301
Saurav Dasc28b3432015-10-30 17:45:38 -07001302 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1303 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1304 deviceId);
1305 return;
1306 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001307 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1308 allIps.add(routerIpv4);
1309 if (routerIpv6 != null) {
1310 allIps.add(routerIpv6);
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001311 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001312 }
Saurav Das261c3002017-06-13 15:35:54 -07001313 if (pairRouterIpv4 != null) {
1314 allIps.add(pairRouterIpv4);
1315 }
1316 if (pairRouterIpv6 != null) {
1317 allIps.add(pairRouterIpv6);
1318 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001319 for (IpAddress ipaddr : allIps) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001320 populateSingleIpPunts(deviceId, ipaddr);
1321 }
1322 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001323
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001324 /**
1325 * Creates a forwarding objective to punt all IP packets, destined to the
1326 * specified IP address, which should be router's port IP address.
1327 *
1328 * @param deviceId the switch dpid for the router
1329 * @param ipAddress the IP address of the router's port
1330 */
1331 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1332 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1333 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1334
1335 srManager.packetService.requestPackets(sbuilder.build(),
1336 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1337 }
1338
1339 /**
1340 * Removes a forwarding objective to punt all IP packets, destined to the
1341 * specified IP address, which should be router's port IP address.
1342 *
1343 * @param deviceId the switch dpid for the router
1344 * @param ipAddress the IP address of the router's port
1345 */
1346 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1347 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1348 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1349
1350 try {
1351 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1352 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1353 srManager.packetService.cancelPackets(sbuilder.build(),
1354 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1355 }
1356 } catch (DeviceConfigNotFoundException e) {
1357 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das9f1c42e2015-10-23 10:51:11 -07001358 }
sangho80f11cb2015-04-01 13:05:26 -07001359 }
1360
piera9941192019-04-24 16:12:47 +02001361 // Method for building an IPv4 selector
1362 private TrafficSelector.Builder buildIpv4Selector() {
1363 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1364 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1365 return selectorBuilder;
1366 }
1367
1368 // Method for building an IPv6 selector
1369 private TrafficSelector.Builder buildIpv6Selector() {
1370 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1371 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1372 return selectorBuilder;
1373 }
1374
1375 // Method for building an IPv4 or IPv6 selector from an IP address
Pier Ventreadb4ae62016-11-23 09:57:42 -08001376 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1377 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1378 }
1379
piera9941192019-04-24 16:12:47 +02001380 // Method for building an IPv4 or IPv6 selector from an IP prefix
Pier Ventreadb4ae62016-11-23 09:57:42 -08001381 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1382 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001383 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001384 if (prefixToMatch.isIp4()) {
1385 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1386 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1387 return selectorBuilder;
1388 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001389 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001390 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1391 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1392 return selectorBuilder;
1393 }
1394
1395 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001396 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1397 * Furthermore, these are applied only by the master instance. Deferred actions
1398 * are not cleared such that packets can be flooded in the cross connect use case
1399 *
1400 * @param deviceId the switch dpid for the router
1401 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001402 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001403 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001404 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1405 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1406 deviceId);
1407 return;
1408 }
1409
Charles Chan3ed34d82017-06-22 18:03:14 -07001410 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001411 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001412 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001413 .add(new ObjectiveContext() {
1414 @Override
1415 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001416 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001417 deviceId, error);
1418 }
1419 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001420 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001421
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001422 if (isIpv6Configured(deviceId)) {
1423 // We punt all NDP packets towards the controller.
1424 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1425 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1426 @Override
1427 public void onError(Objective objective, ObjectiveError error) {
1428 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1429 deviceId, error);
1430 }
1431 });
1432 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan051490d2018-01-11 11:48:18 -08001433 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001434 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001435
Saurav Dasec683dc2018-04-27 18:42:30 -07001436 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001437 ForwardingObjective pairFwdObj;
1438 // Do not punt ARP packets from pair port
1439 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1440 .add(new ObjectiveContext() {
1441 @Override
1442 public void onError(Objective objective, ObjectiveError error) {
1443 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1444 deviceId, error);
1445 }
1446 });
1447 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1448
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001449 if (isIpv6Configured(deviceId)) {
1450 // Do not punt NDP packets from pair port
1451 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1452 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan3ed34d82017-06-22 18:03:14 -07001453 @Override
1454 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001455 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan3ed34d82017-06-22 18:03:14 -07001456 deviceId, error);
1457 }
1458 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001459 srManager.flowObjectiveService.forward(deviceId, obj);
1460 });
1461
1462 // Do not forward DAD packets from pair port
1463 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1464 .add(new ObjectiveContext() {
1465 @Override
1466 public void onError(Objective objective, ObjectiveError error) {
1467 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1468 deviceId, error);
1469 }
1470 });
1471 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1472 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001473 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001474 }
1475
Charles Chan3ed34d82017-06-22 18:03:14 -07001476 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1477 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001478 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001479 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001480 .withSelector(selector)
1481 .fromApp(srManager.appId)
1482 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001483 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001484 .makePermanent();
1485 }
1486
Charles Chan3ed34d82017-06-22 18:03:14 -07001487 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001488 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1489 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001490 if (port != null) {
1491 sBuilder.matchInPort(port);
1492 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001493
Charles Chan3ed34d82017-06-22 18:03:14 -07001494 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1495 if (punt) {
1496 tBuilder.punt();
1497 }
1498 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001499 }
1500
Charles Chan051490d2018-01-11 11:48:18 -08001501 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1502 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001503
Charles Chan051490d2018-01-11 11:48:18 -08001504 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1505 .forEach(type -> {
1506 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1507 sBuilder.matchEthType(TYPE_IPV6)
1508 .matchIPProtocol(PROTOCOL_ICMP6)
1509 .matchIcmpv6Type(type);
1510 if (port != null) {
1511 sBuilder.matchInPort(port);
1512 }
1513
1514 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1515 if (punt) {
1516 tBuilder.punt();
1517 }
1518
1519 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1520 });
1521
1522 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001523 }
1524
1525 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1526 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1527 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001528 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1529 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1530 // .matchIPProtocol(PROTOCOL_ICMP6)
1531 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001532 if (port != null) {
1533 sBuilder.matchInPort(port);
1534 }
1535
1536 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1537 tBuilder.wipeDeferred();
1538 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001539 }
1540
1541 /**
Charles Chan155ec442018-09-16 14:30:19 -07001542 * Block given prefix in routing table.
Charles Chanf4586112015-11-09 16:37:23 -08001543 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001544 * @param address the address to block
1545 * @param deviceId switch ID to set the rules
1546 */
1547 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1548 updateDefaultRouteBlackhole(deviceId, address, true);
1549 }
1550
1551 /**
Charles Chan155ec442018-09-16 14:30:19 -07001552 * Unblock given prefix in routing table.
Andrea Campanella60ce2222018-04-30 11:48:55 +02001553 *
1554 * @param address the address to block
1555 * @param deviceId switch ID to set the rules
1556 */
1557 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1558 updateDefaultRouteBlackhole(deviceId, address, false);
1559 }
1560
1561 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1562 try {
1563 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1564
1565 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1566 if (address.isIp4()) {
1567 sbuilder.matchIPDst(address);
1568 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1569 } else {
1570 sbuilder.matchIPv6Dst(address);
1571 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1572 }
1573
1574 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
Andrea Campanella60ce2222018-04-30 11:48:55 +02001575 tBuilder.wipeDeferred();
1576
1577 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1578 fob.withFlag(Flag.SPECIFIC)
1579 .withSelector(sbuilder.build())
1580 .withTreatment(tBuilder.build())
1581 .withPriority(getPriorityFromPrefix(address))
1582 .fromApp(srManager.appId)
1583 .makePermanent();
1584
1585 log.debug("{} blackhole forwarding objectives for dev: {}",
1586 install ? "Installing" : "Removing", deviceId);
1587 ObjectiveContext context = new DefaultObjectiveContext(
1588 (objective) -> log.debug("Forward for {} {}", deviceId,
1589 install ? "installed" : "removed"),
1590 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1591 install ? "install" : "remove", deviceId, error));
1592 if (install) {
1593 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1594 } else {
1595 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1596 }
1597 }
1598 } catch (DeviceConfigNotFoundException e) {
1599 log.info("Not populating blackhole for un-configured device {}", deviceId);
1600 }
1601
1602 }
1603
1604 /**
1605 * Populates a forwarding objective to send packets that miss other high
1606 * priority Bridging Table entries to a group that contains all ports of
1607 * its subnet.
1608 *
Charles Chanf4586112015-11-09 16:37:23 -08001609 * @param deviceId switch ID to set the rules
1610 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001611 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001612 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001613 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001614 });
1615 }
1616
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001617 /**
1618 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1619 * @param deviceId switch ID to set the rule
1620 * @param vlanId vlan ID to specify the subnet
1621 * @param install true to install the rule, false to revoke the rule
1622 */
1623 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1624 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1625
1626 if (nextId < 0) {
1627 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1628 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1629 return;
1630 }
1631
1632 // Driver should treat objective with MacAddress.NONE as the
1633 // subnet broadcast rule
1634 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1635 sbuilder.matchVlanId(vlanId);
1636 sbuilder.matchEthDst(MacAddress.NONE);
1637
1638 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1639 fob.withFlag(Flag.SPECIFIC)
1640 .withSelector(sbuilder.build())
1641 .nextStep(nextId)
1642 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1643 .fromApp(srManager.appId)
1644 .makePermanent();
1645 ObjectiveContext context = new DefaultObjectiveContext(
1646 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1647 (objective, error) ->
1648 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1649
1650 if (install) {
1651 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1652 } else {
1653 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1654 }
1655 }
1656
Charles Chan82ab1932016-01-30 23:22:37 -08001657 private int getPriorityFromPrefix(IpPrefix prefix) {
1658 return (prefix.isIp4()) ?
1659 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1660 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001661 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001662
1663 /**
1664 * Update Forwarding objective for each host and IP address connected to given port.
1665 * And create corresponding Simple Next objective if it does not exist.
1666 * Applied only when populating Forwarding objective
1667 * @param deviceId switch ID to set the rule
1668 * @param portNumber port number
1669 * @param prefix IP prefix of the route
1670 * @param hostMac MAC address of the next hop
1671 * @param vlanId Vlan ID of the port
1672 * @param popVlan true to pop vlan tag in TrafficTreatment
1673 * @param install true to populate the forwarding objective, false to revoke
1674 */
1675 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1676 VlanId vlanId, boolean popVlan, boolean install) {
1677 ForwardingObjective.Builder fob;
1678 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1679 MacAddress deviceMac;
1680 try {
1681 deviceMac = config.getDeviceMac(deviceId);
1682 } catch (DeviceConfigNotFoundException e) {
1683 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1684 return;
1685 }
1686
1687 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1688 tbuilder.deferred()
1689 .setEthDst(hostMac)
1690 .setEthSrc(deviceMac)
1691 .setOutput(portNumber);
1692
1693 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1694
1695 if (!popVlan) {
1696 tbuilder.setVlanId(vlanId);
1697 } else {
1698 mbuilder.matchVlanId(vlanId);
1699 }
1700
1701 // if the objective is to revoke an existing rule, and for some reason
1702 // the next-objective does not exist, then a new one should not be created
1703 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1704 tbuilder.build(), mbuilder.build(), install);
1705 if (portNextObjId == -1) {
1706 // Warning log will come from getPortNextObjective method
1707 return;
1708 }
1709
1710 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1711 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1712 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1713
1714 ObjectiveContext context = new DefaultObjectiveContext(
1715 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1716 (objective, error) ->
1717 log.warn("Failed to {} IP rule for route {}: {}",
1718 install ? "install" : "revoke", prefix, error));
1719 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1720
1721 if (!install) {
Shibu Vijayakumar632dd642018-03-01 15:45:59 -08001722 if (!srManager.getVlanPortMap(deviceId).containsKey(vlanId) ||
1723 !srManager.getVlanPortMap(deviceId).get(vlanId).contains(portNumber)) {
1724 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1725 if (grpHandler == null) {
1726 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1727 } else {
1728 // Remove L3UG for the given port and host
1729 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1730 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001731 }
1732 }
1733 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001734
1735 /**
1736 * Checks if there is other enabled port within the given VLAN on the given device.
1737 *
1738 * @param deviceId device ID
1739 * @param vlanId VLAN ID
1740 * @return true if there is no more port enabled within the given VLAN on the given device
1741 */
1742 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1743 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1744 .filter(Port::isEnabled)
1745 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1746 .collect(Collectors.toSet());
1747
1748 return enabledPorts.stream().noneMatch(cp ->
1749 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001750 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
pieraac79e92019-10-04 15:40:34 +02001751 // Given vlanId is INTERNAL_VLAN or PSEUDOWIRE_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001752 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
pieraac79e92019-10-04 15:40:34 +02001753 (vlanId.equals(srManager.getDefaultInternalVlan()) || vlanId.equals(srManager.getPwTransportVlan()))) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001754 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1755 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1756 );
1757 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001758
1759 /**
1760 * Returns a forwarding objective builder for egress forwarding rules.
1761 * <p>
1762 * The forwarding objective installs flow rules to egress pipeline to push
1763 * two vlan headers with given inner, outer vlan ids and outer tpid.
1764 *
1765 * @param portNumber port where the next hop attaches to
1766 * @param dummyVlanId vlan ID of the packet to match
1767 * @param innerVlan inner vlan ID of the next hop
1768 * @param outerVlan outer vlan ID of the next hop
1769 * @param outerTpid outer TPID of the next hop
1770 * @return forwarding objective builder
1771 */
1772 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1773 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1774 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1775 sbuilder.matchVlanId(dummyVlanId);
1776 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1777 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1778
1779 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1780 tbuilder.pushVlan(outerTpid);
1781 } else {
1782 tbuilder.pushVlan();
1783 }
1784
1785 tbuilder.setVlanId(outerVlan);
1786 return DefaultForwardingObjective.builder()
1787 .withSelector(sbuilder.build())
1788 .withTreatment(tbuilder.build())
1789 .fromApp(srManager.appId)
1790 .makePermanent()
1791 .withPriority(DEFAULT_PRIORITY)
1792 .withFlag(ForwardingObjective.Flag.EGRESS);
1793 }
1794
1795 /**
1796 * Populates IP rules for a route that has double-tagged next hop.
1797 *
1798 * @param deviceId device ID of the device that next hop attaches to
1799 * @param prefix IP prefix of the route
1800 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001801 * @param innerVlan inner Vlan ID of the next hop
1802 * @param outerVlan outer Vlan ID of the next hop
1803 * @param outerTpid outer TPID of the next hop
1804 * @param outPort port where the next hop attaches to
1805 */
Charles Chan61c086d2019-07-26 17:46:15 -07001806 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001807 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1808 ForwardingObjective.Builder fwdBuilder;
1809 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1810 prefix, deviceId, outPort);
1811
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001812 try {
Charles Chan61c086d2019-07-26 17:46:15 -07001813 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1814 true, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001815 } catch (DeviceConfigNotFoundException e) {
1816 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1817 return;
1818 }
1819 if (fwdBuilder == null) {
1820 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1821 deviceId, prefix);
1822 return;
1823 }
1824
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001825 int nextId = fwdBuilder.add().nextId();
1826 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1827 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001828 }, (objective, error) ->
1829 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1830 );
1831 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1832 rulePopulationCounter.incrementAndGet();
1833 }
1834
1835 /**
1836 * Revokes IP rules for a route that has double-tagged next hop.
1837 *
1838 * @param deviceId device ID of the device that next hop attaches to
1839 * @param prefix IP prefix of the route
1840 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001841 * @param innerVlan inner Vlan ID of the next hop
1842 * @param outerVlan outer Vlan ID of the next hop
1843 * @param outerTpid outer TPID of the next hop
1844 * @param outPort port where the next hop attaches to
1845 */
1846 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -07001847 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1848 ForwardingObjective.Builder fwdBuilder;
1849 log.debug("Revoking direct routing entry for double-tagged host route {} at {}:{}",
1850 prefix, deviceId, outPort);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001851
Charles Chan61c086d2019-07-26 17:46:15 -07001852 try {
1853 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1854 true, true);
1855 } catch (DeviceConfigNotFoundException e) {
1856 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001857 return;
1858 }
Charles Chan61c086d2019-07-26 17:46:15 -07001859 if (fwdBuilder == null) {
1860 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1861 deviceId, prefix);
1862 return;
1863 }
1864
1865 int nextId = fwdBuilder.remove().nextId();
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001866 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
Charles Chan61c086d2019-07-26 17:46:15 -07001867 log.debug("Direct routing rule for double-tagged host route {} revoked. nextId={}", prefix, nextId);
1868
1869 // Try to remove next objective as well
1870 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta;
1871 try {
1872 treatmentAndMeta = getTreatmentAndMeta(deviceId, hostMac, outerVlan, outPort, innerVlan, outerTpid);
1873 } catch (DeviceConfigNotFoundException e) {
1874 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
1875 return;
1876 }
1877
1878 if (treatmentAndMeta == null) {
1879 // Warning log will come from getTreatmentAndMeta method
1880 return;
1881 }
1882
1883 DefaultGroupHandler groupHandler = srManager.getGroupHandler(deviceId);
1884 if (groupHandler == null) {
1885 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: " +
1886 "group handler not found for {}", prefix, deviceId);
1887 return;
1888 }
1889 groupHandler.removeGroupFromPort(outPort, treatmentAndMeta.getLeft(), treatmentAndMeta.getRight());
1890
1891 }, (objective, error) ->
1892 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: {}", prefix, error)
1893 );
1894 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001895 }
1896
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001897 /**
1898 * Checks whether the specified port has IP configuration or not.
1899 *
1900 * @param cp ConnectPoint to check the existance of IP configuration
1901 * @return true if the port has IP configuration; false otherwise.
1902 */
1903 private boolean hasIPConfiguration(ConnectPoint cp) {
1904 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1905 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1906 }
Saurav Das9bf49582018-08-13 15:34:26 -07001907
1908 /**
1909 * Updates filtering rules for unconfigured ports on all devices for which
1910 * this controller instance is master.
1911 *
1912 * @param pushVlan true if the filtering rule requires a push vlan action
1913 * @param oldVlanId the vlanId to be removed
1914 * @param newVlanId the vlanId to be added
1915 */
1916 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1917 VlanId newVlanId) {
1918 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1919 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1920 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1921 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1922 && p.isEnabled()) {
1923 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1924 oldVlanId, false);
1925 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1926 newVlanId, true);
1927 }
1928 }
1929 }
1930 }
1931 }
1932
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001933 private boolean isIpv6Configured(DeviceId deviceId) {
1934 boolean isIpv6Configured;
1935 try {
1936 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1937 } catch (DeviceConfigNotFoundException e) {
1938 isIpv6Configured = false;
1939 }
1940 return isIpv6Configured;
1941 }
sangho80f11cb2015-04-01 13:05:26 -07001942}