blob: de0eb58c650652f7e9d83ba710d659828d47ed9e [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;
Saurav Das4c35fc42015-11-20 15:27:53 -080020import org.onlab.packet.EthType;
sangho80f11cb2015-04-01 13:05:26 -070021import org.onlab.packet.Ethernet;
Charles Chanef8d12e2017-12-05 21:07:38 -080022import org.onlab.packet.IPv6;
sangho80f11cb2015-04-01 13:05:26 -070023import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080024import org.onlab.packet.Ip6Address;
25import org.onlab.packet.IpAddress;
sangho80f11cb2015-04-01 13:05:26 -070026import org.onlab.packet.IpPrefix;
27import org.onlab.packet.MacAddress;
sangho80f11cb2015-04-01 13:05:26 -070028import org.onlab.packet.MplsLabel;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070029import org.onlab.packet.VlanId;
Charles Chanb7f75ac2016-01-11 18:28:54 -080030import org.onosproject.net.ConnectPoint;
Saurav Das9bf49582018-08-13 15:34:26 -070031import org.onosproject.net.Device;
Charles Chan1eaf4802016-04-18 13:44:03 -070032import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080033import org.onosproject.net.flowobjective.Objective;
Charles Chan1eaf4802016-04-18 13:44:03 -070034import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigib9632ba2017-01-12 18:14:58 -080035import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -070036import org.onosproject.net.intf.Interface;
Charles Chan2d0bbcd2017-01-09 11:45:08 -080037import org.onosproject.net.packet.PacketPriority;
Charles Chan319d1a22015-11-03 10:42:14 -080038import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
39import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070040import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das261c3002017-06-13 15:35:54 -070041import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sangho80f11cb2015-04-01 13:05:26 -070042import org.onosproject.net.DeviceId;
Saurav Das7c305372015-10-28 12:39:42 -070043import org.onosproject.net.Port;
sangho80f11cb2015-04-01 13:05:26 -070044import org.onosproject.net.PortNumber;
sangho80f11cb2015-04-01 13:05:26 -070045import org.onosproject.net.flow.DefaultTrafficSelector;
46import org.onosproject.net.flow.DefaultTrafficTreatment;
sangho80f11cb2015-04-01 13:05:26 -070047import org.onosproject.net.flow.TrafficSelector;
48import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070049import org.onosproject.net.flow.criteria.Criteria;
50import org.onosproject.net.flowobjective.DefaultFilteringObjective;
51import org.onosproject.net.flowobjective.DefaultForwardingObjective;
52import org.onosproject.net.flowobjective.FilteringObjective;
53import org.onosproject.net.flowobjective.ForwardingObjective;
54import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
Saurav Das9f1c42e2015-10-23 10:51:11 -070055import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070056import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
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
sangho80f11cb2015-04-01 13:05:26 -070095 /**
96 * Creates a RoutingRulePopulator object.
97 *
Thomas Vachuska8a075092015-04-15 18:20:08 -070098 * @param srManager segment routing manager reference
sangho80f11cb2015-04-01 13:05:26 -070099 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700100 RoutingRulePopulator(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700101 this.srManager = srManager;
sangho9b169e32015-04-14 16:27:13 -0700102 this.config = checkNotNull(srManager.deviceConfiguration);
sanghofb7c7292015-04-13 15:15:58 -0700103 this.rulePopulationCounter = new AtomicLong(0);
psneha86e60d32019-03-26 06:31:41 -0400104 this.routeSimplifierUtils = new RouteSimplifierUtils(srManager);
sanghofb7c7292015-04-13 15:15:58 -0700105 }
106
107 /**
108 * Resets the population counter.
109 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700110 void resetCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700111 rulePopulationCounter.set(0);
112 }
113
114 /**
115 * Returns the number of rules populated.
Thomas Vachuska7cfc6202015-04-30 18:13:25 -0700116 *
117 * @return number of rules
sanghofb7c7292015-04-13 15:15:58 -0700118 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700119 long getCounter() {
sanghofb7c7292015-04-13 15:15:58 -0700120 return rulePopulationCounter.get();
sangho80f11cb2015-04-01 13:05:26 -0700121 }
122
123 /**
Charles Chand66d6712018-03-29 16:03:41 -0700124 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
125 * output to given port.
126 *
127 * @param deviceId device ID
128 * @param port port
129 * @param mac mac address
130 * @param vlanId VLAN ID
131 */
132 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
133 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
134 if (fob == null) {
135 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
136 return;
137 }
138
139 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700140 (objective) -> log.debug("Brigding rule for {}/{} populated", mac, vlanId),
141 (objective, error) -> log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700142 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
143 }
144
145 /**
146 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
147 * output to given port.
148 *
149 * @param deviceId device ID
150 * @param port port
151 * @param mac mac address
152 * @param vlanId VLAN ID
153 */
154 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
155 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
156 if (fob == null) {
157 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
158 return;
159 }
160
161 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das5ff8a3c2018-04-07 16:51:09 -0700162 (objective) -> log.debug("Brigding rule for {}/{} revoked", mac, vlanId),
163 (objective, error) -> log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chand66d6712018-03-29 16:03:41 -0700164 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
165 }
166
167 /**
168 * Generates a forwarding objective builder for bridging rules.
169 * <p>
170 * The forwarding objective bridges packets destined to a given MAC to
171 * given port on given device.
172 *
173 * @param deviceId Device that host attaches to
174 * @param mac MAC address of the host
175 * @param hostVlanId VLAN ID of the host
176 * @param outport Port that host attaches to
177 * @param revoke true if forwarding objective is meant to revoke forwarding rule
178 * @return Forwarding objective builder
179 */
180 private ForwardingObjective.Builder bridgingFwdObjBuilder(
181 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
182 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan098ca202018-05-01 11:50:20 -0700183 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
184 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
185 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chand66d6712018-03-29 16:03:41 -0700186
187 // Create host selector
188 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
189 sbuilder.matchEthDst(mac);
190
191 // Create host treatment
192 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
193 tbuilder.immediate().setOutput(outport);
194
195 // Create host meta
196 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
197
198 // Adjust the selector, treatment and meta according to VLAN configuration
199 if (taggedVlans.contains(hostVlanId)) {
200 sbuilder.matchVlanId(hostVlanId);
201 mbuilder.matchVlanId(hostVlanId);
202 } else if (hostVlanId.equals(VlanId.NONE)) {
203 if (untaggedVlan != null) {
204 sbuilder.matchVlanId(untaggedVlan);
205 mbuilder.matchVlanId(untaggedVlan);
206 tbuilder.immediate().popVlan();
207 } else if (nativeVlan != null) {
208 sbuilder.matchVlanId(nativeVlan);
209 mbuilder.matchVlanId(nativeVlan);
210 tbuilder.immediate().popVlan();
211 } else {
212 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
213 "vlan config", mac, hostVlanId, connectPoint);
214 return null;
215 }
216 } else {
217 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
218 mac, hostVlanId, connectPoint);
219 return null;
220 }
221
222 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
223 // If the objective is to revoke an existing rule, and for some reason
224 // the next-objective does not exist, then a new one should not be created
225 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
226 tbuilder.build(), mbuilder.build(), !revoke);
227 if (portNextObjId == -1) {
228 // Warning log will come from getPortNextObjective method
229 return null;
230 }
231
232 return DefaultForwardingObjective.builder()
233 .withFlag(ForwardingObjective.Flag.SPECIFIC)
234 .withSelector(sbuilder.build())
235 .nextStep(portNextObjId)
236 .withPriority(100)
237 .fromApp(srManager.appId)
238 .makePermanent();
239 }
240
241 /**
242 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
243 * and hostMAC connected to given port, and output to given port only when
244 * vlan information is valid.
245 *
246 * @param deviceId device ID that host attaches to
247 * @param portNum port number that host attaches to
248 * @param hostMac mac address of the host connected to the switch port
249 * @param vlanId Vlan ID configured on the switch port
250 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
251 * @param install true to populate the objective, false to revoke
252 */
253 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
254 // revokeBridging and bridgingFwdObjBuilder.
255 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
256 VlanId vlanId, boolean popVlan, boolean install) {
257 // Create host selector
258 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
259 sbuilder.matchEthDst(hostMac);
260
261 // Create host meta
262 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
263
264 sbuilder.matchVlanId(vlanId);
265 mbuilder.matchVlanId(vlanId);
266
267 // Create host treatment
268 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
269 tbuilder.immediate().setOutput(portNum);
270
271 if (popVlan) {
272 tbuilder.immediate().popVlan();
273 }
274
275 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
276 tbuilder.build(), mbuilder.build(), install);
277 if (portNextObjId != -1) {
278 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
279 .withFlag(ForwardingObjective.Flag.SPECIFIC)
280 .withSelector(sbuilder.build())
281 .nextStep(portNextObjId)
282 .withPriority(100)
283 .fromApp(srManager.appId)
284 .makePermanent();
285
286 ObjectiveContext context = new DefaultObjectiveContext(
287 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
288 install ? "populated" : "revoked"),
289 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
290 install ? "populate" : "revoke", hostMac, vlanId, error));
291 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
292 } else {
293 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
294 }
295 }
296
297 /**
298 * Populates IP rules for a route that has direct connection to the switch.
299 * This method should not be invoked directly without going through DefaultRoutingHandler.
sangho80f11cb2015-04-01 13:05:26 -0700300 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700301 * @param deviceId device ID of the device that next hop attaches to
302 * @param prefix IP prefix of the route
303 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800304 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700305 * @param outPort port where the next hop attaches to
sangho80f11cb2015-04-01 13:05:26 -0700306 */
Charles Chan910be6a2017-08-23 14:46:43 -0700307 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan90772a72017-02-08 15:52:08 -0800308 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Saurav Das261c3002017-06-13 15:35:54 -0700309 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chanddac7fd2016-10-27 14:19:48 -0700310 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800311 ForwardingObjective.Builder fwdBuilder;
Charles Chan319d1a22015-11-03 10:42:14 -0800312 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700313 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
314 hostVlanId, outPort, false);
Charles Chan319d1a22015-11-03 10:42:14 -0800315 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -0700316 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan319d1a22015-11-03 10:42:14 -0800317 return;
318 }
Saurav Das07c74602016-04-27 18:35:50 -0700319 if (fwdBuilder == null) {
Saurav Das368cf212017-03-15 15:15:14 -0700320 log.warn("Aborting host routing table entry due "
Charles Chanddac7fd2016-10-27 14:19:48 -0700321 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das07c74602016-04-27 18:35:50 -0700322 return;
323 }
Charles Chan910be6a2017-08-23 14:46:43 -0700324
325 int nextId = fwdBuilder.add().nextId();
Charles Chan1eaf4802016-04-18 13:44:03 -0700326 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan910be6a2017-08-23 14:46:43 -0700327 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
328 prefix, nextId),
Charles Chan1eaf4802016-04-18 13:44:03 -0700329 (objective, error) ->
Saurav Das261c3002017-06-13 15:35:54 -0700330 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das368cf212017-03-15 15:15:14 -0700331 prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700332 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chanf4586112015-11-09 16:37:23 -0800333 rulePopulationCounter.incrementAndGet();
334 }
335
Charles Chanb7f75ac2016-01-11 18:28:54 -0800336 /**
Charles Chanddac7fd2016-10-27 14:19:48 -0700337 * Removes IP rules for a route when the next hop is gone.
Charles Chand66d6712018-03-29 16:03:41 -0700338 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800339 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700340 * @param deviceId device ID of the device that next hop attaches to
341 * @param prefix IP prefix of the route
342 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800343 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700344 * @param outPort port that next hop attaches to
Charles Chanb7f75ac2016-01-11 18:28:54 -0800345 */
Charles Chan910be6a2017-08-23 14:46:43 -0700346 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan90772a72017-02-08 15:52:08 -0800347 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Charles Chanddac7fd2016-10-27 14:19:48 -0700348 log.debug("Revoke IP table entry for route {} at {}:{}",
349 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800350 ForwardingObjective.Builder fwdBuilder;
351 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700352 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
353 hostVlanId, outPort, true);
Charles Chanf4586112015-11-09 16:37:23 -0800354 } catch (DeviceConfigNotFoundException e) {
355 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
356 return;
357 }
Charles Chanea702b12016-11-30 11:55:05 -0800358 if (fwdBuilder == null) {
359 log.warn("Aborting host routing table entries due "
360 + "to error for dev:{} route:{}", deviceId, prefix);
361 return;
362 }
Charles Chan1eaf4802016-04-18 13:44:03 -0700363 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chanddac7fd2016-10-27 14:19:48 -0700364 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chan1eaf4802016-04-18 13:44:03 -0700365 (objective, error) ->
Charles Chanddac7fd2016-10-27 14:19:48 -0700366 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700367 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chanf4586112015-11-09 16:37:23 -0800368 }
369
Charles Chanddac7fd2016-10-27 14:19:48 -0700370 /**
Charles Chan18fa4252017-02-08 16:10:40 -0800371 * Returns a forwarding objective builder for routing rules.
372 * <p>
373 * The forwarding objective routes packets destined to a given prefix to
374 * given port on given device with given destination MAC.
Charles Chanddac7fd2016-10-27 14:19:48 -0700375 *
376 * @param deviceId device ID
377 * @param prefix prefix that need to be routed
378 * @param hostMac MAC address of the nexthop
Charles Chan90772a72017-02-08 15:52:08 -0800379 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700380 * @param outPort port where the nexthop attaches to
Saurav Das2cb38292017-03-29 19:09:17 -0700381 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Charles Chanddac7fd2016-10-27 14:19:48 -0700382 * @return forwarding objective builder
383 * @throws DeviceConfigNotFoundException if given device is not configured
384 */
Charles Chan18fa4252017-02-08 16:10:40 -0800385 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700386 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700387 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
388 boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800389 throws DeviceConfigNotFoundException {
390 MacAddress deviceMac;
391 deviceMac = config.getDeviceMac(deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800392
Charles Chan90772a72017-02-08 15:52:08 -0800393 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700394 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
395 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
396 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700397
Charles Chan90772a72017-02-08 15:52:08 -0800398 // Create route selector
399 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
400
401 // Create route treatment
Charles Chanddac7fd2016-10-27 14:19:48 -0700402 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho27462c62015-05-14 00:39:53 -0700403 tbuilder.deferred()
404 .setEthDst(hostMac)
Charles Chan319d1a22015-11-03 10:42:14 -0800405 .setEthSrc(deviceMac)
sangho80f11cb2015-04-01 13:05:26 -0700406 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800407
Charles Chan90772a72017-02-08 15:52:08 -0800408 // Create route meta
409 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800410
Charles Chan90772a72017-02-08 15:52:08 -0800411 // Adjust the meta according to VLAN configuration
412 if (taggedVlans.contains(hostVlanId)) {
413 tbuilder.setVlanId(hostVlanId);
414 } else if (hostVlanId.equals(VlanId.NONE)) {
415 if (untaggedVlan != null) {
416 mbuilder.matchVlanId(untaggedVlan);
417 } else if (nativeVlan != null) {
418 mbuilder.matchVlanId(nativeVlan);
419 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700420 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
421 hostMac, hostVlanId, connectPoint);
422 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800423 }
424 } else {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700425 // Internally-assigned dummy VLAN id will be given as hostVlanId
426 // when destination is double-tagged.
427 VlanId vlanId = srManager.dummyVlanIdStore().get(
428 new DummyVlanIdStoreKey(connectPoint, prefix.address()));
429 if (vlanId != null && vlanId.equals(hostVlanId)) {
430 tbuilder.setVlanId(hostVlanId);
431 mbuilder.matchVlanId(VlanId.ANY);
432 } else {
433 log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
434 + " in tagged vlan", hostMac, hostVlanId, connectPoint);
435 return null;
436 }
Saurav Das07c74602016-04-27 18:35:50 -0700437 }
Saurav Das2cb38292017-03-29 19:09:17 -0700438 // if the objective is to revoke an existing rule, and for some reason
439 // the next-objective does not exist, then a new one should not be created
Charles Chan90772a72017-02-08 15:52:08 -0800440 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
Saurav Das2cb38292017-03-29 19:09:17 -0700441 tbuilder.build(), mbuilder.build(), !revoke);
Charles Chan90772a72017-02-08 15:52:08 -0800442 if (portNextObjId == -1) {
443 // Warning log will come from getPortNextObjective method
444 return null;
445 }
446
Charles Chanf4586112015-11-09 16:37:23 -0800447 return DefaultForwardingObjective.builder()
Charles Chan90772a72017-02-08 15:52:08 -0800448 .withSelector(sbuilder.build())
Saurav Das2d94d312015-11-24 23:21:05 -0800449 .nextStep(portNextObjId)
Charles Chanf4586112015-11-09 16:37:23 -0800450 .fromApp(srManager.appId).makePermanent()
Charles Chanddac7fd2016-10-27 14:19:48 -0700451 .withPriority(getPriorityFromPrefix(prefix))
Charles Chan82ab1932016-01-30 23:22:37 -0800452 .withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700453 }
454
455 /**
Saurav Das261c3002017-06-13 15:35:54 -0700456 * Populates IP flow rules for all the given prefixes reachable from the
457 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700458 *
Saurav Das261c3002017-06-13 15:35:54 -0700459 * @param targetSw switch where rules are to be programmed
460 * @param subnets subnets/prefixes being added
461 * @param destSw1 destination switch where the prefixes are reachable
462 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
463 * Should be null if there is no paired destination switch (by config)
464 * or if the given prefixes are reachable only via destSw1
465 * @param nextHops a map containing a set of next-hops for each destination switch.
466 * If destSw2 is not null, then this map must contain an
467 * entry for destSw2 with its next-hops from the targetSw
468 * (although the next-hop set may be empty in certain scenarios).
469 * If destSw2 is null, there should not be an entry in this
470 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700471 * @return true if all rules are set successfully, false otherwise
472 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700473 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700474 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
psneha86e60d32019-03-26 06:31:41 -0400475 // Get pair device of the target switch
476 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
477 // Route simplification will be off in case of the nexthop location at target switch is down
478 // (routing through spine case)
479 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
480 // Iterates over the routes
481 // If route simplification is enabled
482 // If the target device is another leaf in the network
483 if (srManager.routeSimplification && !routeSimplOff) {
484 for (IpPrefix subnet : subnets) {
485 // Skip route programming on the target device
486 // If route simplification applies
487 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
488 // XXX route simplification assumes that source of the traffic
489 // towards the nexthops are co-located with the nexthops. In different
490 // scenarios will not work properly.
491 continue;
492 }
493 // populate the route in the remaning scenarios
494 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
495 return false;
496 }
497 }
498 } else {
499 // Populate IP flow rules for all the subnets.
500 for (IpPrefix subnet : subnets) {
501 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
502 return false;
503 }
sangho80f11cb2015-04-01 13:05:26 -0700504 }
505 }
Charles Chanc22cef32016-04-29 14:38:22 -0700506 return true;
507 }
sangho80f11cb2015-04-01 13:05:26 -0700508
Charles Chanc22cef32016-04-29 14:38:22 -0700509 /**
Charles Chand66d6712018-03-29 16:03:41 -0700510 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700511 *
Charles Chand66d6712018-03-29 16:03:41 -0700512 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700513 * @param subnets subnet being removed
514 * @return true if all rules are removed successfully, false otherwise
515 */
Charles Chand66d6712018-03-29 16:03:41 -0700516 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700517 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700518 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700519 return false;
520 }
521 }
sangho80f11cb2015-04-01 13:05:26 -0700522 return true;
523 }
524
525 /**
Saurav Dase0237a32016-05-27 13:54:07 -0700526 * Populates IP flow rules for an IP prefix in the target device. The prefix
Saurav Das261c3002017-06-13 15:35:54 -0700527 * is reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700528 *
Saurav Das261c3002017-06-13 15:35:54 -0700529 * @param targetSw target device ID to set the rules
530 * @param ipPrefix the IP prefix
531 * @param destSw1 destination switch where the prefixes are reachable
532 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
533 * Should be null if there is no paired destination switch (by config)
534 * or if the given prefixes are reachable only via destSw1
535 * @param nextHops map of destination switches and their next-hops.
536 * Should only contain destination switches that are
537 * actually meant to be routed to. If destSw2 is null, there
538 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700539 * @return true if all rules are set successfully, false otherwise
540 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700541 private boolean populateIpRuleForRouter(DeviceId targetSw,
Saurav Das261c3002017-06-13 15:35:54 -0700542 IpPrefix ipPrefix, DeviceId destSw1,
543 DeviceId destSw2,
544 Map<DeviceId, Set<DeviceId>> nextHops) {
545 int segmentId1, segmentId2 = -1;
Charles Chan319d1a22015-11-03 10:42:14 -0800546 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800547 if (ipPrefix.isIp4()) {
Saurav Das261c3002017-06-13 15:35:54 -0700548 segmentId1 = config.getIPv4SegmentId(destSw1);
549 if (destSw2 != null) {
550 segmentId2 = config.getIPv4SegmentId(destSw2);
551 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800552 } else {
Saurav Das261c3002017-06-13 15:35:54 -0700553 segmentId1 = config.getIPv6SegmentId(destSw1);
554 if (destSw2 != null) {
555 segmentId2 = config.getIPv6SegmentId(destSw2);
556 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800557 }
Charles Chan319d1a22015-11-03 10:42:14 -0800558 } catch (DeviceConfigNotFoundException e) {
559 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
560 return false;
561 }
sangho80f11cb2015-04-01 13:05:26 -0700562
Pier Ventreadb4ae62016-11-23 09:57:42 -0800563 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanf4586112015-11-09 16:37:23 -0800564 TrafficSelector selector = sbuilder.build();
sangho80f11cb2015-04-01 13:05:26 -0700565
Charles Chanf4586112015-11-09 16:37:23 -0800566 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das261c3002017-06-13 15:35:54 -0700567 DestinationSet ds;
Charles Chanf4586112015-11-09 16:37:23 -0800568 TrafficTreatment treatment;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700569 DestinationSet.DestinationSetType dsType;
sangho80f11cb2015-04-01 13:05:26 -0700570
Saurav Das261c3002017-06-13 15:35:54 -0700571 if (destSw2 == null) {
572 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800573 // If the next hop is the same as the final destination, then MPLS
574 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700575 Set<DeviceId> nhd1 = nextHops.get(destSw1);
576 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
577 tbuilder.immediate().decNwTtl();
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700578 ds = DestinationSet.createTypePushNone(destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700579 treatment = tbuilder.build();
580 } else {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700581 ds = DestinationSet.createTypePushBos(segmentId1, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700582 treatment = null;
583 }
584 } else {
585 // dst pair - IP rules for dst-pairs are always from other edge nodes
586 // the destination set needs to have both destinations, even if there
587 // are no next hops to one of them
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700588 ds = DestinationSet.createTypePushBos(segmentId1, destSw1, segmentId2, destSw2);
Charles Chanf4586112015-11-09 16:37:23 -0800589 treatment = null;
sangho80f11cb2015-04-01 13:05:26 -0700590 }
591
Saurav Das4c35fc42015-11-20 15:27:53 -0800592 // setup metadata to pass to nextObjective - indicate the vlan on egress
593 // if needed by the switch pipeline. Since neighbor sets are always to
594 // other neighboring routers, there is no subnet assigned on those ports.
595 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700596 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Saurav Das261c3002017-06-13 15:35:54 -0700597 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700598 if (grpHandler == null) {
599 log.warn("populateIPRuleForRouter: groupHandler for device {} "
Saurav Das261c3002017-06-13 15:35:54 -0700600 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700601 return false;
602 }
Saurav Das4c35fc42015-11-20 15:27:53 -0800603
Saurav Das261c3002017-06-13 15:35:54 -0700604 int nextId = grpHandler.getNextObjectiveId(ds, nextHops,
Saurav Das97241862018-02-14 14:14:54 -0800605 metabuilder.build(), false);
Saurav Das4c35fc42015-11-20 15:27:53 -0800606 if (nextId <= 0) {
Saurav Das261c3002017-06-13 15:35:54 -0700607 log.warn("No next objective in {} for ds: {}", targetSw, ds);
sangho2165d222015-05-01 09:38:25 -0700608 return false;
609 }
610
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700611 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
612 .builder()
613 .fromApp(srManager.appId)
614 .makePermanent()
Saurav Das4c35fc42015-11-20 15:27:53 -0800615 .nextStep(nextId)
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700616 .withSelector(selector)
Charles Chan82ab1932016-01-30 23:22:37 -0800617 .withPriority(getPriorityFromPrefix(ipPrefix))
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700618 .withFlag(ForwardingObjective.Flag.SPECIFIC);
Charles Chanf4586112015-11-09 16:37:23 -0800619 if (treatment != null) {
620 fwdBuilder.withTreatment(treatment);
621 }
Saurav Das62ae6792017-05-15 15:34:25 -0700622 log.debug("Installing IPv4 forwarding objective for router IP/subnet {} "
Saurav Das261c3002017-06-13 15:35:54 -0700623 + "in switch {} with nextId: {}", ipPrefix, targetSw, nextId);
Charles Chan1eaf4802016-04-18 13:44:03 -0700624 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Dase0237a32016-05-27 13:54:07 -0700625 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700626 ipPrefix, targetSw),
Charles Chan1eaf4802016-04-18 13:44:03 -0700627 (objective, error) ->
Saurav Dase0237a32016-05-27 13:54:07 -0700628 log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700629 ipPrefix, error, targetSw));
630 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
sanghofb7c7292015-04-13 15:15:58 -0700631 rulePopulationCounter.incrementAndGet();
sangho80f11cb2015-04-01 13:05:26 -0700632
633 return true;
634 }
635
sangho80f11cb2015-04-01 13:05:26 -0700636 /**
Charles Chand66d6712018-03-29 16:03:41 -0700637 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700638 *
Charles Chand66d6712018-03-29 16:03:41 -0700639 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700640 * @param ipPrefix the IP address of the destination router
641 * @return true if all rules are removed successfully, false otherwise
642 */
Charles Chand66d6712018-03-29 16:03:41 -0700643 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800644 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700645 TrafficSelector selector = sbuilder.build();
646 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
647
648 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
649 .builder()
650 .fromApp(srManager.appId)
651 .makePermanent()
652 .withSelector(selector)
653 .withTreatment(dummyTreatment)
654 .withPriority(getPriorityFromPrefix(ipPrefix))
655 .withFlag(ForwardingObjective.Flag.SPECIFIC);
656
Charles Chand66d6712018-03-29 16:03:41 -0700657 ObjectiveContext context = new DefaultObjectiveContext(
658 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
659 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
660 ipPrefix, targetSw, error));
661 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700662
663 return true;
664 }
665
666 /**
Saurav Das97241862018-02-14 14:14:54 -0800667 * Populates MPLS flow rules in the target device to point towards the
668 * destination device.
669 *
670 * @param targetSwId target device ID of the switch to set the rules
671 * @param destSwId destination switch device ID
672 * @param nextHops next hops switch ID list
673 * @param routerIp the router ip of the destination switch
674 * @return true if all rules are set successfully, false otherwise
675 */
676 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
677 Set<DeviceId> nextHops, IpAddress routerIp) {
678 int segmentId;
679 try {
680 if (routerIp.isIp4()) {
681 segmentId = config.getIPv4SegmentId(destSwId);
682 } else {
683 segmentId = config.getIPv6SegmentId(destSwId);
684 }
685 } catch (DeviceConfigNotFoundException e) {
686 log.warn(e.getMessage() + " Aborting populateMplsRule.");
687 return false;
688 }
689
690 List<ForwardingObjective> fwdObjs = new ArrayList<>();
691 Collection<ForwardingObjective> fwdObjsMpls;
692 // Generates the transit rules used by the standard "routing".
693 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
694 routerIp, true);
695 if (fwdObjsMpls.isEmpty()) {
696 return false;
697 }
698 fwdObjs.addAll(fwdObjsMpls);
699
700 // Generates the transit rules used by the MPLS Pwaas.
701 int pwSrLabel;
702 try {
703 pwSrLabel = config.getPWRoutingLabel(destSwId);
704 } catch (DeviceConfigNotFoundException e) {
705 log.warn(e.getMessage()
706 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
707 return false;
708 }
709 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
710 routerIp, false);
711 if (fwdObjsMpls.isEmpty()) {
712 return false;
713 }
714 fwdObjs.addAll(fwdObjsMpls);
715
716 for (ForwardingObjective fwdObj : fwdObjs) {
717 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
718 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
719 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
720 rulePopulationCounter.incrementAndGet();
721 }
722
723 return true;
724 }
725
726 /**
727 * Differentiates between popping and swapping labels when building an MPLS
728 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700729 *
730 * @param targetSwId the target sw
731 * @param destSwId the destination sw
732 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800733 * @param segmentId the segmentId to match representing the destination
734 * switch
735 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700736 * @return a collection of fwdobjective
737 */
Saurav Das261c3002017-06-13 15:35:54 -0700738 private Collection<ForwardingObjective> handleMpls(
739 DeviceId targetSwId,
740 DeviceId destSwId,
741 Set<DeviceId> nextHops,
742 int segmentId,
743 IpAddress routerIp,
744 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700745
746 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
747 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800748 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700749 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
750 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
751 sbuilder.matchMplsBos(isMplsBos);
752 TrafficSelector selector = sbuilder.build();
753
754 // setup metadata to pass to nextObjective - indicate the vlan on egress
755 // if needed by the switch pipeline. Since mpls next-hops are always to
756 // other neighboring routers, there is no subnet assigned on those ports.
757 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700758 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre229fd0b2016-10-31 16:49:19 -0700759
760 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
761 // If the next hop is the destination router for the segment, do pop
762 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700763 + "label {} in switch {} with pop to next-hops {}",
764 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700765 ForwardingObjective.Builder fwdObjNoBosBuilder =
766 getMplsForwardingObjective(targetSwId,
767 nextHops,
768 true,
769 isMplsBos,
770 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700771 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800772 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700773 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700774 // Error case, we cannot handle, exit.
775 if (fwdObjNoBosBuilder == null) {
776 return Collections.emptyList();
777 }
778 fwdObjBuilders.add(fwdObjNoBosBuilder);
779
780 } else {
Saurav Das97241862018-02-14 14:14:54 -0800781 // next hop is not destination, irrespective of the number of next
782 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700783 log.debug("Installing MPLS forwarding objective for "
784 + "label {} in switch {} without pop to next-hops {}",
785 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700786 ForwardingObjective.Builder fwdObjNoBosBuilder =
787 getMplsForwardingObjective(targetSwId,
788 nextHops,
789 false,
790 isMplsBos,
791 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700792 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800793 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700794 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700795 // Error case, we cannot handle, exit.
796 if (fwdObjNoBosBuilder == null) {
797 return Collections.emptyList();
798 }
799 fwdObjBuilders.add(fwdObjNoBosBuilder);
800
801 }
802
803 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
804 // We add the final property to the fwdObjs.
805 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700806 ((Builder) ((Builder) fwdObjBuilder
807 .fromApp(srManager.appId)
808 .makePermanent())
809 .withSelector(selector)
810 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
811 .withFlag(ForwardingObjective.Flag.SPECIFIC);
812
813 ObjectiveContext context = new DefaultObjectiveContext(
814 (objective) ->
815 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
816 objective.id(), segmentId, targetSwId),
817 (objective, error) ->
818 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
819 objective.id(), segmentId, error, targetSwId));
820
821 ForwardingObjective fob = fwdObjBuilder.add(context);
822 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700823 }
824
825 return fwdObjs;
826 }
827
828 /**
Saurav Das97241862018-02-14 14:14:54 -0800829 * Returns a Forwarding Objective builder for the MPLS rule that references
830 * the desired Next Objective. Creates a DestinationSet that allows the
831 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700832 *
Saurav Das97241862018-02-14 14:14:54 -0800833 * @param targetSw the target sw
834 * @param nextHops the set of next hops
835 * @param phpRequired true if penultimate-hop-popping is required
836 * @param isBos true if matched label is bottom-of-stack
837 * @param meta metadata for creating next objective
838 * @param routerIp the router ip representing the destination switch
839 * @param destSw the destination sw
840 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700841 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800842 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700843 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800844 Set<DeviceId> nextHops,
845 boolean phpRequired,
846 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800847 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700848 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800849 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700850 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800851
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700852 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
853 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700854
855 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800856 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700857 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800858 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700859 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800860 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700861 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700862 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700863 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800864 if (routerIp.isIp4()) {
865 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
866 } else {
867 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
868 }
869 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800870 // standard case -> BoS == True; pop results in IP packet and forwarding
871 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700872 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700873 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800874 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
875 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800876 // double-label case -> BoS == False, pop results in MPLS packet
877 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700878 ds = DestinationSet.createTypePopNotBos(destSw);
879 if (!srManager.getMplsEcmp()) {
880 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800881 }
sangho80f11cb2015-04-01 13:05:26 -0700882 }
883 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800884 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800885 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700886 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800887 // swap results in MPLS packet with same BoS bit regardless of bit value
888 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700889 // differentiate here between swap with not bos or swap with bos
890 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
891 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
892 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800893 simple = true;
894 }
sangho80f11cb2015-04-01 13:05:26 -0700895 }
896
Saurav Das4c35fc42015-11-20 15:27:53 -0800897 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800898 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
899 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700900 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
901 if (gh == null) {
902 log.warn("getNextObjectiveId query - groupHandler for device {} "
903 + "not found", targetSw);
904 return null;
905 }
Saurav Das97241862018-02-14 14:14:54 -0800906
Saurav Das261c3002017-06-13 15:35:54 -0700907 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
908 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800909 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800910 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800911 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800912 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700913 } else {
Saurav Das97241862018-02-14 14:14:54 -0800914 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
915 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -0700916 }
917
Saurav Das4c35fc42015-11-20 15:27:53 -0800918 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700919 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -0700920 }
921
922 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -0700923 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -0700924 * dstMac corresponding to the router's MAC address. For those pipelines
925 * that need to internally assign vlans to untagged packets, this method
926 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -0700927 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -0800928 * Note that the vlan assignment and filter programming should only be done by
929 * the master for a switch. This method is typically called at deviceAdd and
930 * programs filters only for the enabled ports of the device. For port-updates,
931 * that enable/disable ports after device add, singlePortFilter methods should
932 * be called.
sangho80f11cb2015-04-01 13:05:26 -0700933 *
Saurav Das9f1c42e2015-10-23 10:51:11 -0700934 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -0800935 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -0700936 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700937 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -0700938 log.debug("Installing per-port filtering objective for untagged "
939 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800940
Saurav Das07c74602016-04-27 18:35:50 -0700941 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -0800942 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -0700943 log.warn("Device {} ports not available. Unable to add MacVlan filters",
944 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -0800945 return null;
Saurav Das07c74602016-04-27 18:35:50 -0700946 }
Saurav Dasf9332192017-02-18 14:05:44 -0800947 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -0700948 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -0700949 if (!port.isEnabled()) {
950 disabledPorts++;
951 continue;
952 }
Charles Chan43be46b2017-02-26 22:59:35 -0800953 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -0800954 filteredPorts++;
955 } else {
956 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -0700957 }
Saurav Das7c305372015-10-28 12:39:42 -0700958 }
Charles Chan077314e2017-06-22 14:27:17 -0700959 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -0800960 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan9d2dd552018-06-19 20:56:33 -0700961 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Dasf9332192017-02-18 14:05:44 -0800962 }
963
964 /**
Charles Chan43be46b2017-02-26 22:59:35 -0800965 * Creates or removes filtering objectives for a single port. Should only be
966 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -0800967 *
968 * @param deviceId device identifier
969 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -0800970 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -0800971 * @return true if no errors occurred during the build of the filtering objective
972 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700973 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -0800974 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -0700975 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
976 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
977 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -0800978
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700979 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -0800980 if (taggedVlans.size() != 0) {
981 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -0700982 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan43be46b2017-02-26 22:59:35 -0800983 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan90772a72017-02-08 15:52:08 -0800984 return false;
985 }
986 if (nativeVlan != null) {
987 // Filter for native vlan
Charles Chan43be46b2017-02-26 22:59:35 -0800988 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -0800989 return false;
990 }
991 }
992 } else if (untaggedVlan != null) {
993 // Filter for untagged vlan
Charles Chan43be46b2017-02-26 22:59:35 -0800994 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -0800995 return false;
996 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -0700997 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700998 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das9bf49582018-08-13 15:34:26 -0700999 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1000 srManager.getDefaultInternalVlan(),
1001 install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001002 return false;
1003 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001004 // Filter for receiveing pseudowire traffic
Saurav Das9bf49582018-08-13 15:34:26 -07001005 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1006 srManager.getPwTransportVlan(),
1007 install)) {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001008 return false;
1009 }
Charles Chan90772a72017-02-08 15:52:08 -08001010 }
1011 return true;
1012 }
1013
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001014 /**
1015 * Updates filtering objectives for a single port. Should only be called by
1016 * the master for a switch
1017 * @param deviceId device identifier
1018 * @param portNum port identifier for port to be filtered
1019 * @param pushVlan true to push vlan, false otherwise
1020 * @param vlanId vlan identifier
1021 * @param install true to install the filtering objective, false to remove
1022 */
1023 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1024 boolean pushVlan, VlanId vlanId, boolean install) {
1025 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
1026 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1027 deviceId, portNum, vlanId);
1028 }
1029 }
1030
Charles Chan43be46b2017-02-26 22:59:35 -08001031 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1032 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001033 boolean doTMAC = true;
1034
1035 if (!pushVlan) {
1036 // Skip the tagged vlans belonging to an interface without an IP address
1037 Set<Interface> ifaces = srManager.interfaceService
1038 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1039 .stream()
1040 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1041 .collect(Collectors.toSet());
1042 if (!ifaces.isEmpty()) {
1043 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1044 vlanId, deviceId, portnum);
1045 doTMAC = false;
1046 }
1047 }
1048
1049 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Dasf9332192017-02-18 14:05:44 -08001050 if (fob == null) {
1051 // error encountered during build
1052 return false;
1053 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001054 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001055 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001056 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001057 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001058 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001059 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001060 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001061 if (install) {
1062 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1063 } else {
1064 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001065 }
Charles Chan90772a72017-02-08 15:52:08 -08001066 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001067 }
1068
Charles Chan90772a72017-02-08 15:52:08 -08001069 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001070 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Dasf9332192017-02-18 14:05:44 -08001071 MacAddress deviceMac;
1072 try {
1073 deviceMac = config.getDeviceMac(deviceId);
1074 } catch (DeviceConfigNotFoundException e) {
1075 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1076 return null;
1077 }
Saurav Dasf9332192017-02-18 14:05:44 -08001078 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001079
1080 if (doTMAC) {
1081 fob.withKey(Criteria.matchInPort(portnum))
1082 .addCondition(Criteria.matchEthDst(deviceMac))
1083 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1084 } else {
1085 fob.withKey(Criteria.matchInPort(portnum))
1086 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1087 }
Charles Chan90772a72017-02-08 15:52:08 -08001088
Charles Chan17ca2202017-12-19 19:55:57 -08001089 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1090
Charles Chan90772a72017-02-08 15:52:08 -08001091 if (pushVlan) {
1092 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001093 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001094 } else {
1095 fob.addCondition(Criteria.matchVlanId(vlanId));
1096 }
1097
Charles Chan17ca2202017-12-19 19:55:57 -08001098 // NOTE: Some switch hardware share the same filtering flow among different ports.
1099 // We use this metadata to let the driver know that there is no more enabled port
1100 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001101 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001102 tBuilder.wipeDeferred();
1103 }
1104
1105 fob.withMeta(tBuilder.build());
1106
Saurav Dasf9332192017-02-18 14:05:44 -08001107 fob.permit().fromApp(srManager.appId);
1108 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001109 }
1110
1111 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001112 * Creates or removes filtering objectives for a double-tagged host on a port.
1113 *
1114 * @param deviceId device identifier
1115 * @param portNum port identifier for port to be filtered
1116 * @param outerVlan outer VLAN ID
1117 * @param innerVlan inner VLAN ID
1118 * @param install true to install the filtering objective, false to remove
1119 */
1120 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1121 VlanId innerVlan, boolean install) {
1122 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum, outerVlan, innerVlan);
1123 if (fob == null) {
1124 // error encountered during build
1125 return;
1126 }
1127 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1128 install ? "Installing" : "Removing", deviceId, portNum);
1129 ObjectiveContext context = new DefaultObjectiveContext(
1130 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1131 install ? "installed" : "removed"),
1132 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1133 install ? "install" : "remove", deviceId, portNum, error));
1134 if (install) {
1135 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1136 } else {
1137 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1138 }
1139 }
1140
1141 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
1142 VlanId outerVlan, VlanId innerVlan) {
1143 MacAddress deviceMac;
1144 try {
1145 deviceMac = config.getDeviceMac(deviceId);
1146 } catch (DeviceConfigNotFoundException e) {
1147 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1148 return null;
1149 }
1150 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1151 // Outer vlan id match should be appeared before inner vlan id match.
1152 fob.withKey(Criteria.matchInPort(portNum))
1153 .addCondition(Criteria.matchEthDst(deviceMac))
1154 .addCondition(Criteria.matchVlanId(outerVlan))
1155 .addCondition(Criteria.matchVlanId(innerVlan))
1156 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1157
1158 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1159 // Pop outer vlan
1160 tBuilder.popVlan();
1161
1162 // NOTE: Some switch hardware share the same filtering flow among different ports.
1163 // We use this metadata to let the driver know that there is no more enabled port
1164 // within the same VLAN on this device.
1165 if (noMoreEnabledPort(deviceId, outerVlan)) {
1166 tBuilder.wipeDeferred();
1167 }
1168
1169 fob.withMeta(tBuilder.build());
1170
1171 fob.permit().fromApp(srManager.appId);
1172 return fob;
1173 }
1174
1175 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001176 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001177 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001178 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001179 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001180 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001181 * @param deviceId the switch dpid for the router
sangho80f11cb2015-04-01 13:05:26 -07001182 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001183 void populateIpPunts(DeviceId deviceId) {
Saurav Das261c3002017-06-13 15:35:54 -07001184 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001185 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001186 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001187 routerIpv4 = config.getRouterIpv4(deviceId);
1188 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001189 routerLinkLocalIpv6 = Ip6Address.valueOf(
1190 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1191
Saurav Das261c3002017-06-13 15:35:54 -07001192 if (config.isPairedEdge(deviceId)) {
1193 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1194 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1195 }
Charles Chan319d1a22015-11-03 10:42:14 -08001196 } catch (DeviceConfigNotFoundException e) {
Charles Chan18fa4252017-02-08 16:10:40 -08001197 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001198 return;
1199 }
1200
Saurav Dasc28b3432015-10-30 17:45:38 -07001201 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1202 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1203 deviceId);
1204 return;
1205 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001206 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1207 allIps.add(routerIpv4);
1208 if (routerIpv6 != null) {
1209 allIps.add(routerIpv6);
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001210 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001211 }
Saurav Das261c3002017-06-13 15:35:54 -07001212 if (pairRouterIpv4 != null) {
1213 allIps.add(pairRouterIpv4);
1214 }
1215 if (pairRouterIpv6 != null) {
1216 allIps.add(pairRouterIpv6);
1217 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001218 for (IpAddress ipaddr : allIps) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001219 populateSingleIpPunts(deviceId, ipaddr);
1220 }
1221 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001222
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001223 /**
1224 * Creates a forwarding objective to punt all IP packets, destined to the
1225 * specified IP address, which should be router's port IP address.
1226 *
1227 * @param deviceId the switch dpid for the router
1228 * @param ipAddress the IP address of the router's port
1229 */
1230 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1231 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1232 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1233
1234 srManager.packetService.requestPackets(sbuilder.build(),
1235 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1236 }
1237
1238 /**
1239 * Removes a forwarding objective to punt all IP packets, destined to the
1240 * specified IP address, which should be router's port IP address.
1241 *
1242 * @param deviceId the switch dpid for the router
1243 * @param ipAddress the IP address of the router's port
1244 */
1245 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1246 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1247 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1248
1249 try {
1250 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1251 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1252 srManager.packetService.cancelPackets(sbuilder.build(),
1253 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1254 }
1255 } catch (DeviceConfigNotFoundException e) {
1256 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das9f1c42e2015-10-23 10:51:11 -07001257 }
sangho80f11cb2015-04-01 13:05:26 -07001258 }
1259
Charles Chanf4586112015-11-09 16:37:23 -08001260 /**
Pier Ventreadb4ae62016-11-23 09:57:42 -08001261 * Method to build IPv4 or IPv6 selector.
1262 *
1263 * @param addressToMatch the address to match
1264 */
1265 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1266 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1267 }
1268
1269 /**
1270 * Method to build IPv4 or IPv6 selector.
1271 *
1272 * @param prefixToMatch the prefix to match
1273 */
1274 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1275 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001276 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001277 if (prefixToMatch.isIp4()) {
1278 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1279 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1280 return selectorBuilder;
1281 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001282 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001283 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1284 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1285 return selectorBuilder;
1286 }
1287
1288 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001289 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1290 * Furthermore, these are applied only by the master instance. Deferred actions
1291 * are not cleared such that packets can be flooded in the cross connect use case
1292 *
1293 * @param deviceId the switch dpid for the router
1294 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001295 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001296 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001297 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1298 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1299 deviceId);
1300 return;
1301 }
1302
Charles Chan3ed34d82017-06-22 18:03:14 -07001303 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001304 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001305 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001306 .add(new ObjectiveContext() {
1307 @Override
1308 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001309 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001310 deviceId, error);
1311 }
1312 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001313 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001314
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001315 if (isIpv6Configured(deviceId)) {
1316 // We punt all NDP packets towards the controller.
1317 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1318 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1319 @Override
1320 public void onError(Objective objective, ObjectiveError error) {
1321 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1322 deviceId, error);
1323 }
1324 });
1325 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan051490d2018-01-11 11:48:18 -08001326 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001327 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001328
Saurav Dasec683dc2018-04-27 18:42:30 -07001329 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001330 ForwardingObjective pairFwdObj;
1331 // Do not punt ARP packets from pair port
1332 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1333 .add(new ObjectiveContext() {
1334 @Override
1335 public void onError(Objective objective, ObjectiveError error) {
1336 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1337 deviceId, error);
1338 }
1339 });
1340 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1341
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001342 if (isIpv6Configured(deviceId)) {
1343 // Do not punt NDP packets from pair port
1344 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1345 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan3ed34d82017-06-22 18:03:14 -07001346 @Override
1347 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001348 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan3ed34d82017-06-22 18:03:14 -07001349 deviceId, error);
1350 }
1351 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001352 srManager.flowObjectiveService.forward(deviceId, obj);
1353 });
1354
1355 // Do not forward DAD packets from pair port
1356 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1357 .add(new ObjectiveContext() {
1358 @Override
1359 public void onError(Objective objective, ObjectiveError error) {
1360 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1361 deviceId, error);
1362 }
1363 });
1364 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1365 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001366 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001367 }
1368
Charles Chan3ed34d82017-06-22 18:03:14 -07001369 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1370 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001371 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001372 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001373 .withSelector(selector)
1374 .fromApp(srManager.appId)
1375 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001376 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001377 .makePermanent();
1378 }
1379
Charles Chan3ed34d82017-06-22 18:03:14 -07001380 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001381 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1382 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001383 if (port != null) {
1384 sBuilder.matchInPort(port);
1385 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001386
Charles Chan3ed34d82017-06-22 18:03:14 -07001387 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1388 if (punt) {
1389 tBuilder.punt();
1390 }
1391 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001392 }
1393
Charles Chan051490d2018-01-11 11:48:18 -08001394 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1395 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001396
Charles Chan051490d2018-01-11 11:48:18 -08001397 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1398 .forEach(type -> {
1399 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1400 sBuilder.matchEthType(TYPE_IPV6)
1401 .matchIPProtocol(PROTOCOL_ICMP6)
1402 .matchIcmpv6Type(type);
1403 if (port != null) {
1404 sBuilder.matchInPort(port);
1405 }
1406
1407 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1408 if (punt) {
1409 tBuilder.punt();
1410 }
1411
1412 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1413 });
1414
1415 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001416 }
1417
1418 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1419 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1420 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001421 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1422 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1423 // .matchIPProtocol(PROTOCOL_ICMP6)
1424 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001425 if (port != null) {
1426 sBuilder.matchInPort(port);
1427 }
1428
1429 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1430 tBuilder.wipeDeferred();
1431 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001432 }
1433
1434 /**
Charles Chan155ec442018-09-16 14:30:19 -07001435 * Block given prefix in routing table.
Charles Chanf4586112015-11-09 16:37:23 -08001436 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001437 * @param address the address to block
1438 * @param deviceId switch ID to set the rules
1439 */
1440 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1441 updateDefaultRouteBlackhole(deviceId, address, true);
1442 }
1443
1444 /**
Charles Chan155ec442018-09-16 14:30:19 -07001445 * Unblock given prefix in routing table.
Andrea Campanella60ce2222018-04-30 11:48:55 +02001446 *
1447 * @param address the address to block
1448 * @param deviceId switch ID to set the rules
1449 */
1450 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1451 updateDefaultRouteBlackhole(deviceId, address, false);
1452 }
1453
1454 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1455 try {
1456 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1457
1458 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1459 if (address.isIp4()) {
1460 sbuilder.matchIPDst(address);
1461 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1462 } else {
1463 sbuilder.matchIPv6Dst(address);
1464 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1465 }
1466
1467 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
Andrea Campanella60ce2222018-04-30 11:48:55 +02001468 tBuilder.wipeDeferred();
1469
1470 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1471 fob.withFlag(Flag.SPECIFIC)
1472 .withSelector(sbuilder.build())
1473 .withTreatment(tBuilder.build())
1474 .withPriority(getPriorityFromPrefix(address))
1475 .fromApp(srManager.appId)
1476 .makePermanent();
1477
1478 log.debug("{} blackhole forwarding objectives for dev: {}",
1479 install ? "Installing" : "Removing", deviceId);
1480 ObjectiveContext context = new DefaultObjectiveContext(
1481 (objective) -> log.debug("Forward for {} {}", deviceId,
1482 install ? "installed" : "removed"),
1483 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1484 install ? "install" : "remove", deviceId, error));
1485 if (install) {
1486 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1487 } else {
1488 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1489 }
1490 }
1491 } catch (DeviceConfigNotFoundException e) {
1492 log.info("Not populating blackhole for un-configured device {}", deviceId);
1493 }
1494
1495 }
1496
1497 /**
1498 * Populates a forwarding objective to send packets that miss other high
1499 * priority Bridging Table entries to a group that contains all ports of
1500 * its subnet.
1501 *
Charles Chanf4586112015-11-09 16:37:23 -08001502 * @param deviceId switch ID to set the rules
1503 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001504 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001505 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001506 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001507 });
1508 }
1509
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001510 /**
1511 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1512 * @param deviceId switch ID to set the rule
1513 * @param vlanId vlan ID to specify the subnet
1514 * @param install true to install the rule, false to revoke the rule
1515 */
1516 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1517 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1518
1519 if (nextId < 0) {
1520 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1521 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1522 return;
1523 }
1524
1525 // Driver should treat objective with MacAddress.NONE as the
1526 // subnet broadcast rule
1527 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1528 sbuilder.matchVlanId(vlanId);
1529 sbuilder.matchEthDst(MacAddress.NONE);
1530
1531 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1532 fob.withFlag(Flag.SPECIFIC)
1533 .withSelector(sbuilder.build())
1534 .nextStep(nextId)
1535 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1536 .fromApp(srManager.appId)
1537 .makePermanent();
1538 ObjectiveContext context = new DefaultObjectiveContext(
1539 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1540 (objective, error) ->
1541 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1542
1543 if (install) {
1544 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1545 } else {
1546 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1547 }
1548 }
1549
Charles Chan82ab1932016-01-30 23:22:37 -08001550 private int getPriorityFromPrefix(IpPrefix prefix) {
1551 return (prefix.isIp4()) ?
1552 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1553 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001554 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001555
1556 /**
1557 * Update Forwarding objective for each host and IP address connected to given port.
1558 * And create corresponding Simple Next objective if it does not exist.
1559 * Applied only when populating Forwarding objective
1560 * @param deviceId switch ID to set the rule
1561 * @param portNumber port number
1562 * @param prefix IP prefix of the route
1563 * @param hostMac MAC address of the next hop
1564 * @param vlanId Vlan ID of the port
1565 * @param popVlan true to pop vlan tag in TrafficTreatment
1566 * @param install true to populate the forwarding objective, false to revoke
1567 */
1568 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1569 VlanId vlanId, boolean popVlan, boolean install) {
1570 ForwardingObjective.Builder fob;
1571 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1572 MacAddress deviceMac;
1573 try {
1574 deviceMac = config.getDeviceMac(deviceId);
1575 } catch (DeviceConfigNotFoundException e) {
1576 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1577 return;
1578 }
1579
1580 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1581 tbuilder.deferred()
1582 .setEthDst(hostMac)
1583 .setEthSrc(deviceMac)
1584 .setOutput(portNumber);
1585
1586 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1587
1588 if (!popVlan) {
1589 tbuilder.setVlanId(vlanId);
1590 } else {
1591 mbuilder.matchVlanId(vlanId);
1592 }
1593
1594 // if the objective is to revoke an existing rule, and for some reason
1595 // the next-objective does not exist, then a new one should not be created
1596 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1597 tbuilder.build(), mbuilder.build(), install);
1598 if (portNextObjId == -1) {
1599 // Warning log will come from getPortNextObjective method
1600 return;
1601 }
1602
1603 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1604 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1605 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1606
1607 ObjectiveContext context = new DefaultObjectiveContext(
1608 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1609 (objective, error) ->
1610 log.warn("Failed to {} IP rule for route {}: {}",
1611 install ? "install" : "revoke", prefix, error));
1612 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1613
1614 if (!install) {
1615 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1616 if (grpHandler == null) {
1617 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1618 } else {
1619 // Remove L3UG for the given port and host
1620 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1621 }
1622 }
1623 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001624
1625 /**
1626 * Checks if there is other enabled port within the given VLAN on the given device.
1627 *
1628 * @param deviceId device ID
1629 * @param vlanId VLAN ID
1630 * @return true if there is no more port enabled within the given VLAN on the given device
1631 */
1632 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1633 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1634 .filter(Port::isEnabled)
1635 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1636 .collect(Collectors.toSet());
1637
1638 return enabledPorts.stream().noneMatch(cp ->
1639 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001640 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001641 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001642 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Saurav Das9bf49582018-08-13 15:34:26 -07001643 vlanId.equals(srManager.getDefaultInternalVlan())) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001644 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1645 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1646 );
1647 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001648
1649 /**
1650 * Returns a forwarding objective builder for egress forwarding rules.
1651 * <p>
1652 * The forwarding objective installs flow rules to egress pipeline to push
1653 * two vlan headers with given inner, outer vlan ids and outer tpid.
1654 *
1655 * @param portNumber port where the next hop attaches to
1656 * @param dummyVlanId vlan ID of the packet to match
1657 * @param innerVlan inner vlan ID of the next hop
1658 * @param outerVlan outer vlan ID of the next hop
1659 * @param outerTpid outer TPID of the next hop
1660 * @return forwarding objective builder
1661 */
1662 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1663 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1664 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1665 sbuilder.matchVlanId(dummyVlanId);
1666 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1667 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1668
1669 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1670 tbuilder.pushVlan(outerTpid);
1671 } else {
1672 tbuilder.pushVlan();
1673 }
1674
1675 tbuilder.setVlanId(outerVlan);
1676 return DefaultForwardingObjective.builder()
1677 .withSelector(sbuilder.build())
1678 .withTreatment(tbuilder.build())
1679 .fromApp(srManager.appId)
1680 .makePermanent()
1681 .withPriority(DEFAULT_PRIORITY)
1682 .withFlag(ForwardingObjective.Flag.EGRESS);
1683 }
1684
1685 /**
1686 * Populates IP rules for a route that has double-tagged next hop.
1687 *
1688 * @param deviceId device ID of the device that next hop attaches to
1689 * @param prefix IP prefix of the route
1690 * @param hostMac MAC address of the next hop
1691 * @param dummyVlan Dummy Vlan ID allocated for this route
1692 * @param innerVlan inner Vlan ID of the next hop
1693 * @param outerVlan outer Vlan ID of the next hop
1694 * @param outerTpid outer TPID of the next hop
1695 * @param outPort port where the next hop attaches to
1696 */
1697 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId dummyVlan,
1698 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1699 ForwardingObjective.Builder fwdBuilder;
1700 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1701 prefix, deviceId, outPort);
1702
1703 ForwardingObjective.Builder egressFwdBuilder = egressFwdObjBuilder(
1704 outPort, dummyVlan, innerVlan, outerVlan, outerTpid);
1705 DefaultObjectiveContext egressFwdContext = new DefaultObjectiveContext(
1706 objective -> log.debug("Egress rule for IP {} is populated", prefix.address()),
1707 (objective, error) -> {
1708 log.warn("Failed to populate egress rule for IP {}: {}", prefix.address(), error);
1709 srManager.dummyVlanIdStore().remove(new DummyVlanIdStoreKey(
1710 new ConnectPoint(deviceId, outPort), prefix.address()
1711 ));
1712 });
1713 try {
1714 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, dummyVlan, outPort, false);
1715 } catch (DeviceConfigNotFoundException e) {
1716 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1717 return;
1718 }
1719 if (fwdBuilder == null) {
1720 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1721 deviceId, prefix);
1722 return;
1723 }
1724
1725 // Egress forwarding objective should be installed after the nextObjective for the output port is installed.
1726 // Installation of routingFwdObj will ensure the installation of the nextObjective.
1727 int nextId = fwdBuilder.add().nextId();
1728 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1729 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
1730 srManager.flowObjectiveService.forward(deviceId, egressFwdBuilder.add(egressFwdContext));
1731 }, (objective, error) ->
1732 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1733 );
1734 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1735 rulePopulationCounter.incrementAndGet();
1736 }
1737
1738 /**
1739 * Revokes IP rules for a route that has double-tagged next hop.
1740 *
1741 * @param deviceId device ID of the device that next hop attaches to
1742 * @param prefix IP prefix of the route
1743 * @param hostMac MAC address of the next hop
1744 * @param hostVlan Vlan ID of the next hop
1745 * @param innerVlan inner Vlan ID of the next hop
1746 * @param outerVlan outer Vlan ID of the next hop
1747 * @param outerTpid outer TPID of the next hop
1748 * @param outPort port where the next hop attaches to
1749 */
1750 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
1751 VlanId hostVlan, VlanId innerVlan, VlanId outerVlan,
1752 EthType outerTpid, PortNumber outPort) {
1753 revokeRoute(deviceId, prefix, hostMac, hostVlan, outPort);
1754
1755 DummyVlanIdStoreKey key = new DummyVlanIdStoreKey(
1756 new ConnectPoint(deviceId, outPort), prefix.address());
1757 VlanId dummyVlanId = srManager.dummyVlanIdStore().get(key);
1758 if (dummyVlanId == null) {
1759 log.warn("Failed to retrieve dummy VLAN ID for {}/{} and {}",
1760 deviceId, outPort, prefix.address());
1761 return;
1762 }
1763 ForwardingObjective.Builder fob = egressFwdObjBuilder(
1764 outPort, dummyVlanId, innerVlan, outerVlan, outerTpid);
1765 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1766 log.debug("Egress rule for IP {} revoked", prefix.address());
1767 srManager.dummyVlanIdStore().remove(key);
1768 }, (objective, error) -> {
1769 log.warn("Failed to revoke egress rule for IP {}: {}", prefix.address(), error);
1770 });
1771 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1772 }
1773
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001774 /**
1775 * Checks whether the specified port has IP configuration or not.
1776 *
1777 * @param cp ConnectPoint to check the existance of IP configuration
1778 * @return true if the port has IP configuration; false otherwise.
1779 */
1780 private boolean hasIPConfiguration(ConnectPoint cp) {
1781 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1782 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1783 }
Saurav Das9bf49582018-08-13 15:34:26 -07001784
1785 /**
1786 * Updates filtering rules for unconfigured ports on all devices for which
1787 * this controller instance is master.
1788 *
1789 * @param pushVlan true if the filtering rule requires a push vlan action
1790 * @param oldVlanId the vlanId to be removed
1791 * @param newVlanId the vlanId to be added
1792 */
1793 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1794 VlanId newVlanId) {
1795 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1796 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1797 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1798 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1799 && p.isEnabled()) {
1800 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1801 oldVlanId, false);
1802 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1803 newVlanId, true);
1804 }
1805 }
1806 }
1807 }
1808 }
1809
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001810 private boolean isIpv6Configured(DeviceId deviceId) {
1811 boolean isIpv6Configured;
1812 try {
1813 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1814 } catch (DeviceConfigNotFoundException e) {
1815 isIpv6Configured = false;
1816 }
1817 return isIpv6Configured;
1818 }
sangho80f11cb2015-04-01 13:05:26 -07001819}