blob: f19b68c0ed29c5108324319ce005e49e1d951899 [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 Chan1eaf4802016-04-18 13:44:03 -070033import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080034import org.onosproject.net.flowobjective.Objective;
Charles Chan1eaf4802016-04-18 13:44:03 -070035import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080036import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -070037import org.onosproject.net.intf.Interface;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080038import org.onosproject.net.packet.PacketPriority;
Charles Chan319d1a22015-11-03 10:42:14 -080039import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
40import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070041import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070042import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sangho80f11cb2015-04-01 13:05:26 -070043import org.onosproject.net.DeviceId;
Saurav Das7c305372015-10-28 12:39:42 -070044import org.onosproject.net.Port;
sangho80f11cb2015-04-01 13:05:26 -070045import org.onosproject.net.PortNumber;
sangho80f11cb2015-04-01 13:05:26 -070046import org.onosproject.net.flow.DefaultTrafficSelector;
47import org.onosproject.net.flow.DefaultTrafficTreatment;
sangho80f11cb2015-04-01 13:05:26 -070048import org.onosproject.net.flow.TrafficSelector;
49import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070050import org.onosproject.net.flow.criteria.Criteria;
51import org.onosproject.net.flowobjective.DefaultFilteringObjective;
52import org.onosproject.net.flowobjective.DefaultForwardingObjective;
53import org.onosproject.net.flowobjective.FilteringObjective;
54import org.onosproject.net.flowobjective.ForwardingObjective;
55import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
Saurav Das9f1c42e2015-10-23 10:51:11 -070056import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
sangho80f11cb2015-04-01 13:05:26 -070057import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
60import java.util.ArrayList;
Pier Ventre229fd0b2016-10-31 16:49:19 -070061import java.util.Collection;
62import java.util.Collections;
Saurav Das261c3002017-06-13 15:35:54 -070063import java.util.HashMap;
Saurav Dasc28b3432015-10-30 17:45:38 -070064import java.util.HashSet;
sangho80f11cb2015-04-01 13:05:26 -070065import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070066import java.util.Map;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080067import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070068import java.util.Set;
sanghofb7c7292015-04-13 15:15:58 -070069import java.util.concurrent.atomic.AtomicLong;
Charles Chanf17f66b2018-02-26 21:33:25 -080070import java.util.stream.Collectors;
sangho80f11cb2015-04-01 13:05:26 -070071
72import static com.google.common.base.Preconditions.checkNotNull;
Pier Luigib9632ba2017-01-12 18:14:58 -080073import static org.onlab.packet.Ethernet.TYPE_ARP;
74import static org.onlab.packet.Ethernet.TYPE_IPV6;
Charles Chan051490d2018-01-11 11:48:18 -080075import static org.onlab.packet.ICMP6.NEIGHBOR_ADVERTISEMENT;
Pier Luigib9632ba2017-01-12 18:14:58 -080076import static org.onlab.packet.ICMP6.NEIGHBOR_SOLICITATION;
Charles Chan051490d2018-01-11 11:48:18 -080077import static org.onlab.packet.ICMP6.ROUTER_ADVERTISEMENT;
78import static org.onlab.packet.ICMP6.ROUTER_SOLICITATION;
Pier Luigib9632ba2017-01-12 18:14:58 -080079import static org.onlab.packet.IPv6.PROTOCOL_ICMP6;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070080import static org.onosproject.segmentrouting.SegmentRoutingService.DEFAULT_PRIORITY;
sangho80f11cb2015-04-01 13:05:26 -070081
Charles Chanb7f75ac2016-01-11 18:28:54 -080082/**
83 * Populator of segment routing flow rules.
84 */
sangho80f11cb2015-04-01 13:05:26 -070085public class RoutingRulePopulator {
Charles Chanef8d12e2017-12-05 21:07:38 -080086 private static final Logger log = LoggerFactory.getLogger(RoutingRulePopulator.class);
87
88 private static final int ARP_NDP_PRIORITY = 30000;
sangho80f11cb2015-04-01 13:05:26 -070089
sanghofb7c7292015-04-13 15:15:58 -070090 private AtomicLong rulePopulationCounter;
sangho9b169e32015-04-14 16:27:13 -070091 private SegmentRoutingManager srManager;
92 private DeviceConfiguration config;
psneha86e60d32019-03-26 06:31:41 -040093 private RouteSimplifierUtils routeSimplifierUtils;
Saurav Das9f1c42e2015-10-23 10:51:11 -070094
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -070095 // used for signalling the driver to remove vlan table and tmac entry also
96 private static final long CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES = 1;
97 private static final long DOUBLE_TAGGED_METADATA_MASK = 0xffffffffffffffffL;
98
sangho80f11cb2015-04-01 13:05:26 -070099 /**
100 * Creates a RoutingRulePopulator object.
101 *
Thomas Vachuska8a075092015-04-15 18:20:08 -0700102 * @param srManager segment routing manager reference
sangho80f11cb2015-04-01 13:05:26 -0700103 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700104 RoutingRulePopulator(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700105 this.srManager = srManager;
sangho9b169e32015-04-14 16:27:13 -0700106 this.config = checkNotNull(srManager.deviceConfiguration);
sanghofb7c7292015-04-13 15:15:58 -0700107 this.rulePopulationCounter = new AtomicLong(0);
psneha86e60d32019-03-26 06:31:41 -0400108 this.routeSimplifierUtils = new RouteSimplifierUtils(srManager);
sanghofb7c7292015-04-13 15:15:58 -0700109 }
110
111 /**
112 * Resets the population counter.
113 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700114 void resetCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700115 rulePopulationCounter.set(0);
116 }
117
118 /**
119 * Returns the number of rules populated.
Thomas Vachuska7cfc6202015-04-30 18:13:25 -0700120 *
121 * @return number of rules
sanghofb7c7292015-04-13 15:15:58 -0700122 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700123 long getCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700124 return rulePopulationCounter.get();
sangho80f11cb2015-04-01 13:05:26 -0700125 }
126
127 /**
Charles Chand66d6712018-03-29 16:03:41 -0700128 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
129 * output to given port.
130 *
131 * @param deviceId device ID
132 * @param port port
133 * @param mac mac address
134 * @param vlanId VLAN ID
135 */
136 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
137 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
138 if (fob == null) {
139 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
140 return;
141 }
142
143 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700144 (objective) -> log.debug("Brigding rule for {}/{} populated", mac, vlanId),
145 (objective, error) -> log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700146 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
147 }
148
149 /**
150 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
151 * output to given port.
152 *
153 * @param deviceId device ID
154 * @param port port
155 * @param mac mac address
156 * @param vlanId VLAN ID
157 */
158 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
159 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
160 if (fob == null) {
161 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
162 return;
163 }
164
165 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700166 (objective) -> log.debug("Brigding rule for {}/{} revoked", mac, vlanId),
167 (objective, error) -> log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700168 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
169 }
170
171 /**
172 * Generates a forwarding objective builder for bridging rules.
173 * <p>
174 * The forwarding objective bridges packets destined to a given MAC to
175 * given port on given device.
176 *
177 * @param deviceId Device that host attaches to
178 * @param mac MAC address of the host
179 * @param hostVlanId VLAN ID of the host
180 * @param outport Port that host attaches to
181 * @param revoke true if forwarding objective is meant to revoke forwarding rule
182 * @return Forwarding objective builder
183 */
184 private ForwardingObjective.Builder bridgingFwdObjBuilder(
185 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
186 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan098ca202018-05-01 11:50:20 -0700187 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
188 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
189 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chand66d6712018-03-29 16:03:41 -0700190
191 // Create host selector
192 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
193 sbuilder.matchEthDst(mac);
194
195 // Create host treatment
196 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
197 tbuilder.immediate().setOutput(outport);
198
199 // Create host meta
200 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
201
202 // Adjust the selector, treatment and meta according to VLAN configuration
203 if (taggedVlans.contains(hostVlanId)) {
204 sbuilder.matchVlanId(hostVlanId);
205 mbuilder.matchVlanId(hostVlanId);
206 } else if (hostVlanId.equals(VlanId.NONE)) {
207 if (untaggedVlan != null) {
208 sbuilder.matchVlanId(untaggedVlan);
209 mbuilder.matchVlanId(untaggedVlan);
210 tbuilder.immediate().popVlan();
211 } else if (nativeVlan != null) {
212 sbuilder.matchVlanId(nativeVlan);
213 mbuilder.matchVlanId(nativeVlan);
214 tbuilder.immediate().popVlan();
215 } else {
216 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
217 "vlan config", mac, hostVlanId, connectPoint);
218 return null;
219 }
220 } else {
221 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
222 mac, hostVlanId, connectPoint);
223 return null;
224 }
225
226 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
227 // If the objective is to revoke an existing rule, and for some reason
228 // the next-objective does not exist, then a new one should not be created
229 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
230 tbuilder.build(), mbuilder.build(), !revoke);
231 if (portNextObjId == -1) {
232 // Warning log will come from getPortNextObjective method
233 return null;
234 }
235
236 return DefaultForwardingObjective.builder()
237 .withFlag(ForwardingObjective.Flag.SPECIFIC)
238 .withSelector(sbuilder.build())
239 .nextStep(portNextObjId)
240 .withPriority(100)
241 .fromApp(srManager.appId)
242 .makePermanent();
243 }
244
245 /**
246 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
247 * and hostMAC connected to given port, and output to given port only when
248 * vlan information is valid.
249 *
250 * @param deviceId device ID that host attaches to
251 * @param portNum port number that host attaches to
252 * @param hostMac mac address of the host connected to the switch port
253 * @param vlanId Vlan ID configured on the switch port
254 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
255 * @param install true to populate the objective, false to revoke
256 */
257 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
258 // revokeBridging and bridgingFwdObjBuilder.
259 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
260 VlanId vlanId, boolean popVlan, boolean install) {
261 // Create host selector
262 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
263 sbuilder.matchEthDst(hostMac);
264
265 // Create host meta
266 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
267
268 sbuilder.matchVlanId(vlanId);
269 mbuilder.matchVlanId(vlanId);
270
271 // Create host treatment
272 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
273 tbuilder.immediate().setOutput(portNum);
274
275 if (popVlan) {
276 tbuilder.immediate().popVlan();
277 }
278
279 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
280 tbuilder.build(), mbuilder.build(), install);
281 if (portNextObjId != -1) {
282 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
283 .withFlag(ForwardingObjective.Flag.SPECIFIC)
284 .withSelector(sbuilder.build())
285 .nextStep(portNextObjId)
286 .withPriority(100)
287 .fromApp(srManager.appId)
288 .makePermanent();
289
290 ObjectiveContext context = new DefaultObjectiveContext(
291 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
292 install ? "populated" : "revoked"),
293 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
294 install ? "populate" : "revoke", hostMac, vlanId, error));
295 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
296 } else {
297 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
298 }
299 }
300
301 /**
302 * Populates IP rules for a route that has direct connection to the switch.
303 * This method should not be invoked directly without going through DefaultRoutingHandler.
sangho80f11cb2015-04-01 13:05:26 -0700304 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700305 * @param deviceId device ID of the device that next hop attaches to
306 * @param prefix IP prefix of the route
307 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800308 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700309 * @param outPort port where the next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000310 * @param directHost host is of type direct or indirect
sangho80f11cb2015-04-01 13:05:26 -0700311 */
Charles Chan910be6a2017-08-23 14:46:43 -0700312 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000313 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Saurav Das261c3002017-06-13 15:35:54 -0700314 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chanddac7fd2016-10-27 14:19:48 -0700315 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800316 ForwardingObjective.Builder fwdBuilder;
Charles Chan319d1a22015-11-03 10:42:14 -0800317 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700318 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -0700319 hostVlanId, outPort, null, null, directHost, false);
Charles Chan319d1a22015-11-03 10:42:14 -0800320 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -0700321 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan319d1a22015-11-03 10:42:14 -0800322 return;
323 }
Saurav Das07c74602016-04-27 18:35:50 -0700324 if (fwdBuilder == null) {
Saurav Das368cf212017-03-15 15:15:14 -0700325 log.warn("Aborting host routing table entry due "
Charles Chanddac7fd2016-10-27 14:19:48 -0700326 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das07c74602016-04-27 18:35:50 -0700327 return;
328 }
Charles Chan910be6a2017-08-23 14:46:43 -0700329
330 int nextId = fwdBuilder.add().nextId();
Charles Chan1eaf4802016-04-18 13:44:03 -0700331 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan910be6a2017-08-23 14:46:43 -0700332 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
333 prefix, nextId),
Charles Chan1eaf4802016-04-18 13:44:03 -0700334 (objective, error) ->
Saurav Das261c3002017-06-13 15:35:54 -0700335 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das368cf212017-03-15 15:15:14 -0700336 prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700337 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chanf4586112015-11-09 16:37:23 -0800338 rulePopulationCounter.incrementAndGet();
339 }
340
Charles Chanb7f75ac2016-01-11 18:28:54 -0800341 /**
Charles Chanddac7fd2016-10-27 14:19:48 -0700342 * Removes IP rules for a route when the next hop is gone.
Charles Chand66d6712018-03-29 16:03:41 -0700343 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800344 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700345 * @param deviceId device ID of the device that next hop attaches to
346 * @param prefix IP prefix of the route
347 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800348 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700349 * @param outPort port that next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000350 * @param directHost host is of type direct or indirect
Charles Chanb7f75ac2016-01-11 18:28:54 -0800351 */
Charles Chan910be6a2017-08-23 14:46:43 -0700352 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000353 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chanddac7fd2016-10-27 14:19:48 -0700354 log.debug("Revoke IP table entry for route {} at {}:{}",
355 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800356 ForwardingObjective.Builder fwdBuilder;
357 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700358 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -0700359 hostVlanId, outPort, null, null, directHost, true);
Charles Chanf4586112015-11-09 16:37:23 -0800360 } catch (DeviceConfigNotFoundException e) {
361 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
362 return;
363 }
Charles Chanea702b12016-11-30 11:55:05 -0800364 if (fwdBuilder == null) {
365 log.warn("Aborting host routing table entries due "
366 + "to error for dev:{} route:{}", deviceId, prefix);
367 return;
368 }
Charles Chan1eaf4802016-04-18 13:44:03 -0700369 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chanddac7fd2016-10-27 14:19:48 -0700370 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chan1eaf4802016-04-18 13:44:03 -0700371 (objective, error) ->
Charles Chanddac7fd2016-10-27 14:19:48 -0700372 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700373 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chanf4586112015-11-09 16:37:23 -0800374 }
375
Charles Chanddac7fd2016-10-27 14:19:48 -0700376 /**
Charles Chan18fa4252017-02-08 16:10:40 -0800377 * Returns a forwarding objective builder for routing rules.
378 * <p>
379 * The forwarding objective routes packets destined to a given prefix to
380 * given port on given device with given destination MAC.
Charles Chanddac7fd2016-10-27 14:19:48 -0700381 *
382 * @param deviceId device ID
383 * @param prefix prefix that need to be routed
384 * @param hostMac MAC address of the nexthop
Charles Chan90772a72017-02-08 15:52:08 -0800385 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700386 * @param outPort port where the nexthop attaches to
Saurav Das2cb38292017-03-29 19:09:17 -0700387 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000388 * @param directHost host is direct or indirect
Charles Chanddac7fd2016-10-27 14:19:48 -0700389 * @return forwarding objective builder
390 * @throws DeviceConfigNotFoundException if given device is not configured
391 */
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000392
Charles Chan61c086d2019-07-26 17:46:15 -0700393 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700394 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700395 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
Charles Chan61c086d2019-07-26 17:46:15 -0700396 VlanId innerVlan, EthType outerTpid,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000397 boolean directHost, boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800398 throws DeviceConfigNotFoundException {
Charles Chan61c086d2019-07-26 17:46:15 -0700399 int nextObjId;
400 if (directHost) {
401 // if the objective is to revoke an existing rule, and for some reason
402 // the next-objective does not exist, then a new one should not be created
403 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta =
404 getTreatmentAndMeta(deviceId, hostMac, hostVlanId, outPort, innerVlan, outerTpid);
405 if (treatmentAndMeta == null) {
406 // Warning log will come from getTreatmentAndMeta method
407 return null;
408 }
409 nextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
410 treatmentAndMeta.getLeft(), treatmentAndMeta.getRight(), !revoke);
411 } else {
412 // if the objective is to revoke an existing rule, and for some reason
413 // the next-objective does not exist, then a new one should not be created
414 nextObjId = srManager.getMacVlanNextObjectiveId(deviceId, hostMac, hostVlanId,
415 outPort, !revoke);
416 }
417 if (nextObjId == -1) {
418 // Warning log will come from getMacVlanNextObjective method
419 return null;
420 }
421
422 return DefaultForwardingObjective.builder()
423 .withSelector(buildIpSelectorFromIpPrefix(prefix).build())
424 .nextStep(nextObjId)
425 .fromApp(srManager.appId).makePermanent()
426 .withPriority(getPriorityFromPrefix(prefix))
427 .withFlag(ForwardingObjective.Flag.SPECIFIC);
428 }
429
430 private ImmutablePair<TrafficTreatment, TrafficSelector> getTreatmentAndMeta(
431 DeviceId deviceId, MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
432 VlanId innerVlan, EthType outerTpid)
433 throws DeviceConfigNotFoundException {
434 MacAddress routerMac;
435 routerMac = config.getDeviceMac(deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800436
Charles Chan90772a72017-02-08 15:52:08 -0800437 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700438 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
439 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
440 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700441
Charles Chan90772a72017-02-08 15:52:08 -0800442 // Create route treatment
Charles Chanddac7fd2016-10-27 14:19:48 -0700443 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho27462c62015-05-14 00:39:53 -0700444 tbuilder.deferred()
445 .setEthDst(hostMac)
Charles Chan61c086d2019-07-26 17:46:15 -0700446 .setEthSrc(routerMac)
sangho80f11cb2015-04-01 13:05:26 -0700447 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800448
Charles Chan90772a72017-02-08 15:52:08 -0800449 // Create route meta
450 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800451
Charles Chan61c086d2019-07-26 17:46:15 -0700452 // Adjust treatment and meta according to VLAN configuration
Charles Chan90772a72017-02-08 15:52:08 -0800453 if (taggedVlans.contains(hostVlanId)) {
454 tbuilder.setVlanId(hostVlanId);
455 } else if (hostVlanId.equals(VlanId.NONE)) {
456 if (untaggedVlan != null) {
457 mbuilder.matchVlanId(untaggedVlan);
458 } else if (nativeVlan != null) {
459 mbuilder.matchVlanId(nativeVlan);
460 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700461 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
462 hostMac, hostVlanId, connectPoint);
463 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800464 }
465 } else {
Charles Chan61c086d2019-07-26 17:46:15 -0700466 // Double tagged hosts
467 if (innerVlan == null || outerTpid == null) {
468 log.warn("Failed to construct NextObj for double tagged hosts {}/{}. {} {}",
469 hostMac, hostVlanId,
470 (innerVlan == null) ? "innerVlan = null." : "",
471 (outerTpid == null) ? "outerTpid = null." : "");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700472 return null;
473 }
Charles Chan61c086d2019-07-26 17:46:15 -0700474 tbuilder.setVlanId(innerVlan);
475 tbuilder.pushVlan(outerTpid);
476 tbuilder.setVlanId(hostVlanId);
477 mbuilder.matchVlanId(VlanId.ANY);
Saurav Das07c74602016-04-27 18:35:50 -0700478 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000479
Charles Chan61c086d2019-07-26 17:46:15 -0700480 return ImmutablePair.of(tbuilder.build(), mbuilder.build());
sangho80f11cb2015-04-01 13:05:26 -0700481 }
482
483 /**
Saurav Das261c3002017-06-13 15:35:54 -0700484 * Populates IP flow rules for all the given prefixes reachable from the
485 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700486 *
Saurav Das261c3002017-06-13 15:35:54 -0700487 * @param targetSw switch where rules are to be programmed
488 * @param subnets subnets/prefixes being added
489 * @param destSw1 destination switch where the prefixes are reachable
490 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
491 * Should be null if there is no paired destination switch (by config)
492 * or if the given prefixes are reachable only via destSw1
493 * @param nextHops a map containing a set of next-hops for each destination switch.
494 * If destSw2 is not null, then this map must contain an
495 * entry for destSw2 with its next-hops from the targetSw
496 * (although the next-hop set may be empty in certain scenarios).
497 * If destSw2 is null, there should not be an entry in this
498 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700499 * @return true if all rules are set successfully, false otherwise
500 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700501 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700502 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
psneha86e60d32019-03-26 06:31:41 -0400503 // Get pair device of the target switch
504 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
505 // Route simplification will be off in case of the nexthop location at target switch is down
506 // (routing through spine case)
507 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
piera9941192019-04-24 16:12:47 +0200508 // Iterates over the routes. Checking:
psneha86e60d32019-03-26 06:31:41 -0400509 // If route simplification is enabled
510 // If the target device is another leaf in the network
511 if (srManager.routeSimplification && !routeSimplOff) {
piera9941192019-04-24 16:12:47 +0200512 Set<IpPrefix> subnetsToBePopulated = Sets.newHashSet();
psneha86e60d32019-03-26 06:31:41 -0400513 for (IpPrefix subnet : subnets) {
514 // Skip route programming on the target device
515 // If route simplification applies
516 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
517 // XXX route simplification assumes that source of the traffic
518 // towards the nexthops are co-located with the nexthops. In different
519 // scenarios will not work properly.
520 continue;
521 }
522 // populate the route in the remaning scenarios
piera9941192019-04-24 16:12:47 +0200523 subnetsToBePopulated.add(subnet);
psneha86e60d32019-03-26 06:31:41 -0400524 }
piera9941192019-04-24 16:12:47 +0200525 subnets = subnetsToBePopulated;
sangho80f11cb2015-04-01 13:05:26 -0700526 }
piera9941192019-04-24 16:12:47 +0200527 // populate the remaining routes in the target switch
528 return populateIpRulesForRouter(targetSw, subnets, destSw1, destSw2, nextHops);
Charles Chanc22cef32016-04-29 14:38:22 -0700529 }
sangho80f11cb2015-04-01 13:05:26 -0700530
Charles Chanc22cef32016-04-29 14:38:22 -0700531 /**
Charles Chand66d6712018-03-29 16:03:41 -0700532 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700533 *
Charles Chand66d6712018-03-29 16:03:41 -0700534 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700535 * @param subnets subnet being removed
536 * @return true if all rules are removed successfully, false otherwise
537 */
Charles Chand66d6712018-03-29 16:03:41 -0700538 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700539 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700540 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700541 return false;
542 }
543 }
sangho80f11cb2015-04-01 13:05:26 -0700544 return true;
545 }
546
547 /**
piera9941192019-04-24 16:12:47 +0200548 * Populates IP flow rules for a set of IP prefix in the target device.
549 * The prefix are reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700550 *
Saurav Das261c3002017-06-13 15:35:54 -0700551 * @param targetSw target device ID to set the rules
piera9941192019-04-24 16:12:47 +0200552 * @param subnets the set of IP prefix
Saurav Das261c3002017-06-13 15:35:54 -0700553 * @param destSw1 destination switch where the prefixes are reachable
554 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
555 * Should be null if there is no paired destination switch (by config)
556 * or if the given prefixes are reachable only via destSw1
557 * @param nextHops map of destination switches and their next-hops.
558 * Should only contain destination switches that are
559 * actually meant to be routed to. If destSw2 is null, there
560 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700561 * @return true if all rules are set successfully, false otherwise
562 */
piera9941192019-04-24 16:12:47 +0200563 private boolean populateIpRulesForRouter(DeviceId targetSw,
564 Set<IpPrefix> subnets,
565 DeviceId destSw1, DeviceId destSw2,
566 Map<DeviceId, Set<DeviceId>> nextHops) {
567 // pre-compute the needed information
568 int segmentIdIPv41, segmentIdIPv42 = -1;
569 int segmentIdIPv61, segmentIdIPv62 = -1;
570 TrafficTreatment treatment = null;
571 DestinationSet dsIPv4, dsIPv6;
572 TrafficSelector metaIpv4Selector, metaIpv6Selector = null;
573 int nextIdIPv4, nextIdIPv6, nextId;
574 TrafficSelector selector;
575 // start with MPLS SIDs
Charles Chan319d1a22015-11-03 10:42:14 -0800576 try {
piera9941192019-04-24 16:12:47 +0200577 segmentIdIPv41 = config.getIPv4SegmentId(destSw1);
578 segmentIdIPv61 = config.getIPv6SegmentId(destSw1);
579 if (destSw2 != null) {
580 segmentIdIPv42 = config.getIPv4SegmentId(destSw2);
581 segmentIdIPv62 = config.getIPv6SegmentId(destSw2);
Pier Ventreadb4ae62016-11-23 09:57:42 -0800582 }
Charles Chan319d1a22015-11-03 10:42:14 -0800583 } catch (DeviceConfigNotFoundException e) {
584 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
585 return false;
586 }
piera9941192019-04-24 16:12:47 +0200587 // build the IPv4 and IPv6 destination set
Saurav Das261c3002017-06-13 15:35:54 -0700588 if (destSw2 == null) {
589 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800590 // If the next hop is the same as the final destination, then MPLS
591 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700592 Set<DeviceId> nhd1 = nextHops.get(destSw1);
593 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
piera9941192019-04-24 16:12:47 +0200594 dsIPv4 = DestinationSet.createTypePushNone(destSw1);
595 dsIPv6 = DestinationSet.createTypePushNone(destSw1);
596 treatment = DefaultTrafficTreatment.builder()
597 .immediate()
598 .decNwTtl()
599 .build();
Saurav Das261c3002017-06-13 15:35:54 -0700600 } else {
piera9941192019-04-24 16:12:47 +0200601 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1);
602 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700603 }
604 } else {
605 // dst pair - IP rules for dst-pairs are always from other edge nodes
606 // the destination set needs to have both destinations, even if there
607 // are no next hops to one of them
piera9941192019-04-24 16:12:47 +0200608 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1, segmentIdIPv42, destSw2);
609 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1, segmentIdIPv62, destSw2);
sangho80f11cb2015-04-01 13:05:26 -0700610 }
611
Saurav Das4c35fc42015-11-20 15:27:53 -0800612 // setup metadata to pass to nextObjective - indicate the vlan on egress
613 // if needed by the switch pipeline. Since neighbor sets are always to
614 // other neighboring routers, there is no subnet assigned on those ports.
piera9941192019-04-24 16:12:47 +0200615 metaIpv4Selector = buildIpv4Selector()
616 .matchVlanId(srManager.getDefaultInternalVlan())
617 .build();
618 metaIpv6Selector = buildIpv6Selector()
619 .matchVlanId(srManager.getDefaultInternalVlan())
620 .build();
621 // get the group handler of the target switch
Saurav Das261c3002017-06-13 15:35:54 -0700622 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700623 if (grpHandler == null) {
624 log.warn("populateIPRuleForRouter: groupHandler for device {} "
piera9941192019-04-24 16:12:47 +0200625 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700626 return false;
627 }
piera9941192019-04-24 16:12:47 +0200628 // get next id
629 nextIdIPv4 = grpHandler.getNextObjectiveId(dsIPv4, nextHops, metaIpv4Selector, false);
630 if (nextIdIPv4 <= 0) {
631 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv4);
sangho2165d222015-05-01 09:38:25 -0700632 return false;
633 }
piera9941192019-04-24 16:12:47 +0200634 nextIdIPv6 = grpHandler.getNextObjectiveId(dsIPv6, nextHops, metaIpv6Selector, false);
635 if (nextIdIPv6 <= 0) {
636 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv6);
637 return false;
Charles Chanf4586112015-11-09 16:37:23 -0800638 }
piera9941192019-04-24 16:12:47 +0200639 // build all the flow rules and send to the device
640 for (IpPrefix subnet : subnets) {
641 selector = buildIpSelectorFromIpPrefix(subnet).build();
642 if (subnet.isIp4()) {
643 nextId = nextIdIPv4;
644 } else {
645 nextId = nextIdIPv6;
646 }
647 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
648 .builder()
649 .fromApp(srManager.appId)
650 .makePermanent()
651 .nextStep(nextId)
652 .withSelector(selector)
653 .withPriority(getPriorityFromPrefix(subnet))
654 .withFlag(ForwardingObjective.Flag.SPECIFIC);
655 if (treatment != null) {
656 fwdBuilder.withTreatment(treatment);
657 }
658 log.debug("Installing {} forwarding objective for router IP/subnet {} "
659 + "in switch {} with nextId: {}", subnet.isIp4() ? "IPv4" : "IPv6",
660 subnet, targetSw, nextId);
661 ObjectiveContext context = new DefaultObjectiveContext(
662 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
663 subnet, targetSw),
664 (objective, error) -> log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
665 subnet, error, targetSw));
666 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
667 }
668 rulePopulationCounter.addAndGet(subnets.size());
sangho80f11cb2015-04-01 13:05:26 -0700669 return true;
670 }
671
sangho80f11cb2015-04-01 13:05:26 -0700672 /**
Charles Chand66d6712018-03-29 16:03:41 -0700673 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700674 *
Charles Chand66d6712018-03-29 16:03:41 -0700675 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700676 * @param ipPrefix the IP address of the destination router
677 * @return true if all rules are removed successfully, false otherwise
678 */
Charles Chand66d6712018-03-29 16:03:41 -0700679 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800680 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700681 TrafficSelector selector = sbuilder.build();
682 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
683
684 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
685 .builder()
686 .fromApp(srManager.appId)
687 .makePermanent()
688 .withSelector(selector)
689 .withTreatment(dummyTreatment)
690 .withPriority(getPriorityFromPrefix(ipPrefix))
691 .withFlag(ForwardingObjective.Flag.SPECIFIC);
692
Charles Chand66d6712018-03-29 16:03:41 -0700693 ObjectiveContext context = new DefaultObjectiveContext(
694 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
695 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
696 ipPrefix, targetSw, error));
697 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700698
699 return true;
700 }
701
702 /**
Saurav Das97241862018-02-14 14:14:54 -0800703 * Populates MPLS flow rules in the target device to point towards the
704 * destination device.
705 *
706 * @param targetSwId target device ID of the switch to set the rules
707 * @param destSwId destination switch device ID
708 * @param nextHops next hops switch ID list
709 * @param routerIp the router ip of the destination switch
710 * @return true if all rules are set successfully, false otherwise
711 */
712 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
713 Set<DeviceId> nextHops, IpAddress routerIp) {
714 int segmentId;
715 try {
716 if (routerIp.isIp4()) {
717 segmentId = config.getIPv4SegmentId(destSwId);
718 } else {
719 segmentId = config.getIPv6SegmentId(destSwId);
720 }
721 } catch (DeviceConfigNotFoundException e) {
722 log.warn(e.getMessage() + " Aborting populateMplsRule.");
723 return false;
724 }
725
726 List<ForwardingObjective> fwdObjs = new ArrayList<>();
727 Collection<ForwardingObjective> fwdObjsMpls;
728 // Generates the transit rules used by the standard "routing".
729 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
730 routerIp, true);
731 if (fwdObjsMpls.isEmpty()) {
732 return false;
733 }
734 fwdObjs.addAll(fwdObjsMpls);
735
736 // Generates the transit rules used by the MPLS Pwaas.
737 int pwSrLabel;
738 try {
739 pwSrLabel = config.getPWRoutingLabel(destSwId);
740 } catch (DeviceConfigNotFoundException e) {
741 log.warn(e.getMessage()
742 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
743 return false;
744 }
745 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
746 routerIp, false);
747 if (fwdObjsMpls.isEmpty()) {
748 return false;
749 }
750 fwdObjs.addAll(fwdObjsMpls);
751
752 for (ForwardingObjective fwdObj : fwdObjs) {
753 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
754 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
755 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
756 rulePopulationCounter.incrementAndGet();
757 }
758
759 return true;
760 }
761
762 /**
763 * Differentiates between popping and swapping labels when building an MPLS
764 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700765 *
766 * @param targetSwId the target sw
767 * @param destSwId the destination sw
768 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800769 * @param segmentId the segmentId to match representing the destination
770 * switch
771 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700772 * @return a collection of fwdobjective
773 */
Saurav Das261c3002017-06-13 15:35:54 -0700774 private Collection<ForwardingObjective> handleMpls(
775 DeviceId targetSwId,
776 DeviceId destSwId,
777 Set<DeviceId> nextHops,
778 int segmentId,
779 IpAddress routerIp,
780 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700781
782 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
783 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800784 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700785 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
786 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
787 sbuilder.matchMplsBos(isMplsBos);
788 TrafficSelector selector = sbuilder.build();
789
790 // setup metadata to pass to nextObjective - indicate the vlan on egress
791 // if needed by the switch pipeline. Since mpls next-hops are always to
792 // other neighboring routers, there is no subnet assigned on those ports.
793 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700794 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre229fd0b2016-10-31 16:49:19 -0700795
796 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
797 // If the next hop is the destination router for the segment, do pop
798 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700799 + "label {} in switch {} with pop to next-hops {}",
800 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700801 ForwardingObjective.Builder fwdObjNoBosBuilder =
802 getMplsForwardingObjective(targetSwId,
803 nextHops,
804 true,
805 isMplsBos,
806 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700807 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800808 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700809 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700810 // Error case, we cannot handle, exit.
811 if (fwdObjNoBosBuilder == null) {
812 return Collections.emptyList();
813 }
814 fwdObjBuilders.add(fwdObjNoBosBuilder);
815
816 } else {
Saurav Das97241862018-02-14 14:14:54 -0800817 // next hop is not destination, irrespective of the number of next
818 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700819 log.debug("Installing MPLS forwarding objective for "
820 + "label {} in switch {} without pop to next-hops {}",
821 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700822 ForwardingObjective.Builder fwdObjNoBosBuilder =
823 getMplsForwardingObjective(targetSwId,
824 nextHops,
825 false,
826 isMplsBos,
827 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700828 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800829 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700830 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700831 // Error case, we cannot handle, exit.
832 if (fwdObjNoBosBuilder == null) {
833 return Collections.emptyList();
834 }
835 fwdObjBuilders.add(fwdObjNoBosBuilder);
836
837 }
838
839 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
840 // We add the final property to the fwdObjs.
841 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700842 ((Builder) ((Builder) fwdObjBuilder
843 .fromApp(srManager.appId)
844 .makePermanent())
845 .withSelector(selector)
846 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
847 .withFlag(ForwardingObjective.Flag.SPECIFIC);
848
849 ObjectiveContext context = new DefaultObjectiveContext(
850 (objective) ->
851 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
852 objective.id(), segmentId, targetSwId),
853 (objective, error) ->
854 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
855 objective.id(), segmentId, error, targetSwId));
856
857 ForwardingObjective fob = fwdObjBuilder.add(context);
858 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700859 }
860
861 return fwdObjs;
862 }
863
864 /**
Saurav Das97241862018-02-14 14:14:54 -0800865 * Returns a Forwarding Objective builder for the MPLS rule that references
866 * the desired Next Objective. Creates a DestinationSet that allows the
867 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700868 *
Saurav Das97241862018-02-14 14:14:54 -0800869 * @param targetSw the target sw
870 * @param nextHops the set of next hops
871 * @param phpRequired true if penultimate-hop-popping is required
872 * @param isBos true if matched label is bottom-of-stack
873 * @param meta metadata for creating next objective
874 * @param routerIp the router ip representing the destination switch
875 * @param destSw the destination sw
876 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700877 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800878 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700879 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800880 Set<DeviceId> nextHops,
881 boolean phpRequired,
882 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800883 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700884 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800885 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700886 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800887
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700888 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
889 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700890
891 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800892 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700893 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800894 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700895 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800896 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700897 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700898 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700899 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800900 if (routerIp.isIp4()) {
901 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
902 } else {
903 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
904 }
905 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800906 // standard case -> BoS == True; pop results in IP packet and forwarding
907 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700908 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700909 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800910 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
911 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800912 // double-label case -> BoS == False, pop results in MPLS packet
913 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700914 ds = DestinationSet.createTypePopNotBos(destSw);
915 if (!srManager.getMplsEcmp()) {
916 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800917 }
sangho80f11cb2015-04-01 13:05:26 -0700918 }
919 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800920 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800921 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700922 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800923 // swap results in MPLS packet with same BoS bit regardless of bit value
924 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700925 // differentiate here between swap with not bos or swap with bos
926 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
927 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
928 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800929 simple = true;
930 }
sangho80f11cb2015-04-01 13:05:26 -0700931 }
932
Saurav Das4c35fc42015-11-20 15:27:53 -0800933 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800934 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
935 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700936 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
937 if (gh == null) {
938 log.warn("getNextObjectiveId query - groupHandler for device {} "
939 + "not found", targetSw);
940 return null;
941 }
Saurav Das97241862018-02-14 14:14:54 -0800942
Saurav Das261c3002017-06-13 15:35:54 -0700943 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
944 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800945 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800946 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800947 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800948 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700949 } else {
Saurav Das97241862018-02-14 14:14:54 -0800950 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
951 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -0700952 }
953
Saurav Das4c35fc42015-11-20 15:27:53 -0800954 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700955 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -0700956 }
957
958 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -0700959 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -0700960 * dstMac corresponding to the router's MAC address. For those pipelines
961 * that need to internally assign vlans to untagged packets, this method
962 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -0700963 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -0800964 * Note that the vlan assignment and filter programming should only be done by
965 * the master for a switch. This method is typically called at deviceAdd and
966 * programs filters only for the enabled ports of the device. For port-updates,
967 * that enable/disable ports after device add, singlePortFilter methods should
968 * be called.
sangho80f11cb2015-04-01 13:05:26 -0700969 *
Saurav Das9f1c42e2015-10-23 10:51:11 -0700970 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -0800971 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -0700972 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700973 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -0700974 log.debug("Installing per-port filtering objective for untagged "
975 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800976
Saurav Das07c74602016-04-27 18:35:50 -0700977 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -0800978 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -0700979 log.warn("Device {} ports not available. Unable to add MacVlan filters",
980 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -0800981 return null;
Saurav Das07c74602016-04-27 18:35:50 -0700982 }
Saurav Dasf9332192017-02-18 14:05:44 -0800983 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -0700984 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -0700985 if (!port.isEnabled()) {
986 disabledPorts++;
987 continue;
988 }
Charles Chan43be46b2017-02-26 22:59:35 -0800989 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -0800990 filteredPorts++;
991 } else {
992 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -0700993 }
Saurav Das7c305372015-10-28 12:39:42 -0700994 }
Charles Chan077314e2017-06-22 14:27:17 -0700995 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -0800996 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan9d2dd552018-06-19 20:56:33 -0700997 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Dasf9332192017-02-18 14:05:44 -0800998 }
999
1000 /**
Charles Chan43be46b2017-02-26 22:59:35 -08001001 * Creates or removes filtering objectives for a single port. Should only be
1002 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -08001003 *
1004 * @param deviceId device identifier
1005 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -08001006 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -08001007 * @return true if no errors occurred during the build of the filtering objective
1008 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001009 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -08001010 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -07001011 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
1012 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
1013 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -08001014
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001015 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -08001016 if (taggedVlans.size() != 0) {
1017 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -07001018 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan43be46b2017-02-26 22:59:35 -08001019 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan90772a72017-02-08 15:52:08 -08001020 return false;
1021 }
1022 if (nativeVlan != null) {
1023 // Filter for native vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001024 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001025 return false;
1026 }
1027 }
1028 } else if (untaggedVlan != null) {
1029 // Filter for untagged vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001030 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001031 return false;
1032 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001033 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001034 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das9bf49582018-08-13 15:34:26 -07001035 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1036 srManager.getDefaultInternalVlan(),
1037 install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001038 return false;
1039 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001040 // Filter for receiveing pseudowire traffic
Saurav Das9bf49582018-08-13 15:34:26 -07001041 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1042 srManager.getPwTransportVlan(),
1043 install)) {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001044 return false;
1045 }
Charles Chan90772a72017-02-08 15:52:08 -08001046 }
1047 return true;
1048 }
1049
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001050 /**
1051 * Updates filtering objectives for a single port. Should only be called by
1052 * the master for a switch
1053 * @param deviceId device identifier
1054 * @param portNum port identifier for port to be filtered
1055 * @param pushVlan true to push vlan, false otherwise
1056 * @param vlanId vlan identifier
1057 * @param install true to install the filtering objective, false to remove
1058 */
1059 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1060 boolean pushVlan, VlanId vlanId, boolean install) {
1061 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
1062 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1063 deviceId, portNum, vlanId);
1064 }
1065 }
1066
Charles Chan43be46b2017-02-26 22:59:35 -08001067 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1068 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001069 boolean doTMAC = true;
1070
1071 if (!pushVlan) {
1072 // Skip the tagged vlans belonging to an interface without an IP address
1073 Set<Interface> ifaces = srManager.interfaceService
1074 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1075 .stream()
1076 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1077 .collect(Collectors.toSet());
1078 if (!ifaces.isEmpty()) {
1079 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1080 vlanId, deviceId, portnum);
1081 doTMAC = false;
1082 }
1083 }
1084
1085 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Dasf9332192017-02-18 14:05:44 -08001086 if (fob == null) {
1087 // error encountered during build
1088 return false;
1089 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001090 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001091 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001092 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001093 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001094 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001095 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001096 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001097 if (install) {
1098 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1099 } else {
1100 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001101 }
Charles Chan90772a72017-02-08 15:52:08 -08001102 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001103 }
1104
Charles Chan90772a72017-02-08 15:52:08 -08001105 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001106 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Dasf9332192017-02-18 14:05:44 -08001107 MacAddress deviceMac;
1108 try {
1109 deviceMac = config.getDeviceMac(deviceId);
1110 } catch (DeviceConfigNotFoundException e) {
1111 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1112 return null;
1113 }
Saurav Dasf9332192017-02-18 14:05:44 -08001114 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001115
1116 if (doTMAC) {
1117 fob.withKey(Criteria.matchInPort(portnum))
1118 .addCondition(Criteria.matchEthDst(deviceMac))
1119 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1120 } else {
1121 fob.withKey(Criteria.matchInPort(portnum))
1122 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1123 }
Charles Chan90772a72017-02-08 15:52:08 -08001124
Charles Chan17ca2202017-12-19 19:55:57 -08001125 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1126
Charles Chan90772a72017-02-08 15:52:08 -08001127 if (pushVlan) {
1128 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001129 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001130 } else {
1131 fob.addCondition(Criteria.matchVlanId(vlanId));
1132 }
1133
Charles Chan17ca2202017-12-19 19:55:57 -08001134 // NOTE: Some switch hardware share the same filtering flow among different ports.
1135 // We use this metadata to let the driver know that there is no more enabled port
1136 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001137 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001138 tBuilder.wipeDeferred();
1139 }
1140
1141 fob.withMeta(tBuilder.build());
1142
Saurav Dasf9332192017-02-18 14:05:44 -08001143 fob.permit().fromApp(srManager.appId);
1144 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001145 }
1146
1147 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001148 * Creates or removes filtering objectives for a double-tagged host on a port.
1149 *
1150 * @param deviceId device identifier
1151 * @param portNum port identifier for port to be filtered
1152 * @param outerVlan outer VLAN ID
1153 * @param innerVlan inner VLAN ID
1154 * @param install true to install the filtering objective, false to remove
1155 */
1156 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1157 VlanId innerVlan, boolean install) {
Daniele Moro8fc37b42019-10-29 18:48:35 -07001158 // We should trigger the removal of double tagged rules only when removing
1159 // the filtering objective and no other hosts are connected to the same device port.
1160 boolean cleanupDoubleTaggedRules = srManager.hostService
1161 .getConnectedHosts(new ConnectPoint(deviceId, portNum)).size() == 0 && !install;
1162 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum,
1163 outerVlan, innerVlan,
1164 cleanupDoubleTaggedRules);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001165 if (fob == null) {
1166 // error encountered during build
1167 return;
1168 }
1169 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1170 install ? "Installing" : "Removing", deviceId, portNum);
1171 ObjectiveContext context = new DefaultObjectiveContext(
1172 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1173 install ? "installed" : "removed"),
1174 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1175 install ? "install" : "remove", deviceId, portNum, error));
1176 if (install) {
1177 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1178 } else {
1179 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1180 }
1181 }
1182
1183 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001184 VlanId outerVlan, VlanId innerVlan,
1185 boolean cleanupDoubleTaggedRules) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001186 MacAddress deviceMac;
1187 try {
1188 deviceMac = config.getDeviceMac(deviceId);
1189 } catch (DeviceConfigNotFoundException e) {
1190 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1191 return null;
1192 }
1193 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1194 // Outer vlan id match should be appeared before inner vlan id match.
1195 fob.withKey(Criteria.matchInPort(portNum))
1196 .addCondition(Criteria.matchEthDst(deviceMac))
1197 .addCondition(Criteria.matchVlanId(outerVlan))
Daniele Moro998f2df2019-07-12 17:58:54 -07001198 .addCondition(Criteria.matchInnerVlanId(innerVlan))
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001199 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1200
1201 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1202 // Pop outer vlan
1203 tBuilder.popVlan();
1204
Andreas Pantelopoulos59bd97e2018-06-28 17:06:14 -07001205 // special metadata for driver
1206 if (cleanupDoubleTaggedRules) {
1207 tBuilder.writeMetadata(CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES, DOUBLE_TAGGED_METADATA_MASK);
1208 } else {
1209 tBuilder.writeMetadata(0, DOUBLE_TAGGED_METADATA_MASK);
1210 }
1211
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001212 // NOTE: Some switch hardware share the same filtering flow among different ports.
1213 // We use this metadata to let the driver know that there is no more enabled port
1214 // within the same VLAN on this device.
1215 if (noMoreEnabledPort(deviceId, outerVlan)) {
1216 tBuilder.wipeDeferred();
1217 }
1218
1219 fob.withMeta(tBuilder.build());
1220
1221 fob.permit().fromApp(srManager.appId);
1222 return fob;
1223 }
1224
1225 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001226 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001227 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001228 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001229 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001230 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001231 * @param deviceId the switch dpid for the router
sangho80f11cb2015-04-01 13:05:26 -07001232 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001233 void populateIpPunts(DeviceId deviceId) {
Saurav Das261c3002017-06-13 15:35:54 -07001234 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001235 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001236 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001237 routerIpv4 = config.getRouterIpv4(deviceId);
1238 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001239 routerLinkLocalIpv6 = Ip6Address.valueOf(
1240 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1241
Saurav Das261c3002017-06-13 15:35:54 -07001242 if (config.isPairedEdge(deviceId)) {
1243 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1244 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1245 }
Charles Chan319d1a22015-11-03 10:42:14 -08001246 } catch (DeviceConfigNotFoundException e) {
Charles Chan18fa4252017-02-08 16:10:40 -08001247 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001248 return;
1249 }
1250
Saurav Dasc28b3432015-10-30 17:45:38 -07001251 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1252 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1253 deviceId);
1254 return;
1255 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001256 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1257 allIps.add(routerIpv4);
1258 if (routerIpv6 != null) {
1259 allIps.add(routerIpv6);
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001260 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001261 }
Saurav Das261c3002017-06-13 15:35:54 -07001262 if (pairRouterIpv4 != null) {
1263 allIps.add(pairRouterIpv4);
1264 }
1265 if (pairRouterIpv6 != null) {
1266 allIps.add(pairRouterIpv6);
1267 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001268 for (IpAddress ipaddr : allIps) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001269 populateSingleIpPunts(deviceId, ipaddr);
1270 }
1271 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001272
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001273 /**
1274 * Creates a forwarding objective to punt all IP packets, destined to the
1275 * specified IP address, which should be router's port IP address.
1276 *
1277 * @param deviceId the switch dpid for the router
1278 * @param ipAddress the IP address of the router's port
1279 */
1280 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1281 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1282 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1283
1284 srManager.packetService.requestPackets(sbuilder.build(),
1285 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1286 }
1287
1288 /**
1289 * Removes a forwarding objective to punt all IP packets, destined to the
1290 * specified IP address, which should be router's port IP address.
1291 *
1292 * @param deviceId the switch dpid for the router
1293 * @param ipAddress the IP address of the router's port
1294 */
1295 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1296 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1297 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1298
1299 try {
1300 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1301 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1302 srManager.packetService.cancelPackets(sbuilder.build(),
1303 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1304 }
1305 } catch (DeviceConfigNotFoundException e) {
1306 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das9f1c42e2015-10-23 10:51:11 -07001307 }
sangho80f11cb2015-04-01 13:05:26 -07001308 }
1309
piera9941192019-04-24 16:12:47 +02001310 // Method for building an IPv4 selector
1311 private TrafficSelector.Builder buildIpv4Selector() {
1312 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1313 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1314 return selectorBuilder;
1315 }
1316
1317 // Method for building an IPv6 selector
1318 private TrafficSelector.Builder buildIpv6Selector() {
1319 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1320 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1321 return selectorBuilder;
1322 }
1323
1324 // Method for building an IPv4 or IPv6 selector from an IP address
Pier Ventreadb4ae62016-11-23 09:57:42 -08001325 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1326 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1327 }
1328
piera9941192019-04-24 16:12:47 +02001329 // Method for building an IPv4 or IPv6 selector from an IP prefix
Pier Ventreadb4ae62016-11-23 09:57:42 -08001330 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1331 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001332 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001333 if (prefixToMatch.isIp4()) {
1334 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1335 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1336 return selectorBuilder;
1337 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001338 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001339 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1340 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1341 return selectorBuilder;
1342 }
1343
1344 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001345 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1346 * Furthermore, these are applied only by the master instance. Deferred actions
1347 * are not cleared such that packets can be flooded in the cross connect use case
1348 *
1349 * @param deviceId the switch dpid for the router
1350 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001351 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001352 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001353 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1354 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1355 deviceId);
1356 return;
1357 }
1358
Charles Chan3ed34d82017-06-22 18:03:14 -07001359 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001360 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001361 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001362 .add(new ObjectiveContext() {
1363 @Override
1364 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001365 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001366 deviceId, error);
1367 }
1368 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001369 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001370
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001371 if (isIpv6Configured(deviceId)) {
1372 // We punt all NDP packets towards the controller.
1373 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1374 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1375 @Override
1376 public void onError(Objective objective, ObjectiveError error) {
1377 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1378 deviceId, error);
1379 }
1380 });
1381 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan051490d2018-01-11 11:48:18 -08001382 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001383 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001384
Saurav Dasec683dc2018-04-27 18:42:30 -07001385 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001386 ForwardingObjective pairFwdObj;
1387 // Do not punt ARP packets from pair port
1388 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1389 .add(new ObjectiveContext() {
1390 @Override
1391 public void onError(Objective objective, ObjectiveError error) {
1392 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1393 deviceId, error);
1394 }
1395 });
1396 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1397
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001398 if (isIpv6Configured(deviceId)) {
1399 // Do not punt NDP packets from pair port
1400 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1401 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan3ed34d82017-06-22 18:03:14 -07001402 @Override
1403 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001404 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan3ed34d82017-06-22 18:03:14 -07001405 deviceId, error);
1406 }
1407 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001408 srManager.flowObjectiveService.forward(deviceId, obj);
1409 });
1410
1411 // Do not forward DAD packets from pair port
1412 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1413 .add(new ObjectiveContext() {
1414 @Override
1415 public void onError(Objective objective, ObjectiveError error) {
1416 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1417 deviceId, error);
1418 }
1419 });
1420 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1421 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001422 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001423 }
1424
Charles Chan3ed34d82017-06-22 18:03:14 -07001425 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1426 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001427 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001428 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001429 .withSelector(selector)
1430 .fromApp(srManager.appId)
1431 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001432 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001433 .makePermanent();
1434 }
1435
Charles Chan3ed34d82017-06-22 18:03:14 -07001436 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001437 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1438 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001439 if (port != null) {
1440 sBuilder.matchInPort(port);
1441 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001442
Charles Chan3ed34d82017-06-22 18:03:14 -07001443 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1444 if (punt) {
1445 tBuilder.punt();
1446 }
1447 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001448 }
1449
Charles Chan051490d2018-01-11 11:48:18 -08001450 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1451 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001452
Charles Chan051490d2018-01-11 11:48:18 -08001453 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1454 .forEach(type -> {
1455 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1456 sBuilder.matchEthType(TYPE_IPV6)
1457 .matchIPProtocol(PROTOCOL_ICMP6)
1458 .matchIcmpv6Type(type);
1459 if (port != null) {
1460 sBuilder.matchInPort(port);
1461 }
1462
1463 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1464 if (punt) {
1465 tBuilder.punt();
1466 }
1467
1468 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1469 });
1470
1471 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001472 }
1473
1474 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1475 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1476 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001477 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1478 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1479 // .matchIPProtocol(PROTOCOL_ICMP6)
1480 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001481 if (port != null) {
1482 sBuilder.matchInPort(port);
1483 }
1484
1485 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1486 tBuilder.wipeDeferred();
1487 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001488 }
1489
1490 /**
Charles Chan155ec442018-09-16 14:30:19 -07001491 * Block given prefix in routing table.
Charles Chanf4586112015-11-09 16:37:23 -08001492 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001493 * @param address the address to block
1494 * @param deviceId switch ID to set the rules
1495 */
1496 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1497 updateDefaultRouteBlackhole(deviceId, address, true);
1498 }
1499
1500 /**
Charles Chan155ec442018-09-16 14:30:19 -07001501 * Unblock given prefix in routing table.
Andrea Campanella60ce2222018-04-30 11:48:55 +02001502 *
1503 * @param address the address to block
1504 * @param deviceId switch ID to set the rules
1505 */
1506 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1507 updateDefaultRouteBlackhole(deviceId, address, false);
1508 }
1509
1510 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1511 try {
1512 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1513
1514 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1515 if (address.isIp4()) {
1516 sbuilder.matchIPDst(address);
1517 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1518 } else {
1519 sbuilder.matchIPv6Dst(address);
1520 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1521 }
1522
1523 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
Andrea Campanella60ce2222018-04-30 11:48:55 +02001524 tBuilder.wipeDeferred();
1525
1526 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1527 fob.withFlag(Flag.SPECIFIC)
1528 .withSelector(sbuilder.build())
1529 .withTreatment(tBuilder.build())
1530 .withPriority(getPriorityFromPrefix(address))
1531 .fromApp(srManager.appId)
1532 .makePermanent();
1533
1534 log.debug("{} blackhole forwarding objectives for dev: {}",
1535 install ? "Installing" : "Removing", deviceId);
1536 ObjectiveContext context = new DefaultObjectiveContext(
1537 (objective) -> log.debug("Forward for {} {}", deviceId,
1538 install ? "installed" : "removed"),
1539 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1540 install ? "install" : "remove", deviceId, error));
1541 if (install) {
1542 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1543 } else {
1544 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1545 }
1546 }
1547 } catch (DeviceConfigNotFoundException e) {
1548 log.info("Not populating blackhole for un-configured device {}", deviceId);
1549 }
1550
1551 }
1552
1553 /**
1554 * Populates a forwarding objective to send packets that miss other high
1555 * priority Bridging Table entries to a group that contains all ports of
1556 * its subnet.
1557 *
Charles Chanf4586112015-11-09 16:37:23 -08001558 * @param deviceId switch ID to set the rules
1559 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001560 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001561 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001562 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001563 });
1564 }
1565
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001566 /**
1567 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1568 * @param deviceId switch ID to set the rule
1569 * @param vlanId vlan ID to specify the subnet
1570 * @param install true to install the rule, false to revoke the rule
1571 */
1572 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1573 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1574
1575 if (nextId < 0) {
1576 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1577 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1578 return;
1579 }
1580
1581 // Driver should treat objective with MacAddress.NONE as the
1582 // subnet broadcast rule
1583 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1584 sbuilder.matchVlanId(vlanId);
1585 sbuilder.matchEthDst(MacAddress.NONE);
1586
1587 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1588 fob.withFlag(Flag.SPECIFIC)
1589 .withSelector(sbuilder.build())
1590 .nextStep(nextId)
1591 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1592 .fromApp(srManager.appId)
1593 .makePermanent();
1594 ObjectiveContext context = new DefaultObjectiveContext(
1595 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1596 (objective, error) ->
1597 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1598
1599 if (install) {
1600 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1601 } else {
1602 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1603 }
1604 }
1605
Charles Chan82ab1932016-01-30 23:22:37 -08001606 private int getPriorityFromPrefix(IpPrefix prefix) {
1607 return (prefix.isIp4()) ?
1608 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1609 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001610 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001611
1612 /**
1613 * Update Forwarding objective for each host and IP address connected to given port.
1614 * And create corresponding Simple Next objective if it does not exist.
1615 * Applied only when populating Forwarding objective
1616 * @param deviceId switch ID to set the rule
1617 * @param portNumber port number
1618 * @param prefix IP prefix of the route
1619 * @param hostMac MAC address of the next hop
1620 * @param vlanId Vlan ID of the port
1621 * @param popVlan true to pop vlan tag in TrafficTreatment
1622 * @param install true to populate the forwarding objective, false to revoke
1623 */
1624 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1625 VlanId vlanId, boolean popVlan, boolean install) {
1626 ForwardingObjective.Builder fob;
1627 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1628 MacAddress deviceMac;
1629 try {
1630 deviceMac = config.getDeviceMac(deviceId);
1631 } catch (DeviceConfigNotFoundException e) {
1632 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1633 return;
1634 }
1635
1636 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1637 tbuilder.deferred()
1638 .setEthDst(hostMac)
1639 .setEthSrc(deviceMac)
1640 .setOutput(portNumber);
1641
1642 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1643
1644 if (!popVlan) {
1645 tbuilder.setVlanId(vlanId);
1646 } else {
1647 mbuilder.matchVlanId(vlanId);
1648 }
1649
1650 // if the objective is to revoke an existing rule, and for some reason
1651 // the next-objective does not exist, then a new one should not be created
1652 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1653 tbuilder.build(), mbuilder.build(), install);
1654 if (portNextObjId == -1) {
1655 // Warning log will come from getPortNextObjective method
1656 return;
1657 }
1658
1659 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1660 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1661 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1662
1663 ObjectiveContext context = new DefaultObjectiveContext(
1664 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1665 (objective, error) ->
1666 log.warn("Failed to {} IP rule for route {}: {}",
1667 install ? "install" : "revoke", prefix, error));
1668 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1669
1670 if (!install) {
1671 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1672 if (grpHandler == null) {
1673 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1674 } else {
1675 // Remove L3UG for the given port and host
1676 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1677 }
1678 }
1679 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001680
1681 /**
1682 * Checks if there is other enabled port within the given VLAN on the given device.
1683 *
1684 * @param deviceId device ID
1685 * @param vlanId VLAN ID
1686 * @return true if there is no more port enabled within the given VLAN on the given device
1687 */
1688 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1689 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1690 .filter(Port::isEnabled)
1691 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1692 .collect(Collectors.toSet());
1693
1694 return enabledPorts.stream().noneMatch(cp ->
1695 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001696 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001697 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001698 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Saurav Das9bf49582018-08-13 15:34:26 -07001699 vlanId.equals(srManager.getDefaultInternalVlan())) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001700 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1701 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1702 );
1703 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001704
1705 /**
1706 * Returns a forwarding objective builder for egress forwarding rules.
1707 * <p>
1708 * The forwarding objective installs flow rules to egress pipeline to push
1709 * two vlan headers with given inner, outer vlan ids and outer tpid.
1710 *
1711 * @param portNumber port where the next hop attaches to
1712 * @param dummyVlanId vlan ID of the packet to match
1713 * @param innerVlan inner vlan ID of the next hop
1714 * @param outerVlan outer vlan ID of the next hop
1715 * @param outerTpid outer TPID of the next hop
1716 * @return forwarding objective builder
1717 */
1718 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1719 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1720 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1721 sbuilder.matchVlanId(dummyVlanId);
1722 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1723 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1724
1725 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1726 tbuilder.pushVlan(outerTpid);
1727 } else {
1728 tbuilder.pushVlan();
1729 }
1730
1731 tbuilder.setVlanId(outerVlan);
1732 return DefaultForwardingObjective.builder()
1733 .withSelector(sbuilder.build())
1734 .withTreatment(tbuilder.build())
1735 .fromApp(srManager.appId)
1736 .makePermanent()
1737 .withPriority(DEFAULT_PRIORITY)
1738 .withFlag(ForwardingObjective.Flag.EGRESS);
1739 }
1740
1741 /**
1742 * Populates IP rules for a route that has double-tagged next hop.
1743 *
1744 * @param deviceId device ID of the device that next hop attaches to
1745 * @param prefix IP prefix of the route
1746 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001747 * @param innerVlan inner Vlan ID of the next hop
1748 * @param outerVlan outer Vlan ID of the next hop
1749 * @param outerTpid outer TPID of the next hop
1750 * @param outPort port where the next hop attaches to
1751 */
Charles Chan61c086d2019-07-26 17:46:15 -07001752 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001753 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1754 ForwardingObjective.Builder fwdBuilder;
1755 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1756 prefix, deviceId, outPort);
1757
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001758 try {
Charles Chan61c086d2019-07-26 17:46:15 -07001759 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1760 true, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001761 } catch (DeviceConfigNotFoundException e) {
1762 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1763 return;
1764 }
1765 if (fwdBuilder == null) {
1766 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1767 deviceId, prefix);
1768 return;
1769 }
1770
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001771 int nextId = fwdBuilder.add().nextId();
1772 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1773 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001774 }, (objective, error) ->
1775 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1776 );
1777 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1778 rulePopulationCounter.incrementAndGet();
1779 }
1780
1781 /**
1782 * Revokes IP rules for a route that has double-tagged next hop.
1783 *
1784 * @param deviceId device ID of the device that next hop attaches to
1785 * @param prefix IP prefix of the route
1786 * @param hostMac MAC address of the next hop
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001787 * @param innerVlan inner Vlan ID of the next hop
1788 * @param outerVlan outer Vlan ID of the next hop
1789 * @param outerTpid outer TPID of the next hop
1790 * @param outPort port where the next hop attaches to
1791 */
1792 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
Charles Chan61c086d2019-07-26 17:46:15 -07001793 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1794 ForwardingObjective.Builder fwdBuilder;
1795 log.debug("Revoking direct routing entry for double-tagged host route {} at {}:{}",
1796 prefix, deviceId, outPort);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001797
Charles Chan61c086d2019-07-26 17:46:15 -07001798 try {
1799 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, outerVlan, outPort, innerVlan, outerTpid,
1800 true, true);
1801 } catch (DeviceConfigNotFoundException e) {
1802 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001803 return;
1804 }
Charles Chan61c086d2019-07-26 17:46:15 -07001805 if (fwdBuilder == null) {
1806 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1807 deviceId, prefix);
1808 return;
1809 }
1810
1811 int nextId = fwdBuilder.remove().nextId();
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001812 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
Charles Chan61c086d2019-07-26 17:46:15 -07001813 log.debug("Direct routing rule for double-tagged host route {} revoked. nextId={}", prefix, nextId);
1814
1815 // Try to remove next objective as well
1816 ImmutablePair<TrafficTreatment, TrafficSelector> treatmentAndMeta;
1817 try {
1818 treatmentAndMeta = getTreatmentAndMeta(deviceId, hostMac, outerVlan, outPort, innerVlan, outerTpid);
1819 } catch (DeviceConfigNotFoundException e) {
1820 log.error(e.getMessage() + " Aborting revokeDoubleTaggedRoute");
1821 return;
1822 }
1823
1824 if (treatmentAndMeta == null) {
1825 // Warning log will come from getTreatmentAndMeta method
1826 return;
1827 }
1828
1829 DefaultGroupHandler groupHandler = srManager.getGroupHandler(deviceId);
1830 if (groupHandler == null) {
1831 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: " +
1832 "group handler not found for {}", prefix, deviceId);
1833 return;
1834 }
1835 groupHandler.removeGroupFromPort(outPort, treatmentAndMeta.getLeft(), treatmentAndMeta.getRight());
1836
1837 }, (objective, error) ->
1838 log.warn("Failed to revoke direct routing rule for double-tagged host route {}: {}", prefix, error)
1839 );
1840 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001841 }
1842
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001843 /**
1844 * Checks whether the specified port has IP configuration or not.
1845 *
1846 * @param cp ConnectPoint to check the existance of IP configuration
1847 * @return true if the port has IP configuration; false otherwise.
1848 */
1849 private boolean hasIPConfiguration(ConnectPoint cp) {
1850 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1851 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1852 }
Saurav Das9bf49582018-08-13 15:34:26 -07001853
1854 /**
1855 * Updates filtering rules for unconfigured ports on all devices for which
1856 * this controller instance is master.
1857 *
1858 * @param pushVlan true if the filtering rule requires a push vlan action
1859 * @param oldVlanId the vlanId to be removed
1860 * @param newVlanId the vlanId to be added
1861 */
1862 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1863 VlanId newVlanId) {
1864 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1865 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1866 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1867 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1868 && p.isEnabled()) {
1869 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1870 oldVlanId, false);
1871 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1872 newVlanId, true);
1873 }
1874 }
1875 }
1876 }
1877 }
1878
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001879 private boolean isIpv6Configured(DeviceId deviceId) {
1880 boolean isIpv6Configured;
1881 try {
1882 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1883 } catch (DeviceConfigNotFoundException e) {
1884 isIpv6Configured = false;
1885 }
1886 return isIpv6Configured;
1887 }
sangho80f11cb2015-04-01 13:05:26 -07001888}