blob: 980418b4bb84d2d3df686310ecdf926efcdb4fa2 [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sanghob35a6192015-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 Ventre917127a2016-10-31 16:49:19 -070018import com.google.common.collect.Lists;
Charles Chan09bf2692018-01-11 11:48:18 -080019import com.google.common.collect.Sets;
Saurav Das8a0732e2015-11-20 15:27:53 -080020import org.onlab.packet.EthType;
sanghob35a6192015-04-01 13:05:26 -070021import org.onlab.packet.Ethernet;
Charles Chan78ec5052017-12-05 21:07:38 -080022import org.onlab.packet.IPv6;
sanghob35a6192015-04-01 13:05:26 -070023import org.onlab.packet.Ip4Address;
Pier Ventree0ae7a32016-11-23 09:57:42 -080024import org.onlab.packet.Ip6Address;
25import org.onlab.packet.IpAddress;
sanghob35a6192015-04-01 13:05:26 -070026import org.onlab.packet.IpPrefix;
27import org.onlab.packet.MacAddress;
sanghob35a6192015-04-01 13:05:26 -070028import org.onlab.packet.MplsLabel;
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -070029import org.onlab.packet.VlanId;
Charles Chane849c192016-01-11 18:28:54 -080030import org.onosproject.net.ConnectPoint;
Saurav Das3c82f192018-08-13 15:34:26 -070031import org.onosproject.net.Device;
Charles Chand2990362016-04-18 13:44:03 -070032import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -080033import org.onosproject.net.flowobjective.Objective;
Charles Chand2990362016-04-18 13:44:03 -070034import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -080035import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyunbfc35d42018-04-30 09:27:21 -070036import org.onosproject.net.intf.Interface;
Charles Chan2df0e8a2017-01-09 11:45:08 -080037import org.onosproject.net.packet.PacketPriority;
Charles Chan0b4e6182015-11-03 10:42:14 -080038import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
39import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Dasc88d4662017-05-15 15:34:25 -070040import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Saurav Das7bcbe702017-06-13 15:35:54 -070041import org.onosproject.segmentrouting.grouphandler.DestinationSet;
sanghob35a6192015-04-01 13:05:26 -070042import org.onosproject.net.DeviceId;
Saurav Das0e99e2b2015-10-28 12:39:42 -070043import org.onosproject.net.Port;
sanghob35a6192015-04-01 13:05:26 -070044import org.onosproject.net.PortNumber;
sanghob35a6192015-04-01 13:05:26 -070045import org.onosproject.net.flow.DefaultTrafficSelector;
46import org.onosproject.net.flow.DefaultTrafficTreatment;
sanghob35a6192015-04-01 13:05:26 -070047import org.onosproject.net.flow.TrafficSelector;
48import org.onosproject.net.flow.TrafficTreatment;
Srikanth Vavilapallif5b234a2015-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 Das822c4e22015-10-23 10:51:11 -070055import org.onosproject.net.flowobjective.ForwardingObjective.Flag;
Jonghwan Hyuna76bf032018-04-09 09:40:50 -070056import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
sanghob35a6192015-04-01 13:05:26 -070057import org.slf4j.Logger;
58import org.slf4j.LoggerFactory;
59
60import java.util.ArrayList;
Pier Ventre917127a2016-10-31 16:49:19 -070061import java.util.Collection;
62import java.util.Collections;
Saurav Das7bcbe702017-06-13 15:35:54 -070063import java.util.HashMap;
Saurav Das837e0bb2015-10-30 17:45:38 -070064import java.util.HashSet;
sanghob35a6192015-04-01 13:05:26 -070065import java.util.List;
Saurav Das7bcbe702017-06-13 15:35:54 -070066import java.util.Map;
Charles Chan2df0e8a2017-01-09 11:45:08 -080067import java.util.Optional;
sanghob35a6192015-04-01 13:05:26 -070068import java.util.Set;
sangho20eff1d2015-04-13 15:15:58 -070069import java.util.concurrent.atomic.AtomicLong;
Charles Chandd33be52018-02-26 21:33:25 -080070import java.util.stream.Collectors;
sanghob35a6192015-04-01 13:05:26 -070071
72import static com.google.common.base.Preconditions.checkNotNull;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -080073import static org.onlab.packet.Ethernet.TYPE_ARP;
74import static org.onlab.packet.Ethernet.TYPE_IPV6;
Charles Chan09bf2692018-01-11 11:48:18 -080075import static org.onlab.packet.ICMP6.NEIGHBOR_ADVERTISEMENT;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -080076import static org.onlab.packet.ICMP6.NEIGHBOR_SOLICITATION;
Charles Chan09bf2692018-01-11 11:48:18 -080077import static org.onlab.packet.ICMP6.ROUTER_ADVERTISEMENT;
78import static org.onlab.packet.ICMP6.ROUTER_SOLICITATION;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -080079import static org.onlab.packet.IPv6.PROTOCOL_ICMP6;
Jonghwan Hyuna76bf032018-04-09 09:40:50 -070080import static org.onosproject.segmentrouting.SegmentRoutingService.DEFAULT_PRIORITY;
sanghob35a6192015-04-01 13:05:26 -070081
Charles Chane849c192016-01-11 18:28:54 -080082/**
83 * Populator of segment routing flow rules.
84 */
sanghob35a6192015-04-01 13:05:26 -070085public class RoutingRulePopulator {
Charles Chan78ec5052017-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;
sanghob35a6192015-04-01 13:05:26 -070089
sangho20eff1d2015-04-13 15:15:58 -070090 private AtomicLong rulePopulationCounter;
sangho666cd6d2015-04-14 16:27:13 -070091 private SegmentRoutingManager srManager;
92 private DeviceConfiguration config;
Sneha Prem1da248c2019-04-07 02:06:07 -040093 private RouteSimplifierUtils routeSimplifierUtils;
Saurav Das822c4e22015-10-23 10:51:11 -070094
Andreas Pantelopoulos0eaa5162018-06-28 17:06:14 -070095 // used for signalling the driver to remove vlan table and tmac entry also
96 private static final long CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES = 1;
97 private static final long DOUBLE_TAGGED_METADATA_MASK = 0xffffffffffffffffL;
98
sanghob35a6192015-04-01 13:05:26 -070099 /**
100 * Creates a RoutingRulePopulator object.
101 *
Thomas Vachuskae10f56b2015-04-15 18:20:08 -0700102 * @param srManager segment routing manager reference
sanghob35a6192015-04-01 13:05:26 -0700103 */
Charles Chan65238242017-06-22 18:03:14 -0700104 RoutingRulePopulator(SegmentRoutingManager srManager) {
sanghob35a6192015-04-01 13:05:26 -0700105 this.srManager = srManager;
sangho666cd6d2015-04-14 16:27:13 -0700106 this.config = checkNotNull(srManager.deviceConfiguration);
sangho20eff1d2015-04-13 15:15:58 -0700107 this.rulePopulationCounter = new AtomicLong(0);
Sneha Prem1da248c2019-04-07 02:06:07 -0400108 this.routeSimplifierUtils = new RouteSimplifierUtils(srManager);
sangho20eff1d2015-04-13 15:15:58 -0700109 }
110
111 /**
112 * Resets the population counter.
113 */
Charles Chan65238242017-06-22 18:03:14 -0700114 void resetCounter() {
sangho20eff1d2015-04-13 15:15:58 -0700115 rulePopulationCounter.set(0);
116 }
117
118 /**
119 * Returns the number of rules populated.
Thomas Vachuska266b4432015-04-30 18:13:25 -0700120 *
121 * @return number of rules
sangho20eff1d2015-04-13 15:15:58 -0700122 */
Charles Chan65238242017-06-22 18:03:14 -0700123 long getCounter() {
sangho20eff1d2015-04-13 15:15:58 -0700124 return rulePopulationCounter.get();
sanghob35a6192015-04-01 13:05:26 -0700125 }
126
127 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700128 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
129 * output to given port.
130 *
131 * @param deviceId device ID
132 * @param port port
133 * @param mac mac address
134 * @param vlanId VLAN ID
135 */
136 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
137 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
138 if (fob == null) {
139 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
140 return;
141 }
142
143 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das2f2c9d02018-04-07 16:51:09 -0700144 (objective) -> log.debug("Brigding rule for {}/{} populated", mac, vlanId),
145 (objective, error) -> log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chan2ff1bac2018-03-29 16:03:41 -0700146 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
147 }
148
149 /**
150 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
151 * output to given port.
152 *
153 * @param deviceId device ID
154 * @param port port
155 * @param mac mac address
156 * @param vlanId VLAN ID
157 */
158 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
159 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
160 if (fob == null) {
161 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
162 return;
163 }
164
165 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das2f2c9d02018-04-07 16:51:09 -0700166 (objective) -> log.debug("Brigding rule for {}/{} revoked", mac, vlanId),
167 (objective, error) -> log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chan2ff1bac2018-03-29 16:03:41 -0700168 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
169 }
170
171 /**
172 * Generates a forwarding objective builder for bridging rules.
173 * <p>
174 * The forwarding objective bridges packets destined to a given MAC to
175 * given port on given device.
176 *
177 * @param deviceId Device that host attaches to
178 * @param mac MAC address of the host
179 * @param hostVlanId VLAN ID of the host
180 * @param outport Port that host attaches to
181 * @param revoke true if forwarding objective is meant to revoke forwarding rule
182 * @return Forwarding objective builder
183 */
184 private ForwardingObjective.Builder bridgingFwdObjBuilder(
185 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
186 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chanb30213c2018-05-01 11:50:20 -0700187 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
188 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
189 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan2ff1bac2018-03-29 16:03:41 -0700190
191 // Create host selector
192 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
193 sbuilder.matchEthDst(mac);
194
195 // Create host treatment
196 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
197 tbuilder.immediate().setOutput(outport);
198
199 // Create host meta
200 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
201
202 // Adjust the selector, treatment and meta according to VLAN configuration
203 if (taggedVlans.contains(hostVlanId)) {
204 sbuilder.matchVlanId(hostVlanId);
205 mbuilder.matchVlanId(hostVlanId);
206 } else if (hostVlanId.equals(VlanId.NONE)) {
207 if (untaggedVlan != null) {
208 sbuilder.matchVlanId(untaggedVlan);
209 mbuilder.matchVlanId(untaggedVlan);
210 tbuilder.immediate().popVlan();
211 } else if (nativeVlan != null) {
212 sbuilder.matchVlanId(nativeVlan);
213 mbuilder.matchVlanId(nativeVlan);
214 tbuilder.immediate().popVlan();
215 } else {
216 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
217 "vlan config", mac, hostVlanId, connectPoint);
218 return null;
219 }
220 } else {
221 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
222 mac, hostVlanId, connectPoint);
223 return null;
224 }
225
226 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
227 // If the objective is to revoke an existing rule, and for some reason
228 // the next-objective does not exist, then a new one should not be created
229 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
230 tbuilder.build(), mbuilder.build(), !revoke);
231 if (portNextObjId == -1) {
232 // Warning log will come from getPortNextObjective method
233 return null;
234 }
235
236 return DefaultForwardingObjective.builder()
237 .withFlag(ForwardingObjective.Flag.SPECIFIC)
238 .withSelector(sbuilder.build())
239 .nextStep(portNextObjId)
240 .withPriority(100)
241 .fromApp(srManager.appId)
242 .makePermanent();
243 }
244
245 /**
246 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
247 * and hostMAC connected to given port, and output to given port only when
248 * vlan information is valid.
249 *
250 * @param deviceId device ID that host attaches to
251 * @param portNum port number that host attaches to
252 * @param hostMac mac address of the host connected to the switch port
253 * @param vlanId Vlan ID configured on the switch port
254 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
255 * @param install true to populate the objective, false to revoke
256 */
257 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
258 // revokeBridging and bridgingFwdObjBuilder.
259 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
260 VlanId vlanId, boolean popVlan, boolean install) {
261 // Create host selector
262 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
263 sbuilder.matchEthDst(hostMac);
264
265 // Create host meta
266 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
267
268 sbuilder.matchVlanId(vlanId);
269 mbuilder.matchVlanId(vlanId);
270
271 // Create host treatment
272 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
273 tbuilder.immediate().setOutput(portNum);
274
275 if (popVlan) {
276 tbuilder.immediate().popVlan();
277 }
278
279 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
280 tbuilder.build(), mbuilder.build(), install);
281 if (portNextObjId != -1) {
282 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
283 .withFlag(ForwardingObjective.Flag.SPECIFIC)
284 .withSelector(sbuilder.build())
285 .nextStep(portNextObjId)
286 .withPriority(100)
287 .fromApp(srManager.appId)
288 .makePermanent();
289
290 ObjectiveContext context = new DefaultObjectiveContext(
291 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
292 install ? "populated" : "revoked"),
293 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
294 install ? "populate" : "revoke", hostMac, vlanId, error));
295 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
296 } else {
297 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
298 }
299 }
300
301 /**
302 * Populates IP rules for a route that has direct connection to the switch.
303 * This method should not be invoked directly without going through DefaultRoutingHandler.
sanghob35a6192015-04-01 13:05:26 -0700304 *
Charles Chan1cdecff2016-10-27 14:19:48 -0700305 * @param deviceId device ID of the device that next hop attaches to
306 * @param prefix IP prefix of the route
307 * @param hostMac MAC address of the next hop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800308 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700309 * @param outPort port where the next hop attaches to
Ruchi Sahota5d800282019-01-28 01:08:18 +0000310 * @param directHost host is of type direct or indirect
sanghob35a6192015-04-01 13:05:26 -0700311 */
Charles Chan2fde6d42017-08-23 14:46:43 -0700312 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota5d800282019-01-28 01:08:18 +0000313 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700314 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chan1cdecff2016-10-27 14:19:48 -0700315 prefix, deviceId, outPort);
Charles Chan68aa62d2015-11-09 16:37:23 -0800316 ForwardingObjective.Builder fwdBuilder;
Charles Chan0b4e6182015-11-03 10:42:14 -0800317 try {
Saurav Das961beb22017-03-29 19:09:17 -0700318 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Ruchi Sahota5d800282019-01-28 01:08:18 +0000319 hostVlanId, outPort, directHost, false);
Charles Chan0b4e6182015-11-03 10:42:14 -0800320 } catch (DeviceConfigNotFoundException e) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700321 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan0b4e6182015-11-03 10:42:14 -0800322 return;
323 }
Saurav Das59232cf2016-04-27 18:35:50 -0700324 if (fwdBuilder == null) {
Saurav Das76ae6812017-03-15 15:15:14 -0700325 log.warn("Aborting host routing table entry due "
Charles Chan1cdecff2016-10-27 14:19:48 -0700326 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das59232cf2016-04-27 18:35:50 -0700327 return;
328 }
Charles Chan2fde6d42017-08-23 14:46:43 -0700329
330 int nextId = fwdBuilder.add().nextId();
Charles Chand2990362016-04-18 13:44:03 -0700331 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan2fde6d42017-08-23 14:46:43 -0700332 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
333 prefix, nextId),
Charles Chand2990362016-04-18 13:44:03 -0700334 (objective, error) ->
Saurav Das7bcbe702017-06-13 15:35:54 -0700335 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das76ae6812017-03-15 15:15:14 -0700336 prefix, error));
Charles Chand2990362016-04-18 13:44:03 -0700337 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chan68aa62d2015-11-09 16:37:23 -0800338 rulePopulationCounter.incrementAndGet();
339 }
340
Charles Chane849c192016-01-11 18:28:54 -0800341 /**
Charles Chan1cdecff2016-10-27 14:19:48 -0700342 * Removes IP rules for a route when the next hop is gone.
Charles Chan2ff1bac2018-03-29 16:03:41 -0700343 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chane849c192016-01-11 18:28:54 -0800344 *
Charles Chan1cdecff2016-10-27 14:19:48 -0700345 * @param deviceId device ID of the device that next hop attaches to
346 * @param prefix IP prefix of the route
347 * @param hostMac MAC address of the next hop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800348 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700349 * @param outPort port that next hop attaches to
Ruchi Sahota5d800282019-01-28 01:08:18 +0000350 * @param directHost host is of type direct or indirect
Charles Chane849c192016-01-11 18:28:54 -0800351 */
Charles Chan2fde6d42017-08-23 14:46:43 -0700352 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota5d800282019-01-28 01:08:18 +0000353 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chan1cdecff2016-10-27 14:19:48 -0700354 log.debug("Revoke IP table entry for route {} at {}:{}",
355 prefix, deviceId, outPort);
Charles Chan68aa62d2015-11-09 16:37:23 -0800356 ForwardingObjective.Builder fwdBuilder;
357 try {
Saurav Das961beb22017-03-29 19:09:17 -0700358 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
Ruchi Sahota5d800282019-01-28 01:08:18 +0000359 hostVlanId, outPort, directHost, true);
Charles Chan68aa62d2015-11-09 16:37:23 -0800360 } catch (DeviceConfigNotFoundException e) {
361 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
362 return;
363 }
Charles Chan458b8262016-11-30 11:55:05 -0800364 if (fwdBuilder == null) {
365 log.warn("Aborting host routing table entries due "
366 + "to error for dev:{} route:{}", deviceId, prefix);
367 return;
368 }
Charles Chand2990362016-04-18 13:44:03 -0700369 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan1cdecff2016-10-27 14:19:48 -0700370 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chand2990362016-04-18 13:44:03 -0700371 (objective, error) ->
Charles Chan1cdecff2016-10-27 14:19:48 -0700372 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chand2990362016-04-18 13:44:03 -0700373 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chan68aa62d2015-11-09 16:37:23 -0800374 }
375
Charles Chan1cdecff2016-10-27 14:19:48 -0700376 /**
Charles Chanf6ec1532017-02-08 16:10:40 -0800377 * Returns a forwarding objective builder for routing rules.
378 * <p>
379 * The forwarding objective routes packets destined to a given prefix to
380 * given port on given device with given destination MAC.
Charles Chan1cdecff2016-10-27 14:19:48 -0700381 *
382 * @param deviceId device ID
383 * @param prefix prefix that need to be routed
384 * @param hostMac MAC address of the nexthop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800385 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700386 * @param outPort port where the nexthop attaches to
Saurav Das961beb22017-03-29 19:09:17 -0700387 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Ruchi Sahota5d800282019-01-28 01:08:18 +0000388 * @param directHost host is direct or indirect
Charles Chan1cdecff2016-10-27 14:19:48 -0700389 * @return forwarding objective builder
390 * @throws DeviceConfigNotFoundException if given device is not configured
391 */
Ruchi Sahota5d800282019-01-28 01:08:18 +0000392
Charles Chanf6ec1532017-02-08 16:10:40 -0800393 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chan1cdecff2016-10-27 14:19:48 -0700394 DeviceId deviceId, IpPrefix prefix,
Saurav Das961beb22017-03-29 19:09:17 -0700395 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
Ruchi Sahota5d800282019-01-28 01:08:18 +0000396 boolean directHost, boolean revoke)
Charles Chan68aa62d2015-11-09 16:37:23 -0800397 throws DeviceConfigNotFoundException {
398 MacAddress deviceMac;
399 deviceMac = config.getDeviceMac(deviceId);
Ruchi Sahota5d800282019-01-28 01:08:18 +0000400 int nextObjId = -1;
Charles Chan0b4e6182015-11-03 10:42:14 -0800401
Charles Chan7ffd81f2017-02-08 15:52:08 -0800402 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chanb30213c2018-05-01 11:50:20 -0700403 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
404 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
405 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sanghob35a6192015-04-01 13:05:26 -0700406
Charles Chan7ffd81f2017-02-08 15:52:08 -0800407 // Create route selector
408 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
409
410 // Create route treatment
Charles Chan1cdecff2016-10-27 14:19:48 -0700411 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho1e575652015-05-14 00:39:53 -0700412 tbuilder.deferred()
413 .setEthDst(hostMac)
Charles Chan0b4e6182015-11-03 10:42:14 -0800414 .setEthSrc(deviceMac)
sanghob35a6192015-04-01 13:05:26 -0700415 .setOutput(outPort);
Saurav Das4ce45962015-11-24 23:21:05 -0800416
Charles Chan7ffd81f2017-02-08 15:52:08 -0800417 // Create route meta
418 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan59cc16d2017-02-02 16:20:42 -0800419
Charles Chan7ffd81f2017-02-08 15:52:08 -0800420 // Adjust the meta according to VLAN configuration
421 if (taggedVlans.contains(hostVlanId)) {
422 tbuilder.setVlanId(hostVlanId);
423 } else if (hostVlanId.equals(VlanId.NONE)) {
424 if (untaggedVlan != null) {
425 mbuilder.matchVlanId(untaggedVlan);
426 } else if (nativeVlan != null) {
427 mbuilder.matchVlanId(nativeVlan);
428 } else {
Charles Chan65238242017-06-22 18:03:14 -0700429 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
430 hostMac, hostVlanId, connectPoint);
431 return null;
Charles Chan7ffd81f2017-02-08 15:52:08 -0800432 }
433 } else {
Jonghwan Hyuna76bf032018-04-09 09:40:50 -0700434 // Internally-assigned dummy VLAN id will be given as hostVlanId
435 // when destination is double-tagged.
436 VlanId vlanId = srManager.dummyVlanIdStore().get(
437 new DummyVlanIdStoreKey(connectPoint, prefix.address()));
438 if (vlanId != null && vlanId.equals(hostVlanId)) {
439 tbuilder.setVlanId(hostVlanId);
440 mbuilder.matchVlanId(VlanId.ANY);
441 } else {
442 log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
443 + " in tagged vlan", hostMac, hostVlanId, connectPoint);
444 return null;
445 }
Saurav Das59232cf2016-04-27 18:35:50 -0700446 }
Ruchi Sahota5d800282019-01-28 01:08:18 +0000447
448 if (directHost) {
449 // if the objective is to revoke an existing rule, and for some reason
450 // the next-objective does not exist, then a new one should not be created
451 nextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
Saurav Das961beb22017-03-29 19:09:17 -0700452 tbuilder.build(), mbuilder.build(), !revoke);
Ruchi Sahota5d800282019-01-28 01:08:18 +0000453 } else {
454 // if the objective is to revoke an existing rule, and for some reason
455 // the next-objective does not exist, then a new one should not be created
456 nextObjId = srManager.getMacVlanNextObjectiveId(deviceId, hostMac, hostVlanId,
Ruchi Sahotab555e592019-05-09 17:26:14 -0400457 outPort, !revoke);
Ruchi Sahota5d800282019-01-28 01:08:18 +0000458 }
459 if (nextObjId == -1) {
460 // Warning log will come from getMacVlanNextObjective method
Charles Chan7ffd81f2017-02-08 15:52:08 -0800461 return null;
462 }
463
Charles Chan68aa62d2015-11-09 16:37:23 -0800464 return DefaultForwardingObjective.builder()
Charles Chan7ffd81f2017-02-08 15:52:08 -0800465 .withSelector(sbuilder.build())
Ruchi Sahota5d800282019-01-28 01:08:18 +0000466 .nextStep(nextObjId)
Charles Chan68aa62d2015-11-09 16:37:23 -0800467 .fromApp(srManager.appId).makePermanent()
Charles Chan1cdecff2016-10-27 14:19:48 -0700468 .withPriority(getPriorityFromPrefix(prefix))
Charles Chan5270ed02016-01-30 23:22:37 -0800469 .withFlag(ForwardingObjective.Flag.SPECIFIC);
sanghob35a6192015-04-01 13:05:26 -0700470 }
471
472 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700473 * Populates IP flow rules for all the given prefixes reachable from the
474 * destination switch(es).
sanghob35a6192015-04-01 13:05:26 -0700475 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700476 * @param targetSw switch where rules are to be programmed
477 * @param subnets subnets/prefixes being added
478 * @param destSw1 destination switch where the prefixes are reachable
479 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
480 * Should be null if there is no paired destination switch (by config)
481 * or if the given prefixes are reachable only via destSw1
482 * @param nextHops a map containing a set of next-hops for each destination switch.
483 * If destSw2 is not null, then this map must contain an
484 * entry for destSw2 with its next-hops from the targetSw
485 * (although the next-hop set may be empty in certain scenarios).
486 * If destSw2 is null, there should not be an entry in this
487 * map for destSw2.
sanghob35a6192015-04-01 13:05:26 -0700488 * @return true if all rules are set successfully, false otherwise
489 */
Charles Chan65238242017-06-22 18:03:14 -0700490 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Sneha Prem1da248c2019-04-07 02:06:07 -0400491 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
492 // Get pair device of the target switch
493 Optional<DeviceId> pairDev = srManager.getPairDeviceId(targetSw);
494 // Route simplification will be off in case of the nexthop location at target switch is down
495 // (routing through spine case)
496 boolean routeSimplOff = pairDev.isPresent() && pairDev.get().equals(destSw1) && destSw2 == null;
pier8b4ba992019-04-24 16:12:47 +0200497 // Iterates over the routes. Checking:
Sneha Prem1da248c2019-04-07 02:06:07 -0400498 // If route simplification is enabled
499 // If the target device is another leaf in the network
500 if (srManager.routeSimplification && !routeSimplOff) {
pier8b4ba992019-04-24 16:12:47 +0200501 Set<IpPrefix> subnetsToBePopulated = Sets.newHashSet();
Sneha Prem1da248c2019-04-07 02:06:07 -0400502 for (IpPrefix subnet : subnets) {
503 // Skip route programming on the target device
504 // If route simplification applies
505 if (routeSimplifierUtils.hasLeafExclusionEnabledForPrefix(subnet)) {
506 // XXX route simplification assumes that source of the traffic
507 // towards the nexthops are co-located with the nexthops. In different
508 // scenarios will not work properly.
509 continue;
510 }
511 // populate the route in the remaning scenarios
pier8b4ba992019-04-24 16:12:47 +0200512 subnetsToBePopulated.add(subnet);
Sneha Prem1da248c2019-04-07 02:06:07 -0400513 }
pier8b4ba992019-04-24 16:12:47 +0200514 subnets = subnetsToBePopulated;
sanghob35a6192015-04-01 13:05:26 -0700515 }
pier8b4ba992019-04-24 16:12:47 +0200516 // populate the remaining routes in the target switch
517 return populateIpRulesForRouter(targetSw, subnets, destSw1, destSw2, nextHops);
Charles Chan93e71ba2016-04-29 14:38:22 -0700518 }
sanghob35a6192015-04-01 13:05:26 -0700519
Charles Chan93e71ba2016-04-29 14:38:22 -0700520 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700521 * Revokes IP flow rules for the subnets from given device.
Charles Chan93e71ba2016-04-29 14:38:22 -0700522 *
Charles Chan2ff1bac2018-03-29 16:03:41 -0700523 * @param targetSw target switch from which the subnets need to be removed
Charles Chan93e71ba2016-04-29 14:38:22 -0700524 * @param subnets subnet being removed
525 * @return true if all rules are removed successfully, false otherwise
526 */
Charles Chan2ff1bac2018-03-29 16:03:41 -0700527 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chan93e71ba2016-04-29 14:38:22 -0700528 for (IpPrefix subnet : subnets) {
Charles Chan2ff1bac2018-03-29 16:03:41 -0700529 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chan93e71ba2016-04-29 14:38:22 -0700530 return false;
531 }
532 }
sanghob35a6192015-04-01 13:05:26 -0700533 return true;
534 }
535
536 /**
pier8b4ba992019-04-24 16:12:47 +0200537 * Populates IP flow rules for a set of IP prefix in the target device.
538 * The prefix are reachable via destination device(s).
sanghob35a6192015-04-01 13:05:26 -0700539 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700540 * @param targetSw target device ID to set the rules
pier8b4ba992019-04-24 16:12:47 +0200541 * @param subnets the set of IP prefix
Saurav Das7bcbe702017-06-13 15:35:54 -0700542 * @param destSw1 destination switch where the prefixes are reachable
543 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
544 * Should be null if there is no paired destination switch (by config)
545 * or if the given prefixes are reachable only via destSw1
546 * @param nextHops map of destination switches and their next-hops.
547 * Should only contain destination switches that are
548 * actually meant to be routed to. If destSw2 is null, there
549 * should not be an entry for destSw2 in this map.
sanghob35a6192015-04-01 13:05:26 -0700550 * @return true if all rules are set successfully, false otherwise
551 */
pier8b4ba992019-04-24 16:12:47 +0200552 private boolean populateIpRulesForRouter(DeviceId targetSw,
553 Set<IpPrefix> subnets,
554 DeviceId destSw1, DeviceId destSw2,
555 Map<DeviceId, Set<DeviceId>> nextHops) {
556 // pre-compute the needed information
557 int segmentIdIPv41, segmentIdIPv42 = -1;
558 int segmentIdIPv61, segmentIdIPv62 = -1;
559 TrafficTreatment treatment = null;
560 DestinationSet dsIPv4, dsIPv6;
561 TrafficSelector metaIpv4Selector, metaIpv6Selector = null;
562 int nextIdIPv4, nextIdIPv6, nextId;
563 TrafficSelector selector;
564 // start with MPLS SIDs
Charles Chan0b4e6182015-11-03 10:42:14 -0800565 try {
pier8b4ba992019-04-24 16:12:47 +0200566 segmentIdIPv41 = config.getIPv4SegmentId(destSw1);
567 segmentIdIPv61 = config.getIPv6SegmentId(destSw1);
568 if (destSw2 != null) {
569 segmentIdIPv42 = config.getIPv4SegmentId(destSw2);
570 segmentIdIPv62 = config.getIPv6SegmentId(destSw2);
Pier Ventree0ae7a32016-11-23 09:57:42 -0800571 }
Charles Chan0b4e6182015-11-03 10:42:14 -0800572 } catch (DeviceConfigNotFoundException e) {
573 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
574 return false;
575 }
pier8b4ba992019-04-24 16:12:47 +0200576 // build the IPv4 and IPv6 destination set
Saurav Das7bcbe702017-06-13 15:35:54 -0700577 if (destSw2 == null) {
578 // single dst - create destination set based on next-hop
Saurav Dasa4020382018-02-14 14:14:54 -0800579 // If the next hop is the same as the final destination, then MPLS
580 // label is not set.
Saurav Das7bcbe702017-06-13 15:35:54 -0700581 Set<DeviceId> nhd1 = nextHops.get(destSw1);
582 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
pier8b4ba992019-04-24 16:12:47 +0200583 dsIPv4 = DestinationSet.createTypePushNone(destSw1);
584 dsIPv6 = DestinationSet.createTypePushNone(destSw1);
585 treatment = DefaultTrafficTreatment.builder()
586 .immediate()
587 .decNwTtl()
588 .build();
Saurav Das7bcbe702017-06-13 15:35:54 -0700589 } else {
pier8b4ba992019-04-24 16:12:47 +0200590 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1);
591 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1);
Saurav Das7bcbe702017-06-13 15:35:54 -0700592 }
593 } else {
594 // dst pair - IP rules for dst-pairs are always from other edge nodes
595 // the destination set needs to have both destinations, even if there
596 // are no next hops to one of them
pier8b4ba992019-04-24 16:12:47 +0200597 dsIPv4 = DestinationSet.createTypePushBos(segmentIdIPv41, destSw1, segmentIdIPv42, destSw2);
598 dsIPv6 = DestinationSet.createTypePushBos(segmentIdIPv61, destSw1, segmentIdIPv62, destSw2);
sanghob35a6192015-04-01 13:05:26 -0700599 }
600
Saurav Das8a0732e2015-11-20 15:27:53 -0800601 // setup metadata to pass to nextObjective - indicate the vlan on egress
602 // if needed by the switch pipeline. Since neighbor sets are always to
603 // other neighboring routers, there is no subnet assigned on those ports.
pier8b4ba992019-04-24 16:12:47 +0200604 metaIpv4Selector = buildIpv4Selector()
605 .matchVlanId(srManager.getDefaultInternalVlan())
606 .build();
607 metaIpv6Selector = buildIpv6Selector()
608 .matchVlanId(srManager.getDefaultInternalVlan())
609 .build();
610 // get the group handler of the target switch
Saurav Das7bcbe702017-06-13 15:35:54 -0700611 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700612 if (grpHandler == null) {
613 log.warn("populateIPRuleForRouter: groupHandler for device {} "
pier8b4ba992019-04-24 16:12:47 +0200614 + "not found", targetSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700615 return false;
616 }
pier8b4ba992019-04-24 16:12:47 +0200617 // get next id
618 nextIdIPv4 = grpHandler.getNextObjectiveId(dsIPv4, nextHops, metaIpv4Selector, false);
619 if (nextIdIPv4 <= 0) {
620 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv4);
sangho834e4b02015-05-01 09:38:25 -0700621 return false;
622 }
pier8b4ba992019-04-24 16:12:47 +0200623 nextIdIPv6 = grpHandler.getNextObjectiveId(dsIPv6, nextHops, metaIpv6Selector, false);
624 if (nextIdIPv6 <= 0) {
625 log.warn("No next objective in {} for ds: {}", targetSw, dsIPv6);
626 return false;
Charles Chan68aa62d2015-11-09 16:37:23 -0800627 }
pier8b4ba992019-04-24 16:12:47 +0200628 // build all the flow rules and send to the device
629 for (IpPrefix subnet : subnets) {
630 selector = buildIpSelectorFromIpPrefix(subnet).build();
631 if (subnet.isIp4()) {
632 nextId = nextIdIPv4;
633 } else {
634 nextId = nextIdIPv6;
635 }
636 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
637 .builder()
638 .fromApp(srManager.appId)
639 .makePermanent()
640 .nextStep(nextId)
641 .withSelector(selector)
642 .withPriority(getPriorityFromPrefix(subnet))
643 .withFlag(ForwardingObjective.Flag.SPECIFIC);
644 if (treatment != null) {
645 fwdBuilder.withTreatment(treatment);
646 }
647 log.debug("Installing {} forwarding objective for router IP/subnet {} "
648 + "in switch {} with nextId: {}", subnet.isIp4() ? "IPv4" : "IPv6",
649 subnet, targetSw, nextId);
650 ObjectiveContext context = new DefaultObjectiveContext(
651 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
652 subnet, targetSw),
653 (objective, error) -> log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
654 subnet, error, targetSw));
655 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
656 }
657 rulePopulationCounter.addAndGet(subnets.size());
sanghob35a6192015-04-01 13:05:26 -0700658 return true;
659 }
660
sanghob35a6192015-04-01 13:05:26 -0700661 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700662 * Revokes IP flow rules for the router IP address from given device.
Charles Chan93e71ba2016-04-29 14:38:22 -0700663 *
Charles Chan2ff1bac2018-03-29 16:03:41 -0700664 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chan93e71ba2016-04-29 14:38:22 -0700665 * @param ipPrefix the IP address of the destination router
666 * @return true if all rules are removed successfully, false otherwise
667 */
Charles Chan2ff1bac2018-03-29 16:03:41 -0700668 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre968da122016-12-09 17:26:04 -0800669 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chan93e71ba2016-04-29 14:38:22 -0700670 TrafficSelector selector = sbuilder.build();
671 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
672
673 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
674 .builder()
675 .fromApp(srManager.appId)
676 .makePermanent()
677 .withSelector(selector)
678 .withTreatment(dummyTreatment)
679 .withPriority(getPriorityFromPrefix(ipPrefix))
680 .withFlag(ForwardingObjective.Flag.SPECIFIC);
681
Charles Chan2ff1bac2018-03-29 16:03:41 -0700682 ObjectiveContext context = new DefaultObjectiveContext(
683 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
684 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
685 ipPrefix, targetSw, error));
686 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chan93e71ba2016-04-29 14:38:22 -0700687
688 return true;
689 }
690
691 /**
Saurav Dasa4020382018-02-14 14:14:54 -0800692 * Populates MPLS flow rules in the target device to point towards the
693 * destination device.
694 *
695 * @param targetSwId target device ID of the switch to set the rules
696 * @param destSwId destination switch device ID
697 * @param nextHops next hops switch ID list
698 * @param routerIp the router ip of the destination switch
699 * @return true if all rules are set successfully, false otherwise
700 */
701 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
702 Set<DeviceId> nextHops, IpAddress routerIp) {
703 int segmentId;
704 try {
705 if (routerIp.isIp4()) {
706 segmentId = config.getIPv4SegmentId(destSwId);
707 } else {
708 segmentId = config.getIPv6SegmentId(destSwId);
709 }
710 } catch (DeviceConfigNotFoundException e) {
711 log.warn(e.getMessage() + " Aborting populateMplsRule.");
712 return false;
713 }
714
715 List<ForwardingObjective> fwdObjs = new ArrayList<>();
716 Collection<ForwardingObjective> fwdObjsMpls;
717 // Generates the transit rules used by the standard "routing".
718 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
719 routerIp, true);
720 if (fwdObjsMpls.isEmpty()) {
721 return false;
722 }
723 fwdObjs.addAll(fwdObjsMpls);
724
725 // Generates the transit rules used by the MPLS Pwaas.
726 int pwSrLabel;
727 try {
728 pwSrLabel = config.getPWRoutingLabel(destSwId);
729 } catch (DeviceConfigNotFoundException e) {
730 log.warn(e.getMessage()
731 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
732 return false;
733 }
734 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
735 routerIp, false);
736 if (fwdObjsMpls.isEmpty()) {
737 return false;
738 }
739 fwdObjs.addAll(fwdObjsMpls);
740
741 for (ForwardingObjective fwdObj : fwdObjs) {
742 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
743 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
744 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
745 rulePopulationCounter.incrementAndGet();
746 }
747
748 return true;
749 }
750
751 /**
752 * Differentiates between popping and swapping labels when building an MPLS
753 * forwarding objective.
Pier Ventre917127a2016-10-31 16:49:19 -0700754 *
755 * @param targetSwId the target sw
756 * @param destSwId the destination sw
757 * @param nextHops the set of next hops
Saurav Dasa4020382018-02-14 14:14:54 -0800758 * @param segmentId the segmentId to match representing the destination
759 * switch
760 * @param routerIp the router ip representing the destination switch
Pier Ventre917127a2016-10-31 16:49:19 -0700761 * @return a collection of fwdobjective
762 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700763 private Collection<ForwardingObjective> handleMpls(
764 DeviceId targetSwId,
765 DeviceId destSwId,
766 Set<DeviceId> nextHops,
767 int segmentId,
768 IpAddress routerIp,
769 boolean isMplsBos) {
Pier Ventre917127a2016-10-31 16:49:19 -0700770
771 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
772 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi3bfe32c2017-01-30 09:47:36 -0800773 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre917127a2016-10-31 16:49:19 -0700774 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
775 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
776 sbuilder.matchMplsBos(isMplsBos);
777 TrafficSelector selector = sbuilder.build();
778
779 // setup metadata to pass to nextObjective - indicate the vlan on egress
780 // if needed by the switch pipeline. Since mpls next-hops are always to
781 // other neighboring routers, there is no subnet assigned on those ports.
782 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das3c82f192018-08-13 15:34:26 -0700783 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre917127a2016-10-31 16:49:19 -0700784
785 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
786 // If the next hop is the destination router for the segment, do pop
787 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das7bcbe702017-06-13 15:35:54 -0700788 + "label {} in switch {} with pop to next-hops {}",
789 segmentId, targetSwId, nextHops);
Saurav Das961beb22017-03-29 19:09:17 -0700790 ForwardingObjective.Builder fwdObjNoBosBuilder =
791 getMplsForwardingObjective(targetSwId,
792 nextHops,
793 true,
794 isMplsBos,
795 metabuilder.build(),
Saurav Dasc88d4662017-05-15 15:34:25 -0700796 routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800797 segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700798 destSwId);
Pier Ventre917127a2016-10-31 16:49:19 -0700799 // Error case, we cannot handle, exit.
800 if (fwdObjNoBosBuilder == null) {
801 return Collections.emptyList();
802 }
803 fwdObjBuilders.add(fwdObjNoBosBuilder);
804
805 } else {
Saurav Dasa4020382018-02-14 14:14:54 -0800806 // next hop is not destination, irrespective of the number of next
807 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das7bcbe702017-06-13 15:35:54 -0700808 log.debug("Installing MPLS forwarding objective for "
809 + "label {} in switch {} without pop to next-hops {}",
810 segmentId, targetSwId, nextHops);
Saurav Das961beb22017-03-29 19:09:17 -0700811 ForwardingObjective.Builder fwdObjNoBosBuilder =
812 getMplsForwardingObjective(targetSwId,
813 nextHops,
814 false,
815 isMplsBos,
816 metabuilder.build(),
Saurav Dasc88d4662017-05-15 15:34:25 -0700817 routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800818 segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700819 destSwId);
Pier Ventre917127a2016-10-31 16:49:19 -0700820 // Error case, we cannot handle, exit.
821 if (fwdObjNoBosBuilder == null) {
822 return Collections.emptyList();
823 }
824 fwdObjBuilders.add(fwdObjNoBosBuilder);
825
826 }
827
828 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
829 // We add the final property to the fwdObjs.
830 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre917127a2016-10-31 16:49:19 -0700831 ((Builder) ((Builder) fwdObjBuilder
832 .fromApp(srManager.appId)
833 .makePermanent())
834 .withSelector(selector)
835 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
836 .withFlag(ForwardingObjective.Flag.SPECIFIC);
837
838 ObjectiveContext context = new DefaultObjectiveContext(
839 (objective) ->
840 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
841 objective.id(), segmentId, targetSwId),
842 (objective, error) ->
843 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
844 objective.id(), segmentId, error, targetSwId));
845
846 ForwardingObjective fob = fwdObjBuilder.add(context);
847 fwdObjs.add(fob);
Pier Ventre917127a2016-10-31 16:49:19 -0700848 }
849
850 return fwdObjs;
851 }
852
853 /**
Saurav Dasa4020382018-02-14 14:14:54 -0800854 * Returns a Forwarding Objective builder for the MPLS rule that references
855 * the desired Next Objective. Creates a DestinationSet that allows the
856 * groupHandler to create or find the required next objective.
sanghob35a6192015-04-01 13:05:26 -0700857 *
Saurav Dasa4020382018-02-14 14:14:54 -0800858 * @param targetSw the target sw
859 * @param nextHops the set of next hops
860 * @param phpRequired true if penultimate-hop-popping is required
861 * @param isBos true if matched label is bottom-of-stack
862 * @param meta metadata for creating next objective
863 * @param routerIp the router ip representing the destination switch
864 * @param destSw the destination sw
865 * @return the mpls forwarding objective builder
sanghob35a6192015-04-01 13:05:26 -0700866 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800867 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das7bcbe702017-06-13 15:35:54 -0700868 DeviceId targetSw,
Saurav Das8a0732e2015-11-20 15:27:53 -0800869 Set<DeviceId> nextHops,
870 boolean phpRequired,
871 boolean isBos,
Pier Ventree0ae7a32016-11-23 09:57:42 -0800872 TrafficSelector meta,
Saurav Dasc88d4662017-05-15 15:34:25 -0700873 IpAddress routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800874 int segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700875 DeviceId destSw) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800876
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700877 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
878 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sanghob35a6192015-04-01 13:05:26 -0700879
880 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Dasa4020382018-02-14 14:14:54 -0800881 DestinationSet ds = null;
Andreas Pantelopoulose8d5f412018-05-01 14:56:05 -0700882 DestinationSet.DestinationSetType dstType = null;
Saurav Dasa4020382018-02-14 14:14:54 -0800883 boolean simple = false;
sanghob35a6192015-04-01 13:05:26 -0700884 if (phpRequired) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800885 // php case - pop should always be flow-action
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700886 log.debug("getMplsForwardingObjective: php required");
sangho1e575652015-05-14 00:39:53 -0700887 tbuilder.deferred().copyTtlIn();
sanghob35a6192015-04-01 13:05:26 -0700888 if (isBos) {
Pier Ventree0ae7a32016-11-23 09:57:42 -0800889 if (routerIp.isIp4()) {
890 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
891 } else {
892 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
893 }
894 tbuilder.decNwTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800895 // standard case -> BoS == True; pop results in IP packet and forwarding
896 // is via an ECMP group
Andreas Pantelopoulose8d5f412018-05-01 14:56:05 -0700897 ds = DestinationSet.createTypePopBos(destSw);
sanghob35a6192015-04-01 13:05:26 -0700898 } else {
Saurav Das8a0732e2015-11-20 15:27:53 -0800899 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
900 .decMplsTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800901 // double-label case -> BoS == False, pop results in MPLS packet
902 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulose8d5f412018-05-01 14:56:05 -0700903 ds = DestinationSet.createTypePopNotBos(destSw);
904 if (!srManager.getMplsEcmp()) {
905 simple = true;
Saurav Dasa4020382018-02-14 14:14:54 -0800906 }
sanghob35a6192015-04-01 13:05:26 -0700907 }
908 } else {
Saurav Das8a0732e2015-11-20 15:27:53 -0800909 // swap with self case - SR CONTINUE
Saurav Dasa4020382018-02-14 14:14:54 -0800910 log.debug("getMplsForwardingObjective: swap with self");
sangho1e575652015-05-14 00:39:53 -0700911 tbuilder.deferred().decMplsTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800912 // swap results in MPLS packet with same BoS bit regardless of bit value
913 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulose8d5f412018-05-01 14:56:05 -0700914 // differentiate here between swap with not bos or swap with bos
915 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
916 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
917 if (!srManager.getMplsEcmp()) {
Saurav Dasa4020382018-02-14 14:14:54 -0800918 simple = true;
919 }
sanghob35a6192015-04-01 13:05:26 -0700920 }
921
Saurav Das8a0732e2015-11-20 15:27:53 -0800922 fwdBuilder.withTreatment(tbuilder.build());
Saurav Dasa4020382018-02-14 14:14:54 -0800923 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
924 targetSw, ds);
Saurav Das7bcbe702017-06-13 15:35:54 -0700925 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
926 if (gh == null) {
927 log.warn("getNextObjectiveId query - groupHandler for device {} "
928 + "not found", targetSw);
929 return null;
930 }
Saurav Dasa4020382018-02-14 14:14:54 -0800931
Saurav Das7bcbe702017-06-13 15:35:54 -0700932 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
933 dstNextHops.put(destSw, nextHops);
Saurav Dasa4020382018-02-14 14:14:54 -0800934 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das8a0732e2015-11-20 15:27:53 -0800935 if (nextId <= 0) {
Saurav Dasa4020382018-02-14 14:14:54 -0800936 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das8a0732e2015-11-20 15:27:53 -0800937 return null;
Saurav Das25190812016-05-27 13:54:07 -0700938 } else {
Saurav Dasa4020382018-02-14 14:14:54 -0800939 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
940 nextId, targetSw, ds);
sanghob35a6192015-04-01 13:05:26 -0700941 }
942
Saurav Das8a0732e2015-11-20 15:27:53 -0800943 fwdBuilder.nextStep(nextId);
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700944 return fwdBuilder;
sanghob35a6192015-04-01 13:05:26 -0700945 }
946
947 /**
Saurav Das822c4e22015-10-23 10:51:11 -0700948 * Creates a filtering objective to permit all untagged packets with a
Saurav Das0e99e2b2015-10-28 12:39:42 -0700949 * dstMac corresponding to the router's MAC address. For those pipelines
950 * that need to internally assign vlans to untagged packets, this method
951 * provides per-subnet vlan-ids as metadata.
Saurav Das837e0bb2015-10-30 17:45:38 -0700952 * <p>
Saurav Das018605f2017-02-18 14:05:44 -0800953 * Note that the vlan assignment and filter programming should only be done by
954 * the master for a switch. This method is typically called at deviceAdd and
955 * programs filters only for the enabled ports of the device. For port-updates,
956 * that enable/disable ports after device add, singlePortFilter methods should
957 * be called.
sanghob35a6192015-04-01 13:05:26 -0700958 *
Saurav Das822c4e22015-10-23 10:51:11 -0700959 * @param deviceId the switch dpid for the router
Saurav Dasd2fded02016-12-02 15:43:47 -0800960 * @return PortFilterInfo information about the processed ports
sanghob35a6192015-04-01 13:05:26 -0700961 */
Charles Chan65238242017-06-22 18:03:14 -0700962 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das0e99e2b2015-10-28 12:39:42 -0700963 log.debug("Installing per-port filtering objective for untagged "
964 + "packets in device {}", deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -0800965
Saurav Das59232cf2016-04-27 18:35:50 -0700966 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hallcbd1b392017-01-18 20:15:44 -0800967 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das59232cf2016-04-27 18:35:50 -0700968 log.warn("Device {} ports not available. Unable to add MacVlan filters",
969 deviceId);
Saurav Dasd2fded02016-12-02 15:43:47 -0800970 return null;
Saurav Das59232cf2016-04-27 18:35:50 -0700971 }
Saurav Das018605f2017-02-18 14:05:44 -0800972 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das59232cf2016-04-27 18:35:50 -0700973 for (Port port : devPorts) {
Saurav Das25190812016-05-27 13:54:07 -0700974 if (!port.isEnabled()) {
975 disabledPorts++;
976 continue;
977 }
Charles Chan7e4f8192017-02-26 22:59:35 -0800978 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Das018605f2017-02-18 14:05:44 -0800979 filteredPorts++;
980 } else {
981 errorPorts++;
Saurav Das25190812016-05-27 13:54:07 -0700982 }
Saurav Das0e99e2b2015-10-28 12:39:42 -0700983 }
Charles Chan7f9737b2017-06-22 14:27:17 -0700984 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Das018605f2017-02-18 14:05:44 -0800985 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan15281332018-06-19 20:56:33 -0700986 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Das018605f2017-02-18 14:05:44 -0800987 }
988
989 /**
Charles Chan7e4f8192017-02-26 22:59:35 -0800990 * Creates or removes filtering objectives for a single port. Should only be
991 * called by the master for a switch.
Saurav Das018605f2017-02-18 14:05:44 -0800992 *
993 * @param deviceId device identifier
994 * @param portnum port identifier for port to be filtered
Charles Chan7e4f8192017-02-26 22:59:35 -0800995 * @param install true to install the filtering objective, false to remove
Saurav Das018605f2017-02-18 14:05:44 -0800996 * @return true if no errors occurred during the build of the filtering objective
997 */
Charles Chan65238242017-06-22 18:03:14 -0700998 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800999 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chanb30213c2018-05-01 11:50:20 -07001000 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
1001 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
1002 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan7ffd81f2017-02-08 15:52:08 -08001003
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001004 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan7ffd81f2017-02-08 15:52:08 -08001005 if (taggedVlans.size() != 0) {
1006 // Filter for tagged vlans
Charles Chanb30213c2018-05-01 11:50:20 -07001007 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan7e4f8192017-02-26 22:59:35 -08001008 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan7ffd81f2017-02-08 15:52:08 -08001009 return false;
1010 }
1011 if (nativeVlan != null) {
1012 // Filter for native vlan
Charles Chan7e4f8192017-02-26 22:59:35 -08001013 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -08001014 return false;
1015 }
1016 }
1017 } else if (untaggedVlan != null) {
1018 // Filter for untagged vlan
Charles Chan7e4f8192017-02-26 22:59:35 -08001019 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -08001020 return false;
1021 }
Jonghwan Hyunbfc35d42018-04-30 09:27:21 -07001022 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001023 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das3c82f192018-08-13 15:34:26 -07001024 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
1025 srManager.getDefaultInternalVlan(),
1026 install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -08001027 return false;
1028 }
Andreas Pantelopoulose8d5f412018-05-01 14:56:05 -07001029 // Filter for receiveing pseudowire traffic
Saurav Das3c82f192018-08-13 15:34:26 -07001030 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
1031 srManager.getPwTransportVlan(),
1032 install)) {
Andreas Pantelopoulose8d5f412018-05-01 14:56:05 -07001033 return false;
1034 }
Charles Chan7ffd81f2017-02-08 15:52:08 -08001035 }
1036 return true;
1037 }
1038
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001039 /**
1040 * Updates filtering objectives for a single port. Should only be called by
1041 * the master for a switch
1042 * @param deviceId device identifier
1043 * @param portNum port identifier for port to be filtered
1044 * @param pushVlan true to push vlan, false otherwise
1045 * @param vlanId vlan identifier
1046 * @param install true to install the filtering objective, false to remove
1047 */
1048 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
1049 boolean pushVlan, VlanId vlanId, boolean install) {
1050 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
1051 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
1052 deviceId, portNum, vlanId);
1053 }
1054 }
1055
Charles Chan7e4f8192017-02-26 22:59:35 -08001056 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1057 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburg5ebeeb22018-04-30 19:27:19 -04001058 boolean doTMAC = true;
1059
1060 if (!pushVlan) {
1061 // Skip the tagged vlans belonging to an interface without an IP address
1062 Set<Interface> ifaces = srManager.interfaceService
1063 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1064 .stream()
1065 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1066 .collect(Collectors.toSet());
1067 if (!ifaces.isEmpty()) {
1068 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1069 vlanId, deviceId, portnum);
1070 doTMAC = false;
1071 }
1072 }
1073
1074 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Das018605f2017-02-18 14:05:44 -08001075 if (fob == null) {
1076 // error encountered during build
1077 return false;
1078 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001079 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001080 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Das018605f2017-02-18 14:05:44 -08001081 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan7e4f8192017-02-26 22:59:35 -08001082 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Dasc88d4662017-05-15 15:34:25 -07001083 install ? "installed" : "removed"),
Charles Chan7e4f8192017-02-26 22:59:35 -08001084 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001085 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan7e4f8192017-02-26 22:59:35 -08001086 if (install) {
1087 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1088 } else {
1089 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan7ffd81f2017-02-08 15:52:08 -08001090 }
Charles Chan7ffd81f2017-02-08 15:52:08 -08001091 return true;
Saurav Das018605f2017-02-18 14:05:44 -08001092 }
1093
Charles Chan7ffd81f2017-02-08 15:52:08 -08001094 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburg5ebeeb22018-04-30 19:27:19 -04001095 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Das018605f2017-02-18 14:05:44 -08001096 MacAddress deviceMac;
1097 try {
1098 deviceMac = config.getDeviceMac(deviceId);
1099 } catch (DeviceConfigNotFoundException e) {
1100 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1101 return null;
1102 }
Saurav Das018605f2017-02-18 14:05:44 -08001103 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburg5ebeeb22018-04-30 19:27:19 -04001104
1105 if (doTMAC) {
1106 fob.withKey(Criteria.matchInPort(portnum))
1107 .addCondition(Criteria.matchEthDst(deviceMac))
1108 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1109 } else {
1110 fob.withKey(Criteria.matchInPort(portnum))
1111 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1112 }
Charles Chan7ffd81f2017-02-08 15:52:08 -08001113
Charles Chanc550f2e2017-12-19 19:55:57 -08001114 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1115
Charles Chan7ffd81f2017-02-08 15:52:08 -08001116 if (pushVlan) {
1117 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chanc550f2e2017-12-19 19:55:57 -08001118 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan7ffd81f2017-02-08 15:52:08 -08001119 } else {
1120 fob.addCondition(Criteria.matchVlanId(vlanId));
1121 }
1122
Charles Chanc550f2e2017-12-19 19:55:57 -08001123 // NOTE: Some switch hardware share the same filtering flow among different ports.
1124 // We use this metadata to let the driver know that there is no more enabled port
1125 // within the same VLAN on this device.
Charles Chandd33be52018-02-26 21:33:25 -08001126 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chanc550f2e2017-12-19 19:55:57 -08001127 tBuilder.wipeDeferred();
1128 }
1129
1130 fob.withMeta(tBuilder.build());
1131
Saurav Das018605f2017-02-18 14:05:44 -08001132 fob.permit().fromApp(srManager.appId);
1133 return fob;
sanghob35a6192015-04-01 13:05:26 -07001134 }
1135
1136 /**
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001137 * Creates or removes filtering objectives for a double-tagged host on a port.
1138 *
1139 * @param deviceId device identifier
1140 * @param portNum port identifier for port to be filtered
1141 * @param outerVlan outer VLAN ID
1142 * @param innerVlan inner VLAN ID
1143 * @param install true to install the filtering objective, false to remove
1144 */
1145 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1146 VlanId innerVlan, boolean install) {
Andreas Pantelopoulos0eaa5162018-06-28 17:06:14 -07001147 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum, outerVlan, innerVlan, false);
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001148 if (fob == null) {
1149 // error encountered during build
1150 return;
1151 }
1152 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1153 install ? "Installing" : "Removing", deviceId, portNum);
1154 ObjectiveContext context = new DefaultObjectiveContext(
1155 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1156 install ? "installed" : "removed"),
1157 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1158 install ? "install" : "remove", deviceId, portNum, error));
1159 if (install) {
1160 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1161 } else {
1162 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1163 }
1164 }
1165
1166 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
Andreas Pantelopoulos0eaa5162018-06-28 17:06:14 -07001167 VlanId outerVlan, VlanId innerVlan,
1168 boolean cleanupDoubleTaggedRules) {
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001169 MacAddress deviceMac;
1170 try {
1171 deviceMac = config.getDeviceMac(deviceId);
1172 } catch (DeviceConfigNotFoundException e) {
1173 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1174 return null;
1175 }
1176 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1177 // Outer vlan id match should be appeared before inner vlan id match.
1178 fob.withKey(Criteria.matchInPort(portNum))
1179 .addCondition(Criteria.matchEthDst(deviceMac))
1180 .addCondition(Criteria.matchVlanId(outerVlan))
1181 .addCondition(Criteria.matchVlanId(innerVlan))
1182 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1183
1184 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1185 // Pop outer vlan
1186 tBuilder.popVlan();
1187
Andreas Pantelopoulos0eaa5162018-06-28 17:06:14 -07001188 // special metadata for driver
1189 if (cleanupDoubleTaggedRules) {
1190 tBuilder.writeMetadata(CLEANUP_DOUBLE_TAGGED_HOST_ENTRIES, DOUBLE_TAGGED_METADATA_MASK);
1191 } else {
1192 tBuilder.writeMetadata(0, DOUBLE_TAGGED_METADATA_MASK);
1193 }
1194
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001195 // NOTE: Some switch hardware share the same filtering flow among different ports.
1196 // We use this metadata to let the driver know that there is no more enabled port
1197 // within the same VLAN on this device.
1198 if (noMoreEnabledPort(deviceId, outerVlan)) {
1199 tBuilder.wipeDeferred();
1200 }
1201
1202 fob.withMeta(tBuilder.build());
1203
1204 fob.permit().fromApp(srManager.appId);
1205 return fob;
1206 }
1207
1208 /**
Saurav Das822c4e22015-10-23 10:51:11 -07001209 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Das837e0bb2015-10-30 17:45:38 -07001210 * router's port IP addresses, to the controller. Note that the input
Saurav Das822c4e22015-10-23 10:51:11 -07001211 * port should not be matched on, as these packets can come from any input.
Saurav Das837e0bb2015-10-30 17:45:38 -07001212 * Furthermore, these are applied only by the master instance.
sanghob35a6192015-04-01 13:05:26 -07001213 *
Saurav Das822c4e22015-10-23 10:51:11 -07001214 * @param deviceId the switch dpid for the router
sanghob35a6192015-04-01 13:05:26 -07001215 */
Charles Chan65238242017-06-22 18:03:14 -07001216 void populateIpPunts(DeviceId deviceId) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001217 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chan78ec5052017-12-05 21:07:38 -08001218 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan0b4e6182015-11-03 10:42:14 -08001219 try {
Pier Ventree0ae7a32016-11-23 09:57:42 -08001220 routerIpv4 = config.getRouterIpv4(deviceId);
1221 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chan78ec5052017-12-05 21:07:38 -08001222 routerLinkLocalIpv6 = Ip6Address.valueOf(
1223 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1224
Saurav Das7bcbe702017-06-13 15:35:54 -07001225 if (config.isPairedEdge(deviceId)) {
1226 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1227 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1228 }
Charles Chan0b4e6182015-11-03 10:42:14 -08001229 } catch (DeviceConfigNotFoundException e) {
Charles Chanf6ec1532017-02-08 16:10:40 -08001230 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan0b4e6182015-11-03 10:42:14 -08001231 return;
1232 }
1233
Saurav Das837e0bb2015-10-30 17:45:38 -07001234 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1235 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1236 deviceId);
1237 return;
1238 }
Pier Ventree0ae7a32016-11-23 09:57:42 -08001239 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1240 allIps.add(routerIpv4);
Charles Chan78ec5052017-12-05 21:07:38 -08001241 allIps.add(routerLinkLocalIpv6);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001242 if (routerIpv6 != null) {
1243 allIps.add(routerIpv6);
1244 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001245 if (pairRouterIpv4 != null) {
1246 allIps.add(pairRouterIpv4);
1247 }
1248 if (pairRouterIpv6 != null) {
1249 allIps.add(pairRouterIpv6);
1250 }
Pier Ventree0ae7a32016-11-23 09:57:42 -08001251 for (IpAddress ipaddr : allIps) {
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001252 populateSingleIpPunts(deviceId, ipaddr);
1253 }
1254 }
Charles Chan2df0e8a2017-01-09 11:45:08 -08001255
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001256 /**
1257 * Creates a forwarding objective to punt all IP packets, destined to the
1258 * specified IP address, which should be router's port IP address.
1259 *
1260 * @param deviceId the switch dpid for the router
1261 * @param ipAddress the IP address of the router's port
1262 */
1263 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1264 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1265 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1266
1267 srManager.packetService.requestPackets(sbuilder.build(),
1268 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1269 }
1270
1271 /**
1272 * Removes a forwarding objective to punt all IP packets, destined to the
1273 * specified IP address, which should be router's port IP address.
1274 *
1275 * @param deviceId the switch dpid for the router
1276 * @param ipAddress the IP address of the router's port
1277 */
1278 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1279 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1280 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1281
1282 try {
1283 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1284 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1285 srManager.packetService.cancelPackets(sbuilder.build(),
1286 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1287 }
1288 } catch (DeviceConfigNotFoundException e) {
1289 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das822c4e22015-10-23 10:51:11 -07001290 }
sanghob35a6192015-04-01 13:05:26 -07001291 }
1292
pier8b4ba992019-04-24 16:12:47 +02001293 // Method for building an IPv4 selector
1294 private TrafficSelector.Builder buildIpv4Selector() {
1295 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1296 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1297 return selectorBuilder;
1298 }
1299
1300 // Method for building an IPv6 selector
1301 private TrafficSelector.Builder buildIpv6Selector() {
1302 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
1303 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1304 return selectorBuilder;
1305 }
1306
1307 // Method for building an IPv4 or IPv6 selector from an IP address
Pier Ventree0ae7a32016-11-23 09:57:42 -08001308 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1309 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1310 }
1311
pier8b4ba992019-04-24 16:12:47 +02001312 // Method for building an IPv4 or IPv6 selector from an IP prefix
Pier Ventree0ae7a32016-11-23 09:57:42 -08001313 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1314 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre917127a2016-10-31 16:49:19 -07001315 // If the prefix is IPv4
Pier Ventree0ae7a32016-11-23 09:57:42 -08001316 if (prefixToMatch.isIp4()) {
1317 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1318 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1319 return selectorBuilder;
1320 }
Pier Ventre917127a2016-10-31 16:49:19 -07001321 // If the prefix is IPv6
Pier Ventree0ae7a32016-11-23 09:57:42 -08001322 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1323 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1324 return selectorBuilder;
1325 }
1326
1327 /**
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001328 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1329 * Furthermore, these are applied only by the master instance. Deferred actions
1330 * are not cleared such that packets can be flooded in the cross connect use case
1331 *
1332 * @param deviceId the switch dpid for the router
1333 */
Charles Chan65238242017-06-22 18:03:14 -07001334 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre917127a2016-10-31 16:49:19 -07001335 // We are not the master just skip.
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001336 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1337 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1338 deviceId);
1339 return;
1340 }
1341
Charles Chan65238242017-06-22 18:03:14 -07001342 ForwardingObjective fwdObj;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001343 // We punt all ARP packets towards the controller.
Charles Chan78ec5052017-12-05 21:07:38 -08001344 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001345 .add(new ObjectiveContext() {
1346 @Override
1347 public void onError(Objective objective, ObjectiveError error) {
Charles Chan65238242017-06-22 18:03:14 -07001348 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001349 deviceId, error);
1350 }
1351 });
Charles Chan65238242017-06-22 18:03:14 -07001352 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001353
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001354 // We punt all NDP packets towards the controller.
Charles Chan09bf2692018-01-11 11:48:18 -08001355 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1356 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1357 @Override
1358 public void onError(Objective objective, ObjectiveError error) {
1359 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1360 deviceId, error);
1361 }
1362 });
1363 srManager.flowObjectiveService.forward(deviceId, obj);
1364 });
Charles Chan65238242017-06-22 18:03:14 -07001365
Saurav Das41b49a92018-04-27 18:42:30 -07001366 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan65238242017-06-22 18:03:14 -07001367 ForwardingObjective pairFwdObj;
1368 // Do not punt ARP packets from pair port
1369 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1370 .add(new ObjectiveContext() {
1371 @Override
1372 public void onError(Objective objective, ObjectiveError error) {
1373 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1374 deviceId, error);
1375 }
1376 });
1377 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1378
1379 // Do not punt NDP packets from pair port
Charles Chan09bf2692018-01-11 11:48:18 -08001380 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1381 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1382 @Override
1383 public void onError(Objective objective, ObjectiveError error) {
1384 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1385 deviceId, error);
1386 }
1387 });
1388 srManager.flowObjectiveService.forward(deviceId, obj);
1389 });
Charles Chan65238242017-06-22 18:03:14 -07001390
1391 // Do not forward DAD packets from pair port
1392 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1393 .add(new ObjectiveContext() {
1394 @Override
1395 public void onError(Objective objective, ObjectiveError error) {
1396 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1397 deviceId, error);
1398 }
1399 });
1400 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1401 });
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001402 }
1403
Charles Chan65238242017-06-22 18:03:14 -07001404 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1405 TrafficTreatment treatment, int priority) {
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001406 return DefaultForwardingObjective.builder()
Charles Chan65238242017-06-22 18:03:14 -07001407 .withPriority(priority)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001408 .withSelector(selector)
1409 .fromApp(srManager.appId)
1410 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan65238242017-06-22 18:03:14 -07001411 .withTreatment(treatment)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001412 .makePermanent();
1413 }
1414
Charles Chan65238242017-06-22 18:03:14 -07001415 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001416 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1417 sBuilder.matchEthType(TYPE_ARP);
Charles Chan65238242017-06-22 18:03:14 -07001418 if (port != null) {
1419 sBuilder.matchInPort(port);
1420 }
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001421
Charles Chan65238242017-06-22 18:03:14 -07001422 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1423 if (punt) {
1424 tBuilder.punt();
1425 }
1426 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001427 }
1428
Charles Chan09bf2692018-01-11 11:48:18 -08001429 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1430 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001431
Charles Chan09bf2692018-01-11 11:48:18 -08001432 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1433 .forEach(type -> {
1434 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1435 sBuilder.matchEthType(TYPE_IPV6)
1436 .matchIPProtocol(PROTOCOL_ICMP6)
1437 .matchIcmpv6Type(type);
1438 if (port != null) {
1439 sBuilder.matchInPort(port);
1440 }
1441
1442 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1443 if (punt) {
1444 tBuilder.punt();
1445 }
1446
1447 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1448 });
1449
1450 return result;
Charles Chan65238242017-06-22 18:03:14 -07001451 }
1452
1453 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1454 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1455 sBuilder.matchEthType(TYPE_IPV6)
Charles Chanc7e36aa2017-08-07 12:39:03 -07001456 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1457 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1458 // .matchIPProtocol(PROTOCOL_ICMP6)
1459 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan65238242017-06-22 18:03:14 -07001460 if (port != null) {
1461 sBuilder.matchInPort(port);
1462 }
1463
1464 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1465 tBuilder.wipeDeferred();
1466 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001467 }
1468
1469 /**
Charles Chan68aa62d2015-11-09 16:37:23 -08001470 * Populates a forwarding objective to send packets that miss other high
1471 * priority Bridging Table entries to a group that contains all ports of
1472 * its subnet.
1473 *
Andrea Campanella2ade0c92018-04-30 11:48:55 +02001474 * @param address the address to block
1475 * @param deviceId switch ID to set the rules
1476 */
1477 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1478 updateDefaultRouteBlackhole(deviceId, address, true);
1479 }
1480
1481 /**
1482 * Populates a forwarding objective to send packets that miss other high
1483 * priority Bridging Table entries to a group that contains all ports of
1484 * its subnet.
1485 *
1486 * @param address the address to block
1487 * @param deviceId switch ID to set the rules
1488 */
1489 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1490 updateDefaultRouteBlackhole(deviceId, address, false);
1491 }
1492
1493 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1494 try {
1495 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1496
1497 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1498 if (address.isIp4()) {
1499 sbuilder.matchIPDst(address);
1500 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1501 } else {
1502 sbuilder.matchIPv6Dst(address);
1503 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1504 }
1505
1506 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1507
1508 tBuilder.transition(60);
1509 tBuilder.wipeDeferred();
1510
1511 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1512 fob.withFlag(Flag.SPECIFIC)
1513 .withSelector(sbuilder.build())
1514 .withTreatment(tBuilder.build())
1515 .withPriority(getPriorityFromPrefix(address))
1516 .fromApp(srManager.appId)
1517 .makePermanent();
1518
1519 log.debug("{} blackhole forwarding objectives for dev: {}",
1520 install ? "Installing" : "Removing", deviceId);
1521 ObjectiveContext context = new DefaultObjectiveContext(
1522 (objective) -> log.debug("Forward for {} {}", deviceId,
1523 install ? "installed" : "removed"),
1524 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1525 install ? "install" : "remove", deviceId, error));
1526 if (install) {
1527 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1528 } else {
1529 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1530 }
1531 }
1532 } catch (DeviceConfigNotFoundException e) {
1533 log.info("Not populating blackhole for un-configured device {}", deviceId);
1534 }
1535
1536 }
1537
1538 /**
1539 * Populates a forwarding objective to send packets that miss other high
1540 * priority Bridging Table entries to a group that contains all ports of
1541 * its subnet.
1542 *
Charles Chan68aa62d2015-11-09 16:37:23 -08001543 * @param deviceId switch ID to set the rules
1544 */
Charles Chan65238242017-06-22 18:03:14 -07001545 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan7ffd81f2017-02-08 15:52:08 -08001546 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001547 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chan68aa62d2015-11-09 16:37:23 -08001548 });
1549 }
1550
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001551 /**
1552 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1553 * @param deviceId switch ID to set the rule
1554 * @param vlanId vlan ID to specify the subnet
1555 * @param install true to install the rule, false to revoke the rule
1556 */
1557 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1558 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1559
1560 if (nextId < 0) {
1561 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1562 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1563 return;
1564 }
1565
1566 // Driver should treat objective with MacAddress.NONE as the
1567 // subnet broadcast rule
1568 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1569 sbuilder.matchVlanId(vlanId);
1570 sbuilder.matchEthDst(MacAddress.NONE);
1571
1572 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1573 fob.withFlag(Flag.SPECIFIC)
1574 .withSelector(sbuilder.build())
1575 .nextStep(nextId)
1576 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1577 .fromApp(srManager.appId)
1578 .makePermanent();
1579 ObjectiveContext context = new DefaultObjectiveContext(
1580 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1581 (objective, error) ->
1582 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1583
1584 if (install) {
1585 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1586 } else {
1587 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1588 }
1589 }
1590
Charles Chan5270ed02016-01-30 23:22:37 -08001591 private int getPriorityFromPrefix(IpPrefix prefix) {
1592 return (prefix.isIp4()) ?
1593 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1594 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapallif3a8bc02015-05-22 13:47:31 -07001595 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001596
1597 /**
1598 * Update Forwarding objective for each host and IP address connected to given port.
1599 * And create corresponding Simple Next objective if it does not exist.
1600 * Applied only when populating Forwarding objective
1601 * @param deviceId switch ID to set the rule
1602 * @param portNumber port number
1603 * @param prefix IP prefix of the route
1604 * @param hostMac MAC address of the next hop
1605 * @param vlanId Vlan ID of the port
1606 * @param popVlan true to pop vlan tag in TrafficTreatment
1607 * @param install true to populate the forwarding objective, false to revoke
1608 */
1609 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1610 VlanId vlanId, boolean popVlan, boolean install) {
1611 ForwardingObjective.Builder fob;
1612 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1613 MacAddress deviceMac;
1614 try {
1615 deviceMac = config.getDeviceMac(deviceId);
1616 } catch (DeviceConfigNotFoundException e) {
1617 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1618 return;
1619 }
1620
1621 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1622 tbuilder.deferred()
1623 .setEthDst(hostMac)
1624 .setEthSrc(deviceMac)
1625 .setOutput(portNumber);
1626
1627 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1628
1629 if (!popVlan) {
1630 tbuilder.setVlanId(vlanId);
1631 } else {
1632 mbuilder.matchVlanId(vlanId);
1633 }
1634
1635 // if the objective is to revoke an existing rule, and for some reason
1636 // the next-objective does not exist, then a new one should not be created
1637 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1638 tbuilder.build(), mbuilder.build(), install);
1639 if (portNextObjId == -1) {
1640 // Warning log will come from getPortNextObjective method
1641 return;
1642 }
1643
1644 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1645 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1646 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1647
1648 ObjectiveContext context = new DefaultObjectiveContext(
1649 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1650 (objective, error) ->
1651 log.warn("Failed to {} IP rule for route {}: {}",
1652 install ? "install" : "revoke", prefix, error));
1653 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1654
1655 if (!install) {
1656 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1657 if (grpHandler == null) {
1658 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1659 } else {
1660 // Remove L3UG for the given port and host
1661 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1662 }
1663 }
1664 }
Charles Chandd33be52018-02-26 21:33:25 -08001665
1666 /**
1667 * Checks if there is other enabled port within the given VLAN on the given device.
1668 *
1669 * @param deviceId device ID
1670 * @param vlanId VLAN ID
1671 * @return true if there is no more port enabled within the given VLAN on the given device
1672 */
1673 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1674 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1675 .filter(Port::isEnabled)
1676 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1677 .collect(Collectors.toSet());
1678
1679 return enabledPorts.stream().noneMatch(cp ->
1680 // Given vlanId is included in the vlan-tagged configuration
Charles Chanb30213c2018-05-01 11:50:20 -07001681 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chandd33be52018-02-26 21:33:25 -08001682 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chanb30213c2018-05-01 11:50:20 -07001683 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Saurav Das3c82f192018-08-13 15:34:26 -07001684 vlanId.equals(srManager.getDefaultInternalVlan())) ||
Charles Chandd33be52018-02-26 21:33:25 -08001685 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1686 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1687 );
1688 }
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001689
1690 /**
1691 * Returns a forwarding objective builder for egress forwarding rules.
1692 * <p>
1693 * The forwarding objective installs flow rules to egress pipeline to push
1694 * two vlan headers with given inner, outer vlan ids and outer tpid.
1695 *
1696 * @param portNumber port where the next hop attaches to
1697 * @param dummyVlanId vlan ID of the packet to match
1698 * @param innerVlan inner vlan ID of the next hop
1699 * @param outerVlan outer vlan ID of the next hop
1700 * @param outerTpid outer TPID of the next hop
1701 * @return forwarding objective builder
1702 */
1703 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1704 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1705 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1706 sbuilder.matchVlanId(dummyVlanId);
1707 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1708 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1709
1710 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1711 tbuilder.pushVlan(outerTpid);
1712 } else {
1713 tbuilder.pushVlan();
1714 }
1715
1716 tbuilder.setVlanId(outerVlan);
1717 return DefaultForwardingObjective.builder()
1718 .withSelector(sbuilder.build())
1719 .withTreatment(tbuilder.build())
1720 .fromApp(srManager.appId)
1721 .makePermanent()
1722 .withPriority(DEFAULT_PRIORITY)
1723 .withFlag(ForwardingObjective.Flag.EGRESS);
1724 }
1725
1726 /**
1727 * Populates IP rules for a route that has double-tagged next hop.
1728 *
1729 * @param deviceId device ID of the device that next hop attaches to
1730 * @param prefix IP prefix of the route
1731 * @param hostMac MAC address of the next hop
1732 * @param dummyVlan Dummy Vlan ID allocated for this route
1733 * @param innerVlan inner Vlan ID of the next hop
1734 * @param outerVlan outer Vlan ID of the next hop
1735 * @param outerTpid outer TPID of the next hop
1736 * @param outPort port where the next hop attaches to
1737 */
1738 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId dummyVlan,
1739 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1740 ForwardingObjective.Builder fwdBuilder;
1741 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1742 prefix, deviceId, outPort);
1743
1744 ForwardingObjective.Builder egressFwdBuilder = egressFwdObjBuilder(
1745 outPort, dummyVlan, innerVlan, outerVlan, outerTpid);
1746 DefaultObjectiveContext egressFwdContext = new DefaultObjectiveContext(
1747 objective -> log.debug("Egress rule for IP {} is populated", prefix.address()),
1748 (objective, error) -> {
1749 log.warn("Failed to populate egress rule for IP {}: {}", prefix.address(), error);
1750 srManager.dummyVlanIdStore().remove(new DummyVlanIdStoreKey(
1751 new ConnectPoint(deviceId, outPort), prefix.address()
1752 ));
1753 });
1754 try {
Daniele Moro92f77292019-07-02 17:25:25 -07001755 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, dummyVlan, outPort, true, false);
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001756 } catch (DeviceConfigNotFoundException e) {
1757 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1758 return;
1759 }
1760 if (fwdBuilder == null) {
1761 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1762 deviceId, prefix);
1763 return;
1764 }
1765
1766 // Egress forwarding objective should be installed after the nextObjective for the output port is installed.
1767 // Installation of routingFwdObj will ensure the installation of the nextObjective.
1768 int nextId = fwdBuilder.add().nextId();
1769 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1770 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
1771 srManager.flowObjectiveService.forward(deviceId, egressFwdBuilder.add(egressFwdContext));
1772 }, (objective, error) ->
1773 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1774 );
1775 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1776 rulePopulationCounter.incrementAndGet();
1777 }
1778
1779 /**
1780 * Revokes IP rules for a route that has double-tagged next hop.
1781 *
1782 * @param deviceId device ID of the device that next hop attaches to
1783 * @param prefix IP prefix of the route
1784 * @param hostMac MAC address of the next hop
1785 * @param hostVlan Vlan ID of the next hop
1786 * @param innerVlan inner Vlan ID of the next hop
1787 * @param outerVlan outer Vlan ID of the next hop
1788 * @param outerTpid outer TPID of the next hop
1789 * @param outPort port where the next hop attaches to
1790 */
1791 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
1792 VlanId hostVlan, VlanId innerVlan, VlanId outerVlan,
1793 EthType outerTpid, PortNumber outPort) {
Ruchi Sahota5d800282019-01-28 01:08:18 +00001794 revokeRoute(deviceId, prefix, hostMac, hostVlan, outPort, false);
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001795
1796 DummyVlanIdStoreKey key = new DummyVlanIdStoreKey(
1797 new ConnectPoint(deviceId, outPort), prefix.address());
1798 VlanId dummyVlanId = srManager.dummyVlanIdStore().get(key);
1799 if (dummyVlanId == null) {
1800 log.warn("Failed to retrieve dummy VLAN ID for {}/{} and {}",
1801 deviceId, outPort, prefix.address());
1802 return;
1803 }
1804 ForwardingObjective.Builder fob = egressFwdObjBuilder(
1805 outPort, dummyVlanId, innerVlan, outerVlan, outerTpid);
1806 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1807 log.debug("Egress rule for IP {} revoked", prefix.address());
1808 srManager.dummyVlanIdStore().remove(key);
1809 }, (objective, error) -> {
1810 log.warn("Failed to revoke egress rule for IP {}: {}", prefix.address(), error);
1811 });
1812 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1813 }
1814
Jonghwan Hyunbfc35d42018-04-30 09:27:21 -07001815 /**
1816 * Checks whether the specified port has IP configuration or not.
1817 *
1818 * @param cp ConnectPoint to check the existance of IP configuration
1819 * @return true if the port has IP configuration; false otherwise.
1820 */
1821 private boolean hasIPConfiguration(ConnectPoint cp) {
1822 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1823 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1824 }
Saurav Das3c82f192018-08-13 15:34:26 -07001825
1826 /**
1827 * Updates filtering rules for unconfigured ports on all devices for which
1828 * this controller instance is master.
1829 *
1830 * @param pushVlan true if the filtering rule requires a push vlan action
1831 * @param oldVlanId the vlanId to be removed
1832 * @param newVlanId the vlanId to be added
1833 */
1834 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1835 VlanId newVlanId) {
1836 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1837 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1838 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1839 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1840 && p.isEnabled()) {
1841 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1842 oldVlanId, false);
1843 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1844 newVlanId, true);
1845 }
1846 }
1847 }
1848 }
1849 }
1850
sanghob35a6192015-04-01 13:05:26 -07001851}