blob: b864a08cd4e78d8923ef93e8f07ca23518af08f9 [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
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000306 * @param directHost host is of type direct or indirect
sangho80f11cb2015-04-01 13:05:26 -0700307 */
Charles Chan910be6a2017-08-23 14:46:43 -0700308 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000309 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Saurav Das261c3002017-06-13 15:35:54 -0700310 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chanddac7fd2016-10-27 14:19:48 -0700311 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800312 ForwardingObjective.Builder fwdBuilder;
Charles Chan319d1a22015-11-03 10:42:14 -0800313 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700314 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000315 hostVlanId, outPort, directHost, false);
Charles Chan319d1a22015-11-03 10:42:14 -0800316 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -0700317 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan319d1a22015-11-03 10:42:14 -0800318 return;
319 }
Saurav Das07c74602016-04-27 18:35:50 -0700320 if (fwdBuilder == null) {
Saurav Das368cf212017-03-15 15:15:14 -0700321 log.warn("Aborting host routing table entry due "
Charles Chanddac7fd2016-10-27 14:19:48 -0700322 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das07c74602016-04-27 18:35:50 -0700323 return;
324 }
Charles Chan910be6a2017-08-23 14:46:43 -0700325
326 int nextId = fwdBuilder.add().nextId();
Charles Chan1eaf4802016-04-18 13:44:03 -0700327 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan910be6a2017-08-23 14:46:43 -0700328 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
329 prefix, nextId),
Charles Chan1eaf4802016-04-18 13:44:03 -0700330 (objective, error) ->
Saurav Das261c3002017-06-13 15:35:54 -0700331 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das368cf212017-03-15 15:15:14 -0700332 prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700333 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chanf4586112015-11-09 16:37:23 -0800334 rulePopulationCounter.incrementAndGet();
335 }
336
Charles Chanb7f75ac2016-01-11 18:28:54 -0800337 /**
Charles Chanddac7fd2016-10-27 14:19:48 -0700338 * Removes IP rules for a route when the next hop is gone.
Charles Chand66d6712018-03-29 16:03:41 -0700339 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chanb7f75ac2016-01-11 18:28:54 -0800340 *
Charles Chanddac7fd2016-10-27 14:19:48 -0700341 * @param deviceId device ID of the device that next hop attaches to
342 * @param prefix IP prefix of the route
343 * @param hostMac MAC address of the next hop
Charles Chan90772a72017-02-08 15:52:08 -0800344 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700345 * @param outPort port that next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000346 * @param directHost host is of type direct or indirect
Charles Chanb7f75ac2016-01-11 18:28:54 -0800347 */
Charles Chan910be6a2017-08-23 14:46:43 -0700348 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000349 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chanddac7fd2016-10-27 14:19:48 -0700350 log.debug("Revoke IP table entry for route {} at {}:{}",
351 prefix, deviceId, outPort);
Charles Chanf4586112015-11-09 16:37:23 -0800352 ForwardingObjective.Builder fwdBuilder;
353 try {
Saurav Das2cb38292017-03-29 19:09:17 -0700354 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000355 hostVlanId, outPort, directHost, true);
Charles Chanf4586112015-11-09 16:37:23 -0800356 } catch (DeviceConfigNotFoundException e) {
357 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
358 return;
359 }
Charles Chanea702b12016-11-30 11:55:05 -0800360 if (fwdBuilder == null) {
361 log.warn("Aborting host routing table entries due "
362 + "to error for dev:{} route:{}", deviceId, prefix);
363 return;
364 }
Charles Chan1eaf4802016-04-18 13:44:03 -0700365 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chanddac7fd2016-10-27 14:19:48 -0700366 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chan1eaf4802016-04-18 13:44:03 -0700367 (objective, error) ->
Charles Chanddac7fd2016-10-27 14:19:48 -0700368 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chan1eaf4802016-04-18 13:44:03 -0700369 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chanf4586112015-11-09 16:37:23 -0800370 }
371
Charles Chanddac7fd2016-10-27 14:19:48 -0700372 /**
Charles Chan18fa4252017-02-08 16:10:40 -0800373 * Returns a forwarding objective builder for routing rules.
374 * <p>
375 * The forwarding objective routes packets destined to a given prefix to
376 * given port on given device with given destination MAC.
Charles Chanddac7fd2016-10-27 14:19:48 -0700377 *
378 * @param deviceId device ID
379 * @param prefix prefix that need to be routed
380 * @param hostMac MAC address of the nexthop
Charles Chan90772a72017-02-08 15:52:08 -0800381 * @param hostVlanId Vlan ID of the nexthop
Charles Chanddac7fd2016-10-27 14:19:48 -0700382 * @param outPort port where the nexthop attaches to
Saurav Das2cb38292017-03-29 19:09:17 -0700383 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000384 * @param directHost host is direct or indirect
Charles Chanddac7fd2016-10-27 14:19:48 -0700385 * @return forwarding objective builder
386 * @throws DeviceConfigNotFoundException if given device is not configured
387 */
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000388
389 private ForwardingObjective.Builder
390
391
392 routingFwdObjBuilder(
Charles Chanddac7fd2016-10-27 14:19:48 -0700393 DeviceId deviceId, IpPrefix prefix,
Saurav Das2cb38292017-03-29 19:09:17 -0700394 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000395 boolean directHost, boolean revoke)
Charles Chanf4586112015-11-09 16:37:23 -0800396 throws DeviceConfigNotFoundException {
397 MacAddress deviceMac;
398 deviceMac = config.getDeviceMac(deviceId);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000399 int nextObjId = -1;
Charles Chan319d1a22015-11-03 10:42:14 -0800400
Charles Chan90772a72017-02-08 15:52:08 -0800401 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan098ca202018-05-01 11:50:20 -0700402 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
403 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
404 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sangho80f11cb2015-04-01 13:05:26 -0700405
Charles Chan90772a72017-02-08 15:52:08 -0800406 // Create route selector
407 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
408
409 // Create route treatment
Charles Chanddac7fd2016-10-27 14:19:48 -0700410 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho27462c62015-05-14 00:39:53 -0700411 tbuilder.deferred()
412 .setEthDst(hostMac)
Charles Chan319d1a22015-11-03 10:42:14 -0800413 .setEthSrc(deviceMac)
sangho80f11cb2015-04-01 13:05:26 -0700414 .setOutput(outPort);
Saurav Das2d94d312015-11-24 23:21:05 -0800415
Charles Chan90772a72017-02-08 15:52:08 -0800416 // Create route meta
417 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan10b0fb72017-02-02 16:20:42 -0800418
Charles Chan90772a72017-02-08 15:52:08 -0800419 // Adjust the meta according to VLAN configuration
420 if (taggedVlans.contains(hostVlanId)) {
421 tbuilder.setVlanId(hostVlanId);
422 } else if (hostVlanId.equals(VlanId.NONE)) {
423 if (untaggedVlan != null) {
424 mbuilder.matchVlanId(untaggedVlan);
425 } else if (nativeVlan != null) {
426 mbuilder.matchVlanId(nativeVlan);
427 } else {
Charles Chan3ed34d82017-06-22 18:03:14 -0700428 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
429 hostMac, hostVlanId, connectPoint);
430 return null;
Charles Chan90772a72017-02-08 15:52:08 -0800431 }
432 } else {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700433 // Internally-assigned dummy VLAN id will be given as hostVlanId
434 // when destination is double-tagged.
435 VlanId vlanId = srManager.dummyVlanIdStore().get(
436 new DummyVlanIdStoreKey(connectPoint, prefix.address()));
437 if (vlanId != null && vlanId.equals(hostVlanId)) {
438 tbuilder.setVlanId(hostVlanId);
439 mbuilder.matchVlanId(VlanId.ANY);
440 } else {
441 log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
442 + " in tagged vlan", hostMac, hostVlanId, connectPoint);
443 return null;
444 }
Saurav Das07c74602016-04-27 18:35:50 -0700445 }
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000446
447 if (directHost) {
448 // if the objective is to revoke an existing rule, and for some reason
449 // the next-objective does not exist, then a new one should not be created
450 nextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
Saurav Das2cb38292017-03-29 19:09:17 -0700451 tbuilder.build(), mbuilder.build(), !revoke);
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000452 } else {
453 // if the objective is to revoke an existing rule, and for some reason
454 // the next-objective does not exist, then a new one should not be created
455 nextObjId = srManager.getMacVlanNextObjectiveId(deviceId, hostMac, hostVlanId,
456 tbuilder.build(), mbuilder.build(), !revoke);
457 }
458 if (nextObjId == -1) {
459 // Warning log will come from getMacVlanNextObjective method
Charles Chan90772a72017-02-08 15:52:08 -0800460 return null;
461 }
462
Charles Chanf4586112015-11-09 16:37:23 -0800463 return DefaultForwardingObjective.builder()
Charles Chan90772a72017-02-08 15:52:08 -0800464 .withSelector(sbuilder.build())
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +0000465 .nextStep(nextObjId)
Charles Chanf4586112015-11-09 16:37:23 -0800466 .fromApp(srManager.appId).makePermanent()
Charles Chanddac7fd2016-10-27 14:19:48 -0700467 .withPriority(getPriorityFromPrefix(prefix))
Charles Chan82ab1932016-01-30 23:22:37 -0800468 .withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700469 }
470
471 /**
Saurav Das261c3002017-06-13 15:35:54 -0700472 * Populates IP flow rules for all the given prefixes reachable from the
473 * destination switch(es).
sangho80f11cb2015-04-01 13:05:26 -0700474 *
Saurav Das261c3002017-06-13 15:35:54 -0700475 * @param targetSw switch where rules are to be programmed
476 * @param subnets subnets/prefixes being added
477 * @param destSw1 destination switch where the prefixes are reachable
478 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
479 * Should be null if there is no paired destination switch (by config)
480 * or if the given prefixes are reachable only via destSw1
481 * @param nextHops a map containing a set of next-hops for each destination switch.
482 * If destSw2 is not null, then this map must contain an
483 * entry for destSw2 with its next-hops from the targetSw
484 * (although the next-hop set may be empty in certain scenarios).
485 * If destSw2 is null, there should not be an entry in this
486 * map for destSw2.
sangho80f11cb2015-04-01 13:05:26 -0700487 * @return true if all rules are set successfully, false otherwise
488 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700489 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das261c3002017-06-13 15:35:54 -0700490 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
psneha86e60d32019-03-26 06:31:41 -0400491 // Get pair device of the target switch
492 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
493 // Route simplification will be off in case of the nexthop location at target switch is down
494 // (routing through spine case)
495 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
496 // Iterates over the routes
497 // If route simplification is enabled
498 // If the target device is another leaf in the network
499 if (srManager.routeSimplification && !routeSimplOff) {
500 for (IpPrefix subnet : subnets) {
501 // Skip route programming on the target device
502 // If route simplification applies
503 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
504 // XXX route simplification assumes that source of the traffic
505 // towards the nexthops are co-located with the nexthops. In different
506 // scenarios will not work properly.
507 continue;
508 }
509 // populate the route in the remaning scenarios
510 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
511 return false;
512 }
513 }
514 } else {
515 // Populate IP flow rules for all the subnets.
516 for (IpPrefix subnet : subnets) {
517 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
518 return false;
519 }
sangho80f11cb2015-04-01 13:05:26 -0700520 }
521 }
Charles Chanc22cef32016-04-29 14:38:22 -0700522 return true;
523 }
sangho80f11cb2015-04-01 13:05:26 -0700524
Charles Chanc22cef32016-04-29 14:38:22 -0700525 /**
Charles Chand66d6712018-03-29 16:03:41 -0700526 * Revokes IP flow rules for the subnets from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700527 *
Charles Chand66d6712018-03-29 16:03:41 -0700528 * @param targetSw target switch from which the subnets need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700529 * @param subnets subnet being removed
530 * @return true if all rules are removed successfully, false otherwise
531 */
Charles Chand66d6712018-03-29 16:03:41 -0700532 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chanc22cef32016-04-29 14:38:22 -0700533 for (IpPrefix subnet : subnets) {
Charles Chand66d6712018-03-29 16:03:41 -0700534 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chanc22cef32016-04-29 14:38:22 -0700535 return false;
536 }
537 }
sangho80f11cb2015-04-01 13:05:26 -0700538 return true;
539 }
540
541 /**
Saurav Dase0237a32016-05-27 13:54:07 -0700542 * Populates IP flow rules for an IP prefix in the target device. The prefix
Saurav Das261c3002017-06-13 15:35:54 -0700543 * is reachable via destination device(s).
sangho80f11cb2015-04-01 13:05:26 -0700544 *
Saurav Das261c3002017-06-13 15:35:54 -0700545 * @param targetSw target device ID to set the rules
546 * @param ipPrefix the IP prefix
547 * @param destSw1 destination switch where the prefixes are reachable
548 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
549 * Should be null if there is no paired destination switch (by config)
550 * or if the given prefixes are reachable only via destSw1
551 * @param nextHops map of destination switches and their next-hops.
552 * Should only contain destination switches that are
553 * actually meant to be routed to. If destSw2 is null, there
554 * should not be an entry for destSw2 in this map.
sangho80f11cb2015-04-01 13:05:26 -0700555 * @return true if all rules are set successfully, false otherwise
556 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700557 private boolean populateIpRuleForRouter(DeviceId targetSw,
Saurav Das261c3002017-06-13 15:35:54 -0700558 IpPrefix ipPrefix, DeviceId destSw1,
559 DeviceId destSw2,
560 Map<DeviceId, Set<DeviceId>> nextHops) {
561 int segmentId1, segmentId2 = -1;
Charles Chan319d1a22015-11-03 10:42:14 -0800562 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800563 if (ipPrefix.isIp4()) {
Saurav Das261c3002017-06-13 15:35:54 -0700564 segmentId1 = config.getIPv4SegmentId(destSw1);
565 if (destSw2 != null) {
566 segmentId2 = config.getIPv4SegmentId(destSw2);
567 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800568 } else {
Saurav Das261c3002017-06-13 15:35:54 -0700569 segmentId1 = config.getIPv6SegmentId(destSw1);
570 if (destSw2 != null) {
571 segmentId2 = config.getIPv6SegmentId(destSw2);
572 }
Pier Ventreadb4ae62016-11-23 09:57:42 -0800573 }
Charles Chan319d1a22015-11-03 10:42:14 -0800574 } catch (DeviceConfigNotFoundException e) {
575 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
576 return false;
577 }
sangho80f11cb2015-04-01 13:05:26 -0700578
Pier Ventreadb4ae62016-11-23 09:57:42 -0800579 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanf4586112015-11-09 16:37:23 -0800580 TrafficSelector selector = sbuilder.build();
sangho80f11cb2015-04-01 13:05:26 -0700581
Charles Chanf4586112015-11-09 16:37:23 -0800582 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das261c3002017-06-13 15:35:54 -0700583 DestinationSet ds;
Charles Chanf4586112015-11-09 16:37:23 -0800584 TrafficTreatment treatment;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700585 DestinationSet.DestinationSetType dsType;
sangho80f11cb2015-04-01 13:05:26 -0700586
Saurav Das261c3002017-06-13 15:35:54 -0700587 if (destSw2 == null) {
588 // single dst - create destination set based on next-hop
Saurav Das97241862018-02-14 14:14:54 -0800589 // If the next hop is the same as the final destination, then MPLS
590 // label is not set.
Saurav Das261c3002017-06-13 15:35:54 -0700591 Set<DeviceId> nhd1 = nextHops.get(destSw1);
592 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
593 tbuilder.immediate().decNwTtl();
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700594 ds = DestinationSet.createTypePushNone(destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700595 treatment = tbuilder.build();
596 } else {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700597 ds = DestinationSet.createTypePushBos(segmentId1, destSw1);
Saurav Das261c3002017-06-13 15:35:54 -0700598 treatment = null;
599 }
600 } else {
601 // dst pair - IP rules for dst-pairs are always from other edge nodes
602 // the destination set needs to have both destinations, even if there
603 // are no next hops to one of them
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700604 ds = DestinationSet.createTypePushBos(segmentId1, destSw1, segmentId2, destSw2);
Charles Chanf4586112015-11-09 16:37:23 -0800605 treatment = null;
sangho80f11cb2015-04-01 13:05:26 -0700606 }
607
Saurav Das4c35fc42015-11-20 15:27:53 -0800608 // setup metadata to pass to nextObjective - indicate the vlan on egress
609 // if needed by the switch pipeline. Since neighbor sets are always to
610 // other neighboring routers, there is no subnet assigned on those ports.
611 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700612 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Saurav Das261c3002017-06-13 15:35:54 -0700613 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700614 if (grpHandler == null) {
615 log.warn("populateIPRuleForRouter: groupHandler for device {} "
Saurav Das261c3002017-06-13 15:35:54 -0700616 + "not found", targetSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700617 return false;
618 }
Saurav Das4c35fc42015-11-20 15:27:53 -0800619
Saurav Das261c3002017-06-13 15:35:54 -0700620 int nextId = grpHandler.getNextObjectiveId(ds, nextHops,
Saurav Das97241862018-02-14 14:14:54 -0800621 metabuilder.build(), false);
Saurav Das4c35fc42015-11-20 15:27:53 -0800622 if (nextId <= 0) {
Saurav Das261c3002017-06-13 15:35:54 -0700623 log.warn("No next objective in {} for ds: {}", targetSw, ds);
sangho2165d222015-05-01 09:38:25 -0700624 return false;
625 }
626
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700627 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
628 .builder()
629 .fromApp(srManager.appId)
630 .makePermanent()
Saurav Das4c35fc42015-11-20 15:27:53 -0800631 .nextStep(nextId)
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700632 .withSelector(selector)
Charles Chan82ab1932016-01-30 23:22:37 -0800633 .withPriority(getPriorityFromPrefix(ipPrefix))
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700634 .withFlag(ForwardingObjective.Flag.SPECIFIC);
Charles Chanf4586112015-11-09 16:37:23 -0800635 if (treatment != null) {
636 fwdBuilder.withTreatment(treatment);
637 }
Saurav Das62ae6792017-05-15 15:34:25 -0700638 log.debug("Installing IPv4 forwarding objective for router IP/subnet {} "
Saurav Das261c3002017-06-13 15:35:54 -0700639 + "in switch {} with nextId: {}", ipPrefix, targetSw, nextId);
Charles Chan1eaf4802016-04-18 13:44:03 -0700640 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Dase0237a32016-05-27 13:54:07 -0700641 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700642 ipPrefix, targetSw),
Charles Chan1eaf4802016-04-18 13:44:03 -0700643 (objective, error) ->
Saurav Dase0237a32016-05-27 13:54:07 -0700644 log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
Saurav Das261c3002017-06-13 15:35:54 -0700645 ipPrefix, error, targetSw));
646 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
sanghofb7c7292015-04-13 15:15:58 -0700647 rulePopulationCounter.incrementAndGet();
sangho80f11cb2015-04-01 13:05:26 -0700648
649 return true;
650 }
651
sangho80f11cb2015-04-01 13:05:26 -0700652 /**
Charles Chand66d6712018-03-29 16:03:41 -0700653 * Revokes IP flow rules for the router IP address from given device.
Charles Chanc22cef32016-04-29 14:38:22 -0700654 *
Charles Chand66d6712018-03-29 16:03:41 -0700655 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chanc22cef32016-04-29 14:38:22 -0700656 * @param ipPrefix the IP address of the destination router
657 * @return true if all rules are removed successfully, false otherwise
658 */
Charles Chand66d6712018-03-29 16:03:41 -0700659 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre6b2c1b32016-12-09 17:26:04 -0800660 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chanc22cef32016-04-29 14:38:22 -0700661 TrafficSelector selector = sbuilder.build();
662 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
663
664 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
665 .builder()
666 .fromApp(srManager.appId)
667 .makePermanent()
668 .withSelector(selector)
669 .withTreatment(dummyTreatment)
670 .withPriority(getPriorityFromPrefix(ipPrefix))
671 .withFlag(ForwardingObjective.Flag.SPECIFIC);
672
Charles Chand66d6712018-03-29 16:03:41 -0700673 ObjectiveContext context = new DefaultObjectiveContext(
674 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
675 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
676 ipPrefix, targetSw, error));
677 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chanc22cef32016-04-29 14:38:22 -0700678
679 return true;
680 }
681
682 /**
Saurav Das97241862018-02-14 14:14:54 -0800683 * Populates MPLS flow rules in the target device to point towards the
684 * destination device.
685 *
686 * @param targetSwId target device ID of the switch to set the rules
687 * @param destSwId destination switch device ID
688 * @param nextHops next hops switch ID list
689 * @param routerIp the router ip of the destination switch
690 * @return true if all rules are set successfully, false otherwise
691 */
692 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
693 Set<DeviceId> nextHops, IpAddress routerIp) {
694 int segmentId;
695 try {
696 if (routerIp.isIp4()) {
697 segmentId = config.getIPv4SegmentId(destSwId);
698 } else {
699 segmentId = config.getIPv6SegmentId(destSwId);
700 }
701 } catch (DeviceConfigNotFoundException e) {
702 log.warn(e.getMessage() + " Aborting populateMplsRule.");
703 return false;
704 }
705
706 List<ForwardingObjective> fwdObjs = new ArrayList<>();
707 Collection<ForwardingObjective> fwdObjsMpls;
708 // Generates the transit rules used by the standard "routing".
709 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
710 routerIp, true);
711 if (fwdObjsMpls.isEmpty()) {
712 return false;
713 }
714 fwdObjs.addAll(fwdObjsMpls);
715
716 // Generates the transit rules used by the MPLS Pwaas.
717 int pwSrLabel;
718 try {
719 pwSrLabel = config.getPWRoutingLabel(destSwId);
720 } catch (DeviceConfigNotFoundException e) {
721 log.warn(e.getMessage()
722 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
723 return false;
724 }
725 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
726 routerIp, false);
727 if (fwdObjsMpls.isEmpty()) {
728 return false;
729 }
730 fwdObjs.addAll(fwdObjsMpls);
731
732 for (ForwardingObjective fwdObj : fwdObjs) {
733 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
734 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
735 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
736 rulePopulationCounter.incrementAndGet();
737 }
738
739 return true;
740 }
741
742 /**
743 * Differentiates between popping and swapping labels when building an MPLS
744 * forwarding objective.
Pier Ventre229fd0b2016-10-31 16:49:19 -0700745 *
746 * @param targetSwId the target sw
747 * @param destSwId the destination sw
748 * @param nextHops the set of next hops
Saurav Das97241862018-02-14 14:14:54 -0800749 * @param segmentId the segmentId to match representing the destination
750 * switch
751 * @param routerIp the router ip representing the destination switch
Pier Ventre229fd0b2016-10-31 16:49:19 -0700752 * @return a collection of fwdobjective
753 */
Saurav Das261c3002017-06-13 15:35:54 -0700754 private Collection<ForwardingObjective> handleMpls(
755 DeviceId targetSwId,
756 DeviceId destSwId,
757 Set<DeviceId> nextHops,
758 int segmentId,
759 IpAddress routerIp,
760 boolean isMplsBos) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700761
762 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
763 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi0be3f0f2017-01-30 09:47:36 -0800764 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre229fd0b2016-10-31 16:49:19 -0700765 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
766 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
767 sbuilder.matchMplsBos(isMplsBos);
768 TrafficSelector selector = sbuilder.build();
769
770 // setup metadata to pass to nextObjective - indicate the vlan on egress
771 // if needed by the switch pipeline. Since mpls next-hops are always to
772 // other neighboring routers, there is no subnet assigned on those ports.
773 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das9bf49582018-08-13 15:34:26 -0700774 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre229fd0b2016-10-31 16:49:19 -0700775
776 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
777 // If the next hop is the destination router for the segment, do pop
778 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das261c3002017-06-13 15:35:54 -0700779 + "label {} in switch {} with pop to next-hops {}",
780 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700781 ForwardingObjective.Builder fwdObjNoBosBuilder =
782 getMplsForwardingObjective(targetSwId,
783 nextHops,
784 true,
785 isMplsBos,
786 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700787 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800788 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700789 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700790 // Error case, we cannot handle, exit.
791 if (fwdObjNoBosBuilder == null) {
792 return Collections.emptyList();
793 }
794 fwdObjBuilders.add(fwdObjNoBosBuilder);
795
796 } else {
Saurav Das97241862018-02-14 14:14:54 -0800797 // next hop is not destination, irrespective of the number of next
798 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das261c3002017-06-13 15:35:54 -0700799 log.debug("Installing MPLS forwarding objective for "
800 + "label {} in switch {} without pop to next-hops {}",
801 segmentId, targetSwId, nextHops);
Saurav Das2cb38292017-03-29 19:09:17 -0700802 ForwardingObjective.Builder fwdObjNoBosBuilder =
803 getMplsForwardingObjective(targetSwId,
804 nextHops,
805 false,
806 isMplsBos,
807 metabuilder.build(),
Saurav Das62ae6792017-05-15 15:34:25 -0700808 routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800809 segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700810 destSwId);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700811 // Error case, we cannot handle, exit.
812 if (fwdObjNoBosBuilder == null) {
813 return Collections.emptyList();
814 }
815 fwdObjBuilders.add(fwdObjNoBosBuilder);
816
817 }
818
819 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
820 // We add the final property to the fwdObjs.
821 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre229fd0b2016-10-31 16:49:19 -0700822 ((Builder) ((Builder) fwdObjBuilder
823 .fromApp(srManager.appId)
824 .makePermanent())
825 .withSelector(selector)
826 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
827 .withFlag(ForwardingObjective.Flag.SPECIFIC);
828
829 ObjectiveContext context = new DefaultObjectiveContext(
830 (objective) ->
831 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
832 objective.id(), segmentId, targetSwId),
833 (objective, error) ->
834 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
835 objective.id(), segmentId, error, targetSwId));
836
837 ForwardingObjective fob = fwdObjBuilder.add(context);
838 fwdObjs.add(fob);
Pier Ventre229fd0b2016-10-31 16:49:19 -0700839 }
840
841 return fwdObjs;
842 }
843
844 /**
Saurav Das97241862018-02-14 14:14:54 -0800845 * Returns a Forwarding Objective builder for the MPLS rule that references
846 * the desired Next Objective. Creates a DestinationSet that allows the
847 * groupHandler to create or find the required next objective.
sangho80f11cb2015-04-01 13:05:26 -0700848 *
Saurav Das97241862018-02-14 14:14:54 -0800849 * @param targetSw the target sw
850 * @param nextHops the set of next hops
851 * @param phpRequired true if penultimate-hop-popping is required
852 * @param isBos true if matched label is bottom-of-stack
853 * @param meta metadata for creating next objective
854 * @param routerIp the router ip representing the destination switch
855 * @param destSw the destination sw
856 * @return the mpls forwarding objective builder
sangho80f11cb2015-04-01 13:05:26 -0700857 */
Saurav Das4c35fc42015-11-20 15:27:53 -0800858 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das261c3002017-06-13 15:35:54 -0700859 DeviceId targetSw,
Saurav Das4c35fc42015-11-20 15:27:53 -0800860 Set<DeviceId> nextHops,
861 boolean phpRequired,
862 boolean isBos,
Pier Ventreadb4ae62016-11-23 09:57:42 -0800863 TrafficSelector meta,
Saurav Das62ae6792017-05-15 15:34:25 -0700864 IpAddress routerIp,
Saurav Das97241862018-02-14 14:14:54 -0800865 int segmentId,
Saurav Das62ae6792017-05-15 15:34:25 -0700866 DeviceId destSw) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800867
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700868 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
869 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sangho80f11cb2015-04-01 13:05:26 -0700870
871 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das97241862018-02-14 14:14:54 -0800872 DestinationSet ds = null;
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700873 DestinationSet.DestinationSetType dstType = null;
Saurav Das97241862018-02-14 14:14:54 -0800874 boolean simple = false;
sangho80f11cb2015-04-01 13:05:26 -0700875 if (phpRequired) {
Saurav Das4c35fc42015-11-20 15:27:53 -0800876 // php case - pop should always be flow-action
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700877 log.debug("getMplsForwardingObjective: php required");
sangho27462c62015-05-14 00:39:53 -0700878 tbuilder.deferred().copyTtlIn();
sangho80f11cb2015-04-01 13:05:26 -0700879 if (isBos) {
Pier Ventreadb4ae62016-11-23 09:57:42 -0800880 if (routerIp.isIp4()) {
881 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
882 } else {
883 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
884 }
885 tbuilder.decNwTtl();
Saurav Das97241862018-02-14 14:14:54 -0800886 // standard case -> BoS == True; pop results in IP packet and forwarding
887 // is via an ECMP group
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700888 ds = DestinationSet.createTypePopBos(destSw);
sangho80f11cb2015-04-01 13:05:26 -0700889 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800890 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
891 .decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800892 // double-label case -> BoS == False, pop results in MPLS packet
893 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700894 ds = DestinationSet.createTypePopNotBos(destSw);
895 if (!srManager.getMplsEcmp()) {
896 simple = true;
Saurav Das97241862018-02-14 14:14:54 -0800897 }
sangho80f11cb2015-04-01 13:05:26 -0700898 }
899 } else {
Saurav Das4c35fc42015-11-20 15:27:53 -0800900 // swap with self case - SR CONTINUE
Saurav Das97241862018-02-14 14:14:54 -0800901 log.debug("getMplsForwardingObjective: swap with self");
sangho27462c62015-05-14 00:39:53 -0700902 tbuilder.deferred().decMplsTtl();
Saurav Das97241862018-02-14 14:14:54 -0800903 // swap results in MPLS packet with same BoS bit regardless of bit value
904 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -0700905 // differentiate here between swap with not bos or swap with bos
906 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
907 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
908 if (!srManager.getMplsEcmp()) {
Saurav Das97241862018-02-14 14:14:54 -0800909 simple = true;
910 }
sangho80f11cb2015-04-01 13:05:26 -0700911 }
912
Saurav Das4c35fc42015-11-20 15:27:53 -0800913 fwdBuilder.withTreatment(tbuilder.build());
Saurav Das97241862018-02-14 14:14:54 -0800914 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
915 targetSw, ds);
Saurav Das261c3002017-06-13 15:35:54 -0700916 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
917 if (gh == null) {
918 log.warn("getNextObjectiveId query - groupHandler for device {} "
919 + "not found", targetSw);
920 return null;
921 }
Saurav Das97241862018-02-14 14:14:54 -0800922
Saurav Das261c3002017-06-13 15:35:54 -0700923 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
924 dstNextHops.put(destSw, nextHops);
Saurav Das97241862018-02-14 14:14:54 -0800925 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das4c35fc42015-11-20 15:27:53 -0800926 if (nextId <= 0) {
Saurav Das97241862018-02-14 14:14:54 -0800927 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das4c35fc42015-11-20 15:27:53 -0800928 return null;
Saurav Dase0237a32016-05-27 13:54:07 -0700929 } else {
Saurav Das97241862018-02-14 14:14:54 -0800930 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
931 nextId, targetSw, ds);
sangho80f11cb2015-04-01 13:05:26 -0700932 }
933
Saurav Das4c35fc42015-11-20 15:27:53 -0800934 fwdBuilder.nextStep(nextId);
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700935 return fwdBuilder;
sangho80f11cb2015-04-01 13:05:26 -0700936 }
937
938 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -0700939 * Creates a filtering objective to permit all untagged packets with a
Saurav Das7c305372015-10-28 12:39:42 -0700940 * dstMac corresponding to the router's MAC address. For those pipelines
941 * that need to internally assign vlans to untagged packets, this method
942 * provides per-subnet vlan-ids as metadata.
Saurav Dasc28b3432015-10-30 17:45:38 -0700943 * <p>
Saurav Dasf9332192017-02-18 14:05:44 -0800944 * Note that the vlan assignment and filter programming should only be done by
945 * the master for a switch. This method is typically called at deviceAdd and
946 * programs filters only for the enabled ports of the device. For port-updates,
947 * that enable/disable ports after device add, singlePortFilter methods should
948 * be called.
sangho80f11cb2015-04-01 13:05:26 -0700949 *
Saurav Das9f1c42e2015-10-23 10:51:11 -0700950 * @param deviceId the switch dpid for the router
Saurav Dasd1872b02016-12-02 15:43:47 -0800951 * @return PortFilterInfo information about the processed ports
sangho80f11cb2015-04-01 13:05:26 -0700952 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700953 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das7c305372015-10-28 12:39:42 -0700954 log.debug("Installing per-port filtering objective for untagged "
955 + "packets in device {}", deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -0800956
Saurav Das07c74602016-04-27 18:35:50 -0700957 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hall31d84782017-01-18 20:15:44 -0800958 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das07c74602016-04-27 18:35:50 -0700959 log.warn("Device {} ports not available. Unable to add MacVlan filters",
960 deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -0800961 return null;
Saurav Das07c74602016-04-27 18:35:50 -0700962 }
Saurav Dasf9332192017-02-18 14:05:44 -0800963 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -0700964 for (Port port : devPorts) {
Saurav Dase0237a32016-05-27 13:54:07 -0700965 if (!port.isEnabled()) {
966 disabledPorts++;
967 continue;
968 }
Charles Chan43be46b2017-02-26 22:59:35 -0800969 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Dasf9332192017-02-18 14:05:44 -0800970 filteredPorts++;
971 } else {
972 errorPorts++;
Saurav Dase0237a32016-05-27 13:54:07 -0700973 }
Saurav Das7c305372015-10-28 12:39:42 -0700974 }
Charles Chan077314e2017-06-22 14:27:17 -0700975 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Dasf9332192017-02-18 14:05:44 -0800976 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan9d2dd552018-06-19 20:56:33 -0700977 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Dasf9332192017-02-18 14:05:44 -0800978 }
979
980 /**
Charles Chan43be46b2017-02-26 22:59:35 -0800981 * Creates or removes filtering objectives for a single port. Should only be
982 * called by the master for a switch.
Saurav Dasf9332192017-02-18 14:05:44 -0800983 *
984 * @param deviceId device identifier
985 * @param portnum port identifier for port to be filtered
Charles Chan43be46b2017-02-26 22:59:35 -0800986 * @param install true to install the filtering objective, false to remove
Saurav Dasf9332192017-02-18 14:05:44 -0800987 * @return true if no errors occurred during the build of the filtering objective
988 */
Charles Chan3ed34d82017-06-22 18:03:14 -0700989 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan90772a72017-02-08 15:52:08 -0800990 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan098ca202018-05-01 11:50:20 -0700991 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
992 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
993 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan90772a72017-02-08 15:52:08 -0800994
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -0700995 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan90772a72017-02-08 15:52:08 -0800996 if (taggedVlans.size() != 0) {
997 // Filter for tagged vlans
Charles Chan098ca202018-05-01 11:50:20 -0700998 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan43be46b2017-02-26 22:59:35 -0800999 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan90772a72017-02-08 15:52:08 -08001000 return false;
1001 }
1002 if (nativeVlan != null) {
1003 // Filter for native vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001004 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001005 return false;
1006 }
1007 }
1008 } else if (untaggedVlan != null) {
1009 // Filter for untagged vlan
Charles Chan43be46b2017-02-26 22:59:35 -08001010 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001011 return false;
1012 }
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001013 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001014 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das9bf49582018-08-13 15:34:26 -07001015 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1016 srManager.getDefaultInternalVlan(),
1017 install)) {
Charles Chan90772a72017-02-08 15:52:08 -08001018 return false;
1019 }
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001020 // Filter for receiveing pseudowire traffic
Saurav Das9bf49582018-08-13 15:34:26 -07001021 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1022 srManager.getPwTransportVlan(),
1023 install)) {
Andreas Pantelopoulosb281ae22018-05-01 14:56:05 -07001024 return false;
1025 }
Charles Chan90772a72017-02-08 15:52:08 -08001026 }
1027 return true;
1028 }
1029
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001030 /**
1031 * Updates filtering objectives for a single port. Should only be called by
1032 * the master for a switch
1033 * @param deviceId device identifier
1034 * @param portNum port identifier for port to be filtered
1035 * @param pushVlan true to push vlan, false otherwise
1036 * @param vlanId vlan identifier
1037 * @param install true to install the filtering objective, false to remove
1038 */
1039 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1040 boolean pushVlan, VlanId vlanId, boolean install) {
1041 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
1042 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1043 deviceId, portNum, vlanId);
1044 }
1045 }
1046
Charles Chan43be46b2017-02-26 22:59:35 -08001047 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1048 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001049 boolean doTMAC = true;
1050
1051 if (!pushVlan) {
1052 // Skip the tagged vlans belonging to an interface without an IP address
1053 Set<Interface> ifaces = srManager.interfaceService
1054 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1055 .stream()
1056 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1057 .collect(Collectors.toSet());
1058 if (!ifaces.isEmpty()) {
1059 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1060 vlanId, deviceId, portnum);
1061 doTMAC = false;
1062 }
1063 }
1064
1065 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Dasf9332192017-02-18 14:05:44 -08001066 if (fob == null) {
1067 // error encountered during build
1068 return false;
1069 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001070 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Das62ae6792017-05-15 15:34:25 -07001071 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Dasf9332192017-02-18 14:05:44 -08001072 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan43be46b2017-02-26 22:59:35 -08001073 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Das62ae6792017-05-15 15:34:25 -07001074 install ? "installed" : "removed"),
Charles Chan43be46b2017-02-26 22:59:35 -08001075 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001076 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan43be46b2017-02-26 22:59:35 -08001077 if (install) {
1078 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1079 } else {
1080 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan90772a72017-02-08 15:52:08 -08001081 }
Charles Chan90772a72017-02-08 15:52:08 -08001082 return true;
Saurav Dasf9332192017-02-18 14:05:44 -08001083 }
1084
Charles Chan90772a72017-02-08 15:52:08 -08001085 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001086 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Dasf9332192017-02-18 14:05:44 -08001087 MacAddress deviceMac;
1088 try {
1089 deviceMac = config.getDeviceMac(deviceId);
1090 } catch (DeviceConfigNotFoundException e) {
1091 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1092 return null;
1093 }
Saurav Dasf9332192017-02-18 14:05:44 -08001094 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg776789f2018-04-30 19:27:19 -04001095
1096 if (doTMAC) {
1097 fob.withKey(Criteria.matchInPort(portnum))
1098 .addCondition(Criteria.matchEthDst(deviceMac))
1099 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1100 } else {
1101 fob.withKey(Criteria.matchInPort(portnum))
1102 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1103 }
Charles Chan90772a72017-02-08 15:52:08 -08001104
Charles Chan17ca2202017-12-19 19:55:57 -08001105 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1106
Charles Chan90772a72017-02-08 15:52:08 -08001107 if (pushVlan) {
1108 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chan17ca2202017-12-19 19:55:57 -08001109 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan90772a72017-02-08 15:52:08 -08001110 } else {
1111 fob.addCondition(Criteria.matchVlanId(vlanId));
1112 }
1113
Charles Chan17ca2202017-12-19 19:55:57 -08001114 // NOTE: Some switch hardware share the same filtering flow among different ports.
1115 // We use this metadata to let the driver know that there is no more enabled port
1116 // within the same VLAN on this device.
Charles Chanf17f66b2018-02-26 21:33:25 -08001117 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chan17ca2202017-12-19 19:55:57 -08001118 tBuilder.wipeDeferred();
1119 }
1120
1121 fob.withMeta(tBuilder.build());
1122
Saurav Dasf9332192017-02-18 14:05:44 -08001123 fob.permit().fromApp(srManager.appId);
1124 return fob;
sangho80f11cb2015-04-01 13:05:26 -07001125 }
1126
1127 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001128 * Creates or removes filtering objectives for a double-tagged host on a port.
1129 *
1130 * @param deviceId device identifier
1131 * @param portNum port identifier for port to be filtered
1132 * @param outerVlan outer VLAN ID
1133 * @param innerVlan inner VLAN ID
1134 * @param install true to install the filtering objective, false to remove
1135 */
1136 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1137 VlanId innerVlan, boolean install) {
1138 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum, outerVlan, innerVlan);
1139 if (fob == null) {
1140 // error encountered during build
1141 return;
1142 }
1143 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1144 install ? "Installing" : "Removing", deviceId, portNum);
1145 ObjectiveContext context = new DefaultObjectiveContext(
1146 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1147 install ? "installed" : "removed"),
1148 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1149 install ? "install" : "remove", deviceId, portNum, error));
1150 if (install) {
1151 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1152 } else {
1153 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1154 }
1155 }
1156
1157 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
1158 VlanId outerVlan, VlanId innerVlan) {
1159 MacAddress deviceMac;
1160 try {
1161 deviceMac = config.getDeviceMac(deviceId);
1162 } catch (DeviceConfigNotFoundException e) {
1163 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1164 return null;
1165 }
1166 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1167 // Outer vlan id match should be appeared before inner vlan id match.
1168 fob.withKey(Criteria.matchInPort(portNum))
1169 .addCondition(Criteria.matchEthDst(deviceMac))
1170 .addCondition(Criteria.matchVlanId(outerVlan))
1171 .addCondition(Criteria.matchVlanId(innerVlan))
1172 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1173
1174 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1175 // Pop outer vlan
1176 tBuilder.popVlan();
1177
1178 // NOTE: Some switch hardware share the same filtering flow among different ports.
1179 // We use this metadata to let the driver know that there is no more enabled port
1180 // within the same VLAN on this device.
1181 if (noMoreEnabledPort(deviceId, outerVlan)) {
1182 tBuilder.wipeDeferred();
1183 }
1184
1185 fob.withMeta(tBuilder.build());
1186
1187 fob.permit().fromApp(srManager.appId);
1188 return fob;
1189 }
1190
1191 /**
Saurav Das9f1c42e2015-10-23 10:51:11 -07001192 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Dasc28b3432015-10-30 17:45:38 -07001193 * router's port IP addresses, to the controller. Note that the input
Saurav Das9f1c42e2015-10-23 10:51:11 -07001194 * port should not be matched on, as these packets can come from any input.
Saurav Dasc28b3432015-10-30 17:45:38 -07001195 * Furthermore, these are applied only by the master instance.
sangho80f11cb2015-04-01 13:05:26 -07001196 *
Saurav Das9f1c42e2015-10-23 10:51:11 -07001197 * @param deviceId the switch dpid for the router
sangho80f11cb2015-04-01 13:05:26 -07001198 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001199 void populateIpPunts(DeviceId deviceId) {
Saurav Das261c3002017-06-13 15:35:54 -07001200 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chanef8d12e2017-12-05 21:07:38 -08001201 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan319d1a22015-11-03 10:42:14 -08001202 try {
Pier Ventreadb4ae62016-11-23 09:57:42 -08001203 routerIpv4 = config.getRouterIpv4(deviceId);
1204 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chanef8d12e2017-12-05 21:07:38 -08001205 routerLinkLocalIpv6 = Ip6Address.valueOf(
1206 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1207
Saurav Das261c3002017-06-13 15:35:54 -07001208 if (config.isPairedEdge(deviceId)) {
1209 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1210 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1211 }
Charles Chan319d1a22015-11-03 10:42:14 -08001212 } catch (DeviceConfigNotFoundException e) {
Charles Chan18fa4252017-02-08 16:10:40 -08001213 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan319d1a22015-11-03 10:42:14 -08001214 return;
1215 }
1216
Saurav Dasc28b3432015-10-30 17:45:38 -07001217 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1218 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1219 deviceId);
1220 return;
1221 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001222 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1223 allIps.add(routerIpv4);
1224 if (routerIpv6 != null) {
1225 allIps.add(routerIpv6);
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001226 allIps.add(routerLinkLocalIpv6);
Pier Ventreadb4ae62016-11-23 09:57:42 -08001227 }
Saurav Das261c3002017-06-13 15:35:54 -07001228 if (pairRouterIpv4 != null) {
1229 allIps.add(pairRouterIpv4);
1230 }
1231 if (pairRouterIpv6 != null) {
1232 allIps.add(pairRouterIpv6);
1233 }
Pier Ventreadb4ae62016-11-23 09:57:42 -08001234 for (IpAddress ipaddr : allIps) {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001235 populateSingleIpPunts(deviceId, ipaddr);
1236 }
1237 }
Charles Chan2d0bbcd2017-01-09 11:45:08 -08001238
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001239 /**
1240 * Creates a forwarding objective to punt all IP packets, destined to the
1241 * specified IP address, which should be router's port IP address.
1242 *
1243 * @param deviceId the switch dpid for the router
1244 * @param ipAddress the IP address of the router's port
1245 */
1246 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1247 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1248 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1249
1250 srManager.packetService.requestPackets(sbuilder.build(),
1251 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1252 }
1253
1254 /**
1255 * Removes a forwarding objective to punt all IP packets, destined to the
1256 * specified IP address, which should be router's port IP address.
1257 *
1258 * @param deviceId the switch dpid for the router
1259 * @param ipAddress the IP address of the router's port
1260 */
1261 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1262 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1263 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1264
1265 try {
1266 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1267 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1268 srManager.packetService.cancelPackets(sbuilder.build(),
1269 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1270 }
1271 } catch (DeviceConfigNotFoundException e) {
1272 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das9f1c42e2015-10-23 10:51:11 -07001273 }
sangho80f11cb2015-04-01 13:05:26 -07001274 }
1275
Charles Chanf4586112015-11-09 16:37:23 -08001276 /**
Pier Ventreadb4ae62016-11-23 09:57:42 -08001277 * Method to build IPv4 or IPv6 selector.
1278 *
1279 * @param addressToMatch the address to match
1280 */
1281 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1282 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1283 }
1284
1285 /**
1286 * Method to build IPv4 or IPv6 selector.
1287 *
1288 * @param prefixToMatch the prefix to match
1289 */
1290 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1291 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre229fd0b2016-10-31 16:49:19 -07001292 // If the prefix is IPv4
Pier Ventreadb4ae62016-11-23 09:57:42 -08001293 if (prefixToMatch.isIp4()) {
1294 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1295 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1296 return selectorBuilder;
1297 }
Pier Ventre229fd0b2016-10-31 16:49:19 -07001298 // If the prefix is IPv6
Pier Ventreadb4ae62016-11-23 09:57:42 -08001299 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1300 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1301 return selectorBuilder;
1302 }
1303
1304 /**
Pier Luigib9632ba2017-01-12 18:14:58 -08001305 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1306 * Furthermore, these are applied only by the master instance. Deferred actions
1307 * are not cleared such that packets can be flooded in the cross connect use case
1308 *
1309 * @param deviceId the switch dpid for the router
1310 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001311 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre229fd0b2016-10-31 16:49:19 -07001312 // We are not the master just skip.
Pier Luigib9632ba2017-01-12 18:14:58 -08001313 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1314 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1315 deviceId);
1316 return;
1317 }
1318
Charles Chan3ed34d82017-06-22 18:03:14 -07001319 ForwardingObjective fwdObj;
Pier Luigib9632ba2017-01-12 18:14:58 -08001320 // We punt all ARP packets towards the controller.
Charles Chanef8d12e2017-12-05 21:07:38 -08001321 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigib9632ba2017-01-12 18:14:58 -08001322 .add(new ObjectiveContext() {
1323 @Override
1324 public void onError(Objective objective, ObjectiveError error) {
Charles Chan3ed34d82017-06-22 18:03:14 -07001325 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigib9632ba2017-01-12 18:14:58 -08001326 deviceId, error);
1327 }
1328 });
Charles Chan3ed34d82017-06-22 18:03:14 -07001329 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigib9632ba2017-01-12 18:14:58 -08001330
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001331 if (isIpv6Configured(deviceId)) {
1332 // We punt all NDP packets towards the controller.
1333 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1334 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1335 @Override
1336 public void onError(Objective objective, ObjectiveError error) {
1337 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1338 deviceId, error);
1339 }
1340 });
1341 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan051490d2018-01-11 11:48:18 -08001342 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001343 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001344
Saurav Dasec683dc2018-04-27 18:42:30 -07001345 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan3ed34d82017-06-22 18:03:14 -07001346 ForwardingObjective pairFwdObj;
1347 // Do not punt ARP packets from pair port
1348 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1349 .add(new ObjectiveContext() {
1350 @Override
1351 public void onError(Objective objective, ObjectiveError error) {
1352 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1353 deviceId, error);
1354 }
1355 });
1356 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1357
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001358 if (isIpv6Configured(deviceId)) {
1359 // Do not punt NDP packets from pair port
1360 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1361 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan3ed34d82017-06-22 18:03:14 -07001362 @Override
1363 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001364 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan3ed34d82017-06-22 18:03:14 -07001365 deviceId, error);
1366 }
1367 });
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001368 srManager.flowObjectiveService.forward(deviceId, obj);
1369 });
1370
1371 // Do not forward DAD packets from pair port
1372 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1373 .add(new ObjectiveContext() {
1374 @Override
1375 public void onError(Objective objective, ObjectiveError error) {
1376 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1377 deviceId, error);
1378 }
1379 });
1380 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1381 }
Charles Chan3ed34d82017-06-22 18:03:14 -07001382 });
Pier Luigib9632ba2017-01-12 18:14:58 -08001383 }
1384
Charles Chan3ed34d82017-06-22 18:03:14 -07001385 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1386 TrafficTreatment treatment, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001387 return DefaultForwardingObjective.builder()
Charles Chan3ed34d82017-06-22 18:03:14 -07001388 .withPriority(priority)
Pier Luigib9632ba2017-01-12 18:14:58 -08001389 .withSelector(selector)
1390 .fromApp(srManager.appId)
1391 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan3ed34d82017-06-22 18:03:14 -07001392 .withTreatment(treatment)
Pier Luigib9632ba2017-01-12 18:14:58 -08001393 .makePermanent();
1394 }
1395
Charles Chan3ed34d82017-06-22 18:03:14 -07001396 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigib9632ba2017-01-12 18:14:58 -08001397 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1398 sBuilder.matchEthType(TYPE_ARP);
Charles Chan3ed34d82017-06-22 18:03:14 -07001399 if (port != null) {
1400 sBuilder.matchInPort(port);
1401 }
Pier Luigib9632ba2017-01-12 18:14:58 -08001402
Charles Chan3ed34d82017-06-22 18:03:14 -07001403 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1404 if (punt) {
1405 tBuilder.punt();
1406 }
1407 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001408 }
1409
Charles Chan051490d2018-01-11 11:48:18 -08001410 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1411 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigib9632ba2017-01-12 18:14:58 -08001412
Charles Chan051490d2018-01-11 11:48:18 -08001413 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1414 .forEach(type -> {
1415 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1416 sBuilder.matchEthType(TYPE_IPV6)
1417 .matchIPProtocol(PROTOCOL_ICMP6)
1418 .matchIcmpv6Type(type);
1419 if (port != null) {
1420 sBuilder.matchInPort(port);
1421 }
1422
1423 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1424 if (punt) {
1425 tBuilder.punt();
1426 }
1427
1428 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1429 });
1430
1431 return result;
Charles Chan3ed34d82017-06-22 18:03:14 -07001432 }
1433
1434 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1435 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1436 sBuilder.matchEthType(TYPE_IPV6)
Charles Chane6bda752017-08-07 12:39:03 -07001437 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1438 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1439 // .matchIPProtocol(PROTOCOL_ICMP6)
1440 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan3ed34d82017-06-22 18:03:14 -07001441 if (port != null) {
1442 sBuilder.matchInPort(port);
1443 }
1444
1445 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1446 tBuilder.wipeDeferred();
1447 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigib9632ba2017-01-12 18:14:58 -08001448 }
1449
1450 /**
Charles Chan155ec442018-09-16 14:30:19 -07001451 * Block given prefix in routing table.
Charles Chanf4586112015-11-09 16:37:23 -08001452 *
Andrea Campanella60ce2222018-04-30 11:48:55 +02001453 * @param address the address to block
1454 * @param deviceId switch ID to set the rules
1455 */
1456 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1457 updateDefaultRouteBlackhole(deviceId, address, true);
1458 }
1459
1460 /**
Charles Chan155ec442018-09-16 14:30:19 -07001461 * Unblock given prefix in routing table.
Andrea Campanella60ce2222018-04-30 11:48:55 +02001462 *
1463 * @param address the address to block
1464 * @param deviceId switch ID to set the rules
1465 */
1466 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1467 updateDefaultRouteBlackhole(deviceId, address, false);
1468 }
1469
1470 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1471 try {
1472 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1473
1474 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1475 if (address.isIp4()) {
1476 sbuilder.matchIPDst(address);
1477 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1478 } else {
1479 sbuilder.matchIPv6Dst(address);
1480 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1481 }
1482
1483 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
Andrea Campanella60ce2222018-04-30 11:48:55 +02001484 tBuilder.wipeDeferred();
1485
1486 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1487 fob.withFlag(Flag.SPECIFIC)
1488 .withSelector(sbuilder.build())
1489 .withTreatment(tBuilder.build())
1490 .withPriority(getPriorityFromPrefix(address))
1491 .fromApp(srManager.appId)
1492 .makePermanent();
1493
1494 log.debug("{} blackhole forwarding objectives for dev: {}",
1495 install ? "Installing" : "Removing", deviceId);
1496 ObjectiveContext context = new DefaultObjectiveContext(
1497 (objective) -> log.debug("Forward for {} {}", deviceId,
1498 install ? "installed" : "removed"),
1499 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1500 install ? "install" : "remove", deviceId, error));
1501 if (install) {
1502 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1503 } else {
1504 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1505 }
1506 }
1507 } catch (DeviceConfigNotFoundException e) {
1508 log.info("Not populating blackhole for un-configured device {}", deviceId);
1509 }
1510
1511 }
1512
1513 /**
1514 * Populates a forwarding objective to send packets that miss other high
1515 * priority Bridging Table entries to a group that contains all ports of
1516 * its subnet.
1517 *
Charles Chanf4586112015-11-09 16:37:23 -08001518 * @param deviceId switch ID to set the rules
1519 */
Charles Chan3ed34d82017-06-22 18:03:14 -07001520 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan90772a72017-02-08 15:52:08 -08001521 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001522 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chanf4586112015-11-09 16:37:23 -08001523 });
1524 }
1525
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001526 /**
1527 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1528 * @param deviceId switch ID to set the rule
1529 * @param vlanId vlan ID to specify the subnet
1530 * @param install true to install the rule, false to revoke the rule
1531 */
1532 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1533 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1534
1535 if (nextId < 0) {
1536 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1537 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1538 return;
1539 }
1540
1541 // Driver should treat objective with MacAddress.NONE as the
1542 // subnet broadcast rule
1543 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1544 sbuilder.matchVlanId(vlanId);
1545 sbuilder.matchEthDst(MacAddress.NONE);
1546
1547 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1548 fob.withFlag(Flag.SPECIFIC)
1549 .withSelector(sbuilder.build())
1550 .nextStep(nextId)
1551 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1552 .fromApp(srManager.appId)
1553 .makePermanent();
1554 ObjectiveContext context = new DefaultObjectiveContext(
1555 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1556 (objective, error) ->
1557 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1558
1559 if (install) {
1560 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1561 } else {
1562 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1563 }
1564 }
1565
Charles Chan82ab1932016-01-30 23:22:37 -08001566 private int getPriorityFromPrefix(IpPrefix prefix) {
1567 return (prefix.isIp4()) ?
1568 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1569 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapalli8c83f1d2015-05-22 13:47:31 -07001570 }
Jonghwan Hyune5ef7622017-08-25 17:48:36 -07001571
1572 /**
1573 * Update Forwarding objective for each host and IP address connected to given port.
1574 * And create corresponding Simple Next objective if it does not exist.
1575 * Applied only when populating Forwarding objective
1576 * @param deviceId switch ID to set the rule
1577 * @param portNumber port number
1578 * @param prefix IP prefix of the route
1579 * @param hostMac MAC address of the next hop
1580 * @param vlanId Vlan ID of the port
1581 * @param popVlan true to pop vlan tag in TrafficTreatment
1582 * @param install true to populate the forwarding objective, false to revoke
1583 */
1584 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1585 VlanId vlanId, boolean popVlan, boolean install) {
1586 ForwardingObjective.Builder fob;
1587 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1588 MacAddress deviceMac;
1589 try {
1590 deviceMac = config.getDeviceMac(deviceId);
1591 } catch (DeviceConfigNotFoundException e) {
1592 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1593 return;
1594 }
1595
1596 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1597 tbuilder.deferred()
1598 .setEthDst(hostMac)
1599 .setEthSrc(deviceMac)
1600 .setOutput(portNumber);
1601
1602 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1603
1604 if (!popVlan) {
1605 tbuilder.setVlanId(vlanId);
1606 } else {
1607 mbuilder.matchVlanId(vlanId);
1608 }
1609
1610 // if the objective is to revoke an existing rule, and for some reason
1611 // the next-objective does not exist, then a new one should not be created
1612 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1613 tbuilder.build(), mbuilder.build(), install);
1614 if (portNextObjId == -1) {
1615 // Warning log will come from getPortNextObjective method
1616 return;
1617 }
1618
1619 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1620 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1621 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1622
1623 ObjectiveContext context = new DefaultObjectiveContext(
1624 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1625 (objective, error) ->
1626 log.warn("Failed to {} IP rule for route {}: {}",
1627 install ? "install" : "revoke", prefix, error));
1628 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1629
1630 if (!install) {
1631 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1632 if (grpHandler == null) {
1633 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1634 } else {
1635 // Remove L3UG for the given port and host
1636 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1637 }
1638 }
1639 }
Charles Chanf17f66b2018-02-26 21:33:25 -08001640
1641 /**
1642 * Checks if there is other enabled port within the given VLAN on the given device.
1643 *
1644 * @param deviceId device ID
1645 * @param vlanId VLAN ID
1646 * @return true if there is no more port enabled within the given VLAN on the given device
1647 */
1648 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1649 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1650 .filter(Port::isEnabled)
1651 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1652 .collect(Collectors.toSet());
1653
1654 return enabledPorts.stream().noneMatch(cp ->
1655 // Given vlanId is included in the vlan-tagged configuration
Charles Chan098ca202018-05-01 11:50:20 -07001656 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001657 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan098ca202018-05-01 11:50:20 -07001658 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Saurav Das9bf49582018-08-13 15:34:26 -07001659 vlanId.equals(srManager.getDefaultInternalVlan())) ||
Charles Chanf17f66b2018-02-26 21:33:25 -08001660 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1661 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1662 );
1663 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001664
1665 /**
1666 * Returns a forwarding objective builder for egress forwarding rules.
1667 * <p>
1668 * The forwarding objective installs flow rules to egress pipeline to push
1669 * two vlan headers with given inner, outer vlan ids and outer tpid.
1670 *
1671 * @param portNumber port where the next hop attaches to
1672 * @param dummyVlanId vlan ID of the packet to match
1673 * @param innerVlan inner vlan ID of the next hop
1674 * @param outerVlan outer vlan ID of the next hop
1675 * @param outerTpid outer TPID of the next hop
1676 * @return forwarding objective builder
1677 */
1678 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1679 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1680 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1681 sbuilder.matchVlanId(dummyVlanId);
1682 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1683 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1684
1685 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1686 tbuilder.pushVlan(outerTpid);
1687 } else {
1688 tbuilder.pushVlan();
1689 }
1690
1691 tbuilder.setVlanId(outerVlan);
1692 return DefaultForwardingObjective.builder()
1693 .withSelector(sbuilder.build())
1694 .withTreatment(tbuilder.build())
1695 .fromApp(srManager.appId)
1696 .makePermanent()
1697 .withPriority(DEFAULT_PRIORITY)
1698 .withFlag(ForwardingObjective.Flag.EGRESS);
1699 }
1700
1701 /**
1702 * Populates IP rules for a route that has double-tagged next hop.
1703 *
1704 * @param deviceId device ID of the device that next hop attaches to
1705 * @param prefix IP prefix of the route
1706 * @param hostMac MAC address of the next hop
1707 * @param dummyVlan Dummy Vlan ID allocated for this route
1708 * @param innerVlan inner Vlan ID of the next hop
1709 * @param outerVlan outer Vlan ID of the next hop
1710 * @param outerTpid outer TPID of the next hop
1711 * @param outPort port where the next hop attaches to
1712 */
1713 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId dummyVlan,
1714 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1715 ForwardingObjective.Builder fwdBuilder;
1716 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1717 prefix, deviceId, outPort);
1718
1719 ForwardingObjective.Builder egressFwdBuilder = egressFwdObjBuilder(
1720 outPort, dummyVlan, innerVlan, outerVlan, outerTpid);
1721 DefaultObjectiveContext egressFwdContext = new DefaultObjectiveContext(
1722 objective -> log.debug("Egress rule for IP {} is populated", prefix.address()),
1723 (objective, error) -> {
1724 log.warn("Failed to populate egress rule for IP {}: {}", prefix.address(), error);
1725 srManager.dummyVlanIdStore().remove(new DummyVlanIdStoreKey(
1726 new ConnectPoint(deviceId, outPort), prefix.address()
1727 ));
1728 });
1729 try {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001730 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, dummyVlan, outPort, false, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001731 } catch (DeviceConfigNotFoundException e) {
1732 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1733 return;
1734 }
1735 if (fwdBuilder == null) {
1736 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1737 deviceId, prefix);
1738 return;
1739 }
1740
1741 // Egress forwarding objective should be installed after the nextObjective for the output port is installed.
1742 // Installation of routingFwdObj will ensure the installation of the nextObjective.
1743 int nextId = fwdBuilder.add().nextId();
1744 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1745 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
1746 srManager.flowObjectiveService.forward(deviceId, egressFwdBuilder.add(egressFwdContext));
1747 }, (objective, error) ->
1748 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1749 );
1750 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1751 rulePopulationCounter.incrementAndGet();
1752 }
1753
1754 /**
1755 * Revokes IP rules for a route that has double-tagged next hop.
1756 *
1757 * @param deviceId device ID of the device that next hop attaches to
1758 * @param prefix IP prefix of the route
1759 * @param hostMac MAC address of the next hop
1760 * @param hostVlan Vlan ID of the next hop
1761 * @param innerVlan inner Vlan ID of the next hop
1762 * @param outerVlan outer Vlan ID of the next hop
1763 * @param outerTpid outer TPID of the next hop
1764 * @param outPort port where the next hop attaches to
1765 */
1766 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
1767 VlanId hostVlan, VlanId innerVlan, VlanId outerVlan,
1768 EthType outerTpid, PortNumber outPort) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001769 revokeRoute(deviceId, prefix, hostMac, hostVlan, outPort, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001770
1771 DummyVlanIdStoreKey key = new DummyVlanIdStoreKey(
1772 new ConnectPoint(deviceId, outPort), prefix.address());
1773 VlanId dummyVlanId = srManager.dummyVlanIdStore().get(key);
1774 if (dummyVlanId == null) {
1775 log.warn("Failed to retrieve dummy VLAN ID for {}/{} and {}",
1776 deviceId, outPort, prefix.address());
1777 return;
1778 }
1779 ForwardingObjective.Builder fob = egressFwdObjBuilder(
1780 outPort, dummyVlanId, innerVlan, outerVlan, outerTpid);
1781 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1782 log.debug("Egress rule for IP {} revoked", prefix.address());
1783 srManager.dummyVlanIdStore().remove(key);
1784 }, (objective, error) -> {
1785 log.warn("Failed to revoke egress rule for IP {}: {}", prefix.address(), error);
1786 });
1787 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1788 }
1789
Jonghwan Hyun671a7ab2018-04-30 09:27:21 -07001790 /**
1791 * Checks whether the specified port has IP configuration or not.
1792 *
1793 * @param cp ConnectPoint to check the existance of IP configuration
1794 * @return true if the port has IP configuration; false otherwise.
1795 */
1796 private boolean hasIPConfiguration(ConnectPoint cp) {
1797 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1798 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1799 }
Saurav Das9bf49582018-08-13 15:34:26 -07001800
1801 /**
1802 * Updates filtering rules for unconfigured ports on all devices for which
1803 * this controller instance is master.
1804 *
1805 * @param pushVlan true if the filtering rule requires a push vlan action
1806 * @param oldVlanId the vlanId to be removed
1807 * @param newVlanId the vlanId to be added
1808 */
1809 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1810 VlanId newVlanId) {
1811 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1812 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1813 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1814 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1815 && p.isEnabled()) {
1816 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1817 oldVlanId, false);
1818 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1819 newVlanId, true);
1820 }
1821 }
1822 }
1823 }
1824 }
1825
Charles Chanf0f7b5c2018-08-29 14:55:53 -07001826 private boolean isIpv6Configured(DeviceId deviceId) {
1827 boolean isIpv6Configured;
1828 try {
1829 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1830 } catch (DeviceConfigNotFoundException e) {
1831 isIpv6Configured = false;
1832 }
1833 return isIpv6Configured;
1834 }
sangho80f11cb2015-04-01 13:05:26 -07001835}