blob: 90da4b4f3c7e5ac5cd91dc2c7f462ba8f0c0c591 [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;
Charles Chand2990362016-04-18 13:44:03 -070031import org.onosproject.net.flowobjective.DefaultObjectiveContext;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -080032import org.onosproject.net.flowobjective.Objective;
Charles Chand2990362016-04-18 13:44:03 -070033import org.onosproject.net.flowobjective.ObjectiveContext;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -080034import org.onosproject.net.flowobjective.ObjectiveError;
Jonghwan Hyun5efd7682018-04-30 09:27:21 -070035import org.onosproject.net.intf.Interface;
Charles Chan2df0e8a2017-01-09 11:45:08 -080036import org.onosproject.net.packet.PacketPriority;
Saurav Dasd2fded02016-12-02 15:43:47 -080037import org.onosproject.segmentrouting.DefaultRoutingHandler.PortFilterInfo;
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 Hyun800d9d02018-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;
Charles Chan59cc16d2017-02-02 16:20:42 -080080import static org.onosproject.segmentrouting.SegmentRoutingManager.INTERNAL_VLAN;
Jonghwan Hyun800d9d02018-04-09 09:40:50 -070081import static org.onosproject.segmentrouting.SegmentRoutingService.DEFAULT_PRIORITY;
sanghob35a6192015-04-01 13:05:26 -070082
Charles Chane849c192016-01-11 18:28:54 -080083/**
84 * Populator of segment routing flow rules.
85 */
sanghob35a6192015-04-01 13:05:26 -070086public class RoutingRulePopulator {
Charles Chan78ec5052017-12-05 21:07:38 -080087 private static final Logger log = LoggerFactory.getLogger(RoutingRulePopulator.class);
88
89 private static final int ARP_NDP_PRIORITY = 30000;
sanghob35a6192015-04-01 13:05:26 -070090
sangho20eff1d2015-04-13 15:15:58 -070091 private AtomicLong rulePopulationCounter;
sangho666cd6d2015-04-14 16:27:13 -070092 private SegmentRoutingManager srManager;
93 private DeviceConfiguration config;
Saurav Das822c4e22015-10-23 10:51:11 -070094
sanghob35a6192015-04-01 13:05:26 -070095 /**
96 * Creates a RoutingRulePopulator object.
97 *
Thomas Vachuskae10f56b2015-04-15 18:20:08 -070098 * @param srManager segment routing manager reference
sanghob35a6192015-04-01 13:05:26 -070099 */
Charles Chan65238242017-06-22 18:03:14 -0700100 RoutingRulePopulator(SegmentRoutingManager srManager) {
sanghob35a6192015-04-01 13:05:26 -0700101 this.srManager = srManager;
sangho666cd6d2015-04-14 16:27:13 -0700102 this.config = checkNotNull(srManager.deviceConfiguration);
sangho20eff1d2015-04-13 15:15:58 -0700103 this.rulePopulationCounter = new AtomicLong(0);
104 }
105
106 /**
107 * Resets the population counter.
108 */
Charles Chan65238242017-06-22 18:03:14 -0700109 void resetCounter() {
sangho20eff1d2015-04-13 15:15:58 -0700110 rulePopulationCounter.set(0);
111 }
112
113 /**
114 * Returns the number of rules populated.
Thomas Vachuska266b4432015-04-30 18:13:25 -0700115 *
116 * @return number of rules
sangho20eff1d2015-04-13 15:15:58 -0700117 */
Charles Chan65238242017-06-22 18:03:14 -0700118 long getCounter() {
sangho20eff1d2015-04-13 15:15:58 -0700119 return rulePopulationCounter.get();
sanghob35a6192015-04-01 13:05:26 -0700120 }
121
122 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700123 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
124 * output to given port.
125 *
126 * @param deviceId device ID
127 * @param port port
128 * @param mac mac address
129 * @param vlanId VLAN ID
130 */
131 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
132 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
133 if (fob == null) {
134 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
135 return;
136 }
137
138 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das2f2c9d02018-04-07 16:51:09 -0700139 (objective) -> log.debug("Brigding rule for {}/{} populated", mac, vlanId),
140 (objective, error) -> log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chan2ff1bac2018-03-29 16:03:41 -0700141 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
142 }
143
144 /**
145 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
146 * output to given port.
147 *
148 * @param deviceId device ID
149 * @param port port
150 * @param mac mac address
151 * @param vlanId VLAN ID
152 */
153 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
154 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
155 if (fob == null) {
156 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
157 return;
158 }
159
160 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das2f2c9d02018-04-07 16:51:09 -0700161 (objective) -> log.debug("Brigding rule for {}/{} revoked", mac, vlanId),
162 (objective, error) -> log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chan2ff1bac2018-03-29 16:03:41 -0700163 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
164 }
165
166 /**
167 * Generates a forwarding objective builder for bridging rules.
168 * <p>
169 * The forwarding objective bridges packets destined to a given MAC to
170 * given port on given device.
171 *
172 * @param deviceId Device that host attaches to
173 * @param mac MAC address of the host
174 * @param hostVlanId VLAN ID of the host
175 * @param outport Port that host attaches to
176 * @param revoke true if forwarding objective is meant to revoke forwarding rule
177 * @return Forwarding objective builder
178 */
179 private ForwardingObjective.Builder bridgingFwdObjBuilder(
180 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
181 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan971d7ba2018-05-01 11:50:20 -0700182 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
183 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
184 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan2ff1bac2018-03-29 16:03:41 -0700185
186 // Create host selector
187 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
188 sbuilder.matchEthDst(mac);
189
190 // Create host treatment
191 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
192 tbuilder.immediate().setOutput(outport);
193
194 // Create host meta
195 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
196
197 // Adjust the selector, treatment and meta according to VLAN configuration
198 if (taggedVlans.contains(hostVlanId)) {
199 sbuilder.matchVlanId(hostVlanId);
200 mbuilder.matchVlanId(hostVlanId);
201 } else if (hostVlanId.equals(VlanId.NONE)) {
202 if (untaggedVlan != null) {
203 sbuilder.matchVlanId(untaggedVlan);
204 mbuilder.matchVlanId(untaggedVlan);
205 tbuilder.immediate().popVlan();
206 } else if (nativeVlan != null) {
207 sbuilder.matchVlanId(nativeVlan);
208 mbuilder.matchVlanId(nativeVlan);
209 tbuilder.immediate().popVlan();
210 } else {
211 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
212 "vlan config", mac, hostVlanId, connectPoint);
213 return null;
214 }
215 } else {
216 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
217 mac, hostVlanId, connectPoint);
218 return null;
219 }
220
221 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
222 // If the objective is to revoke an existing rule, and for some reason
223 // the next-objective does not exist, then a new one should not be created
224 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
225 tbuilder.build(), mbuilder.build(), !revoke);
226 if (portNextObjId == -1) {
227 // Warning log will come from getPortNextObjective method
228 return null;
229 }
230
231 return DefaultForwardingObjective.builder()
232 .withFlag(ForwardingObjective.Flag.SPECIFIC)
233 .withSelector(sbuilder.build())
234 .nextStep(portNextObjId)
235 .withPriority(100)
236 .fromApp(srManager.appId)
237 .makePermanent();
238 }
239
240 /**
241 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
242 * and hostMAC connected to given port, and output to given port only when
243 * vlan information is valid.
244 *
245 * @param deviceId device ID that host attaches to
246 * @param portNum port number that host attaches to
247 * @param hostMac mac address of the host connected to the switch port
248 * @param vlanId Vlan ID configured on the switch port
249 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
250 * @param install true to populate the objective, false to revoke
251 */
252 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
253 // revokeBridging and bridgingFwdObjBuilder.
254 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
255 VlanId vlanId, boolean popVlan, boolean install) {
256 // Create host selector
257 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
258 sbuilder.matchEthDst(hostMac);
259
260 // Create host meta
261 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
262
263 sbuilder.matchVlanId(vlanId);
264 mbuilder.matchVlanId(vlanId);
265
266 // Create host treatment
267 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
268 tbuilder.immediate().setOutput(portNum);
269
270 if (popVlan) {
271 tbuilder.immediate().popVlan();
272 }
273
274 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
275 tbuilder.build(), mbuilder.build(), install);
276 if (portNextObjId != -1) {
277 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
278 .withFlag(ForwardingObjective.Flag.SPECIFIC)
279 .withSelector(sbuilder.build())
280 .nextStep(portNextObjId)
281 .withPriority(100)
282 .fromApp(srManager.appId)
283 .makePermanent();
284
285 ObjectiveContext context = new DefaultObjectiveContext(
286 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
287 install ? "populated" : "revoked"),
288 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
289 install ? "populate" : "revoke", hostMac, vlanId, error));
290 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
291 } else {
292 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
293 }
294 }
295
296 /**
297 * Populates IP rules for a route that has direct connection to the switch.
298 * This method should not be invoked directly without going through DefaultRoutingHandler.
sanghob35a6192015-04-01 13:05:26 -0700299 *
Charles Chan1cdecff2016-10-27 14:19:48 -0700300 * @param deviceId device ID of the device that next hop attaches to
301 * @param prefix IP prefix of the route
302 * @param hostMac MAC address of the next hop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800303 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700304 * @param outPort port where the next hop attaches to
sanghob35a6192015-04-01 13:05:26 -0700305 */
Charles Chan2fde6d42017-08-23 14:46:43 -0700306 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan7ffd81f2017-02-08 15:52:08 -0800307 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700308 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chan1cdecff2016-10-27 14:19:48 -0700309 prefix, deviceId, outPort);
Charles Chan68aa62d2015-11-09 16:37:23 -0800310 ForwardingObjective.Builder fwdBuilder;
Charles Chan0b4e6182015-11-03 10:42:14 -0800311 try {
Saurav Das961beb22017-03-29 19:09:17 -0700312 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
313 hostVlanId, outPort, false);
Charles Chan0b4e6182015-11-03 10:42:14 -0800314 } catch (DeviceConfigNotFoundException e) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700315 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan0b4e6182015-11-03 10:42:14 -0800316 return;
317 }
Saurav Das59232cf2016-04-27 18:35:50 -0700318 if (fwdBuilder == null) {
Saurav Das76ae6812017-03-15 15:15:14 -0700319 log.warn("Aborting host routing table entry due "
Charles Chan1cdecff2016-10-27 14:19:48 -0700320 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das59232cf2016-04-27 18:35:50 -0700321 return;
322 }
Charles Chan2fde6d42017-08-23 14:46:43 -0700323
324 int nextId = fwdBuilder.add().nextId();
Charles Chand2990362016-04-18 13:44:03 -0700325 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan2fde6d42017-08-23 14:46:43 -0700326 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
327 prefix, nextId),
Charles Chand2990362016-04-18 13:44:03 -0700328 (objective, error) ->
Saurav Das7bcbe702017-06-13 15:35:54 -0700329 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das76ae6812017-03-15 15:15:14 -0700330 prefix, error));
Charles Chand2990362016-04-18 13:44:03 -0700331 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chan68aa62d2015-11-09 16:37:23 -0800332 rulePopulationCounter.incrementAndGet();
333 }
334
Charles Chane849c192016-01-11 18:28:54 -0800335 /**
Charles Chan1cdecff2016-10-27 14:19:48 -0700336 * Removes IP rules for a route when the next hop is gone.
Charles Chan2ff1bac2018-03-29 16:03:41 -0700337 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chane849c192016-01-11 18:28:54 -0800338 *
Charles Chan1cdecff2016-10-27 14:19:48 -0700339 * @param deviceId device ID of the device that next hop attaches to
340 * @param prefix IP prefix of the route
341 * @param hostMac MAC address of the next hop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800342 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700343 * @param outPort port that next hop attaches to
Charles Chane849c192016-01-11 18:28:54 -0800344 */
Charles Chan2fde6d42017-08-23 14:46:43 -0700345 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan7ffd81f2017-02-08 15:52:08 -0800346 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Charles Chan1cdecff2016-10-27 14:19:48 -0700347 log.debug("Revoke IP table entry for route {} at {}:{}",
348 prefix, deviceId, outPort);
Charles Chan68aa62d2015-11-09 16:37:23 -0800349 ForwardingObjective.Builder fwdBuilder;
350 try {
Saurav Das961beb22017-03-29 19:09:17 -0700351 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
352 hostVlanId, outPort, true);
Charles Chan68aa62d2015-11-09 16:37:23 -0800353 } catch (DeviceConfigNotFoundException e) {
354 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
355 return;
356 }
Charles Chan458b8262016-11-30 11:55:05 -0800357 if (fwdBuilder == null) {
358 log.warn("Aborting host routing table entries due "
359 + "to error for dev:{} route:{}", deviceId, prefix);
360 return;
361 }
Charles Chand2990362016-04-18 13:44:03 -0700362 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan1cdecff2016-10-27 14:19:48 -0700363 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chand2990362016-04-18 13:44:03 -0700364 (objective, error) ->
Charles Chan1cdecff2016-10-27 14:19:48 -0700365 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chand2990362016-04-18 13:44:03 -0700366 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chan68aa62d2015-11-09 16:37:23 -0800367 }
368
Charles Chan1cdecff2016-10-27 14:19:48 -0700369 /**
Charles Chanf6ec1532017-02-08 16:10:40 -0800370 * Returns a forwarding objective builder for routing rules.
371 * <p>
372 * The forwarding objective routes packets destined to a given prefix to
373 * given port on given device with given destination MAC.
Charles Chan1cdecff2016-10-27 14:19:48 -0700374 *
375 * @param deviceId device ID
376 * @param prefix prefix that need to be routed
377 * @param hostMac MAC address of the nexthop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800378 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700379 * @param outPort port where the nexthop attaches to
Saurav Das961beb22017-03-29 19:09:17 -0700380 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Charles Chan1cdecff2016-10-27 14:19:48 -0700381 * @return forwarding objective builder
382 * @throws DeviceConfigNotFoundException if given device is not configured
383 */
Charles Chanf6ec1532017-02-08 16:10:40 -0800384 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chan1cdecff2016-10-27 14:19:48 -0700385 DeviceId deviceId, IpPrefix prefix,
Saurav Das961beb22017-03-29 19:09:17 -0700386 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
387 boolean revoke)
Charles Chan68aa62d2015-11-09 16:37:23 -0800388 throws DeviceConfigNotFoundException {
389 MacAddress deviceMac;
390 deviceMac = config.getDeviceMac(deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -0800391
Charles Chan7ffd81f2017-02-08 15:52:08 -0800392 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan971d7ba2018-05-01 11:50:20 -0700393 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
394 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
395 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sanghob35a6192015-04-01 13:05:26 -0700396
Charles Chan7ffd81f2017-02-08 15:52:08 -0800397 // Create route selector
398 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
399
400 // Create route treatment
Charles Chan1cdecff2016-10-27 14:19:48 -0700401 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho1e575652015-05-14 00:39:53 -0700402 tbuilder.deferred()
403 .setEthDst(hostMac)
Charles Chan0b4e6182015-11-03 10:42:14 -0800404 .setEthSrc(deviceMac)
sanghob35a6192015-04-01 13:05:26 -0700405 .setOutput(outPort);
Saurav Das4ce45962015-11-24 23:21:05 -0800406
Charles Chan7ffd81f2017-02-08 15:52:08 -0800407 // Create route meta
408 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan59cc16d2017-02-02 16:20:42 -0800409
Charles Chan7ffd81f2017-02-08 15:52:08 -0800410 // Adjust the meta according to VLAN configuration
411 if (taggedVlans.contains(hostVlanId)) {
412 tbuilder.setVlanId(hostVlanId);
413 } else if (hostVlanId.equals(VlanId.NONE)) {
414 if (untaggedVlan != null) {
415 mbuilder.matchVlanId(untaggedVlan);
416 } else if (nativeVlan != null) {
417 mbuilder.matchVlanId(nativeVlan);
418 } else {
Charles Chan65238242017-06-22 18:03:14 -0700419 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
420 hostMac, hostVlanId, connectPoint);
421 return null;
Charles Chan7ffd81f2017-02-08 15:52:08 -0800422 }
423 } else {
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700424 // Internally-assigned dummy VLAN id will be given as hostVlanId
425 // when destination is double-tagged.
426 VlanId vlanId = srManager.dummyVlanIdStore().get(
427 new DummyVlanIdStoreKey(connectPoint, prefix.address()));
428 if (vlanId != null && vlanId.equals(hostVlanId)) {
429 tbuilder.setVlanId(hostVlanId);
430 mbuilder.matchVlanId(VlanId.ANY);
431 } else {
432 log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
433 + " in tagged vlan", hostMac, hostVlanId, connectPoint);
434 return null;
435 }
Saurav Das59232cf2016-04-27 18:35:50 -0700436 }
Saurav Das961beb22017-03-29 19:09:17 -0700437 // if the objective is to revoke an existing rule, and for some reason
438 // the next-objective does not exist, then a new one should not be created
Charles Chan7ffd81f2017-02-08 15:52:08 -0800439 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
Saurav Das961beb22017-03-29 19:09:17 -0700440 tbuilder.build(), mbuilder.build(), !revoke);
Charles Chan7ffd81f2017-02-08 15:52:08 -0800441 if (portNextObjId == -1) {
442 // Warning log will come from getPortNextObjective method
443 return null;
444 }
445
Charles Chan68aa62d2015-11-09 16:37:23 -0800446 return DefaultForwardingObjective.builder()
Charles Chan7ffd81f2017-02-08 15:52:08 -0800447 .withSelector(sbuilder.build())
Saurav Das4ce45962015-11-24 23:21:05 -0800448 .nextStep(portNextObjId)
Charles Chan68aa62d2015-11-09 16:37:23 -0800449 .fromApp(srManager.appId).makePermanent()
Charles Chan1cdecff2016-10-27 14:19:48 -0700450 .withPriority(getPriorityFromPrefix(prefix))
Charles Chan5270ed02016-01-30 23:22:37 -0800451 .withFlag(ForwardingObjective.Flag.SPECIFIC);
sanghob35a6192015-04-01 13:05:26 -0700452 }
453
454 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700455 * Populates IP flow rules for all the given prefixes reachable from the
456 * destination switch(es).
sanghob35a6192015-04-01 13:05:26 -0700457 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700458 * @param targetSw switch where rules are to be programmed
459 * @param subnets subnets/prefixes being added
460 * @param destSw1 destination switch where the prefixes are reachable
461 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
462 * Should be null if there is no paired destination switch (by config)
463 * or if the given prefixes are reachable only via destSw1
464 * @param nextHops a map containing a set of next-hops for each destination switch.
465 * If destSw2 is not null, then this map must contain an
466 * entry for destSw2 with its next-hops from the targetSw
467 * (although the next-hop set may be empty in certain scenarios).
468 * If destSw2 is null, there should not be an entry in this
469 * map for destSw2.
sanghob35a6192015-04-01 13:05:26 -0700470 * @return true if all rules are set successfully, false otherwise
471 */
Charles Chan65238242017-06-22 18:03:14 -0700472 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das7bcbe702017-06-13 15:35:54 -0700473 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700474 for (IpPrefix subnet : subnets) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700475 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
sanghob35a6192015-04-01 13:05:26 -0700476 return false;
477 }
478 }
Charles Chan93e71ba2016-04-29 14:38:22 -0700479 return true;
480 }
sanghob35a6192015-04-01 13:05:26 -0700481
Charles Chan93e71ba2016-04-29 14:38:22 -0700482 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700483 * Revokes IP flow rules for the subnets from given device.
Charles Chan93e71ba2016-04-29 14:38:22 -0700484 *
Charles Chan2ff1bac2018-03-29 16:03:41 -0700485 * @param targetSw target switch from which the subnets need to be removed
Charles Chan93e71ba2016-04-29 14:38:22 -0700486 * @param subnets subnet being removed
487 * @return true if all rules are removed successfully, false otherwise
488 */
Charles Chan2ff1bac2018-03-29 16:03:41 -0700489 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chan93e71ba2016-04-29 14:38:22 -0700490 for (IpPrefix subnet : subnets) {
Charles Chan2ff1bac2018-03-29 16:03:41 -0700491 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chan93e71ba2016-04-29 14:38:22 -0700492 return false;
493 }
494 }
sanghob35a6192015-04-01 13:05:26 -0700495 return true;
496 }
497
498 /**
Saurav Das25190812016-05-27 13:54:07 -0700499 * Populates IP flow rules for an IP prefix in the target device. The prefix
Saurav Das7bcbe702017-06-13 15:35:54 -0700500 * is reachable via destination device(s).
sanghob35a6192015-04-01 13:05:26 -0700501 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700502 * @param targetSw target device ID to set the rules
503 * @param ipPrefix the IP prefix
504 * @param destSw1 destination switch where the prefixes are reachable
505 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
506 * Should be null if there is no paired destination switch (by config)
507 * or if the given prefixes are reachable only via destSw1
508 * @param nextHops map of destination switches and their next-hops.
509 * Should only contain destination switches that are
510 * actually meant to be routed to. If destSw2 is null, there
511 * should not be an entry for destSw2 in this map.
sanghob35a6192015-04-01 13:05:26 -0700512 * @return true if all rules are set successfully, false otherwise
513 */
Charles Chan65238242017-06-22 18:03:14 -0700514 private boolean populateIpRuleForRouter(DeviceId targetSw,
Saurav Das7bcbe702017-06-13 15:35:54 -0700515 IpPrefix ipPrefix, DeviceId destSw1,
516 DeviceId destSw2,
517 Map<DeviceId, Set<DeviceId>> nextHops) {
518 int segmentId1, segmentId2 = -1;
Charles Chan0b4e6182015-11-03 10:42:14 -0800519 try {
Pier Ventree0ae7a32016-11-23 09:57:42 -0800520 if (ipPrefix.isIp4()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700521 segmentId1 = config.getIPv4SegmentId(destSw1);
522 if (destSw2 != null) {
523 segmentId2 = config.getIPv4SegmentId(destSw2);
524 }
Pier Ventree0ae7a32016-11-23 09:57:42 -0800525 } else {
Saurav Das7bcbe702017-06-13 15:35:54 -0700526 segmentId1 = config.getIPv6SegmentId(destSw1);
527 if (destSw2 != null) {
528 segmentId2 = config.getIPv6SegmentId(destSw2);
529 }
Pier Ventree0ae7a32016-11-23 09:57:42 -0800530 }
Charles Chan0b4e6182015-11-03 10:42:14 -0800531 } catch (DeviceConfigNotFoundException e) {
532 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
533 return false;
534 }
sanghob35a6192015-04-01 13:05:26 -0700535
Pier Ventree0ae7a32016-11-23 09:57:42 -0800536 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chan68aa62d2015-11-09 16:37:23 -0800537 TrafficSelector selector = sbuilder.build();
sanghob35a6192015-04-01 13:05:26 -0700538
Charles Chan68aa62d2015-11-09 16:37:23 -0800539 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700540 DestinationSet ds;
Charles Chan68aa62d2015-11-09 16:37:23 -0800541 TrafficTreatment treatment;
sanghob35a6192015-04-01 13:05:26 -0700542
Saurav Das7bcbe702017-06-13 15:35:54 -0700543 if (destSw2 == null) {
544 // single dst - create destination set based on next-hop
Saurav Dasa4020382018-02-14 14:14:54 -0800545 // If the next hop is the same as the final destination, then MPLS
546 // label is not set.
Saurav Das7bcbe702017-06-13 15:35:54 -0700547 Set<DeviceId> nhd1 = nextHops.get(destSw1);
548 if (nhd1.size() == 1 && nhd1.iterator().next().equals(destSw1)) {
549 tbuilder.immediate().decNwTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800550 ds = new DestinationSet(false, false, destSw1);
Saurav Das7bcbe702017-06-13 15:35:54 -0700551 treatment = tbuilder.build();
552 } else {
Saurav Dasa4020382018-02-14 14:14:54 -0800553 ds = new DestinationSet(false, false, segmentId1, destSw1);
Saurav Das7bcbe702017-06-13 15:35:54 -0700554 treatment = null;
555 }
556 } else {
557 // dst pair - IP rules for dst-pairs are always from other edge nodes
558 // the destination set needs to have both destinations, even if there
559 // are no next hops to one of them
Saurav Dasa4020382018-02-14 14:14:54 -0800560 ds = new DestinationSet(false, false, segmentId1, destSw1,
561 segmentId2, destSw2);
Charles Chan68aa62d2015-11-09 16:37:23 -0800562 treatment = null;
sanghob35a6192015-04-01 13:05:26 -0700563 }
564
Saurav Das8a0732e2015-11-20 15:27:53 -0800565 // setup metadata to pass to nextObjective - indicate the vlan on egress
566 // if needed by the switch pipeline. Since neighbor sets are always to
567 // other neighboring routers, there is no subnet assigned on those ports.
568 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Charles Chan59cc16d2017-02-02 16:20:42 -0800569 metabuilder.matchVlanId(SegmentRoutingManager.INTERNAL_VLAN);
Saurav Das7bcbe702017-06-13 15:35:54 -0700570 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700571 if (grpHandler == null) {
572 log.warn("populateIPRuleForRouter: groupHandler for device {} "
Saurav Das7bcbe702017-06-13 15:35:54 -0700573 + "not found", targetSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700574 return false;
575 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800576
Saurav Das7bcbe702017-06-13 15:35:54 -0700577 int nextId = grpHandler.getNextObjectiveId(ds, nextHops,
Saurav Dasa4020382018-02-14 14:14:54 -0800578 metabuilder.build(), false);
Saurav Das8a0732e2015-11-20 15:27:53 -0800579 if (nextId <= 0) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700580 log.warn("No next objective in {} for ds: {}", targetSw, ds);
sangho834e4b02015-05-01 09:38:25 -0700581 return false;
582 }
583
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700584 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
585 .builder()
586 .fromApp(srManager.appId)
587 .makePermanent()
Saurav Das8a0732e2015-11-20 15:27:53 -0800588 .nextStep(nextId)
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700589 .withSelector(selector)
Charles Chan5270ed02016-01-30 23:22:37 -0800590 .withPriority(getPriorityFromPrefix(ipPrefix))
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700591 .withFlag(ForwardingObjective.Flag.SPECIFIC);
Charles Chan68aa62d2015-11-09 16:37:23 -0800592 if (treatment != null) {
593 fwdBuilder.withTreatment(treatment);
594 }
Saurav Dasc88d4662017-05-15 15:34:25 -0700595 log.debug("Installing IPv4 forwarding objective for router IP/subnet {} "
Saurav Das7bcbe702017-06-13 15:35:54 -0700596 + "in switch {} with nextId: {}", ipPrefix, targetSw, nextId);
Charles Chand2990362016-04-18 13:44:03 -0700597 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das25190812016-05-27 13:54:07 -0700598 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
Saurav Das7bcbe702017-06-13 15:35:54 -0700599 ipPrefix, targetSw),
Charles Chand2990362016-04-18 13:44:03 -0700600 (objective, error) ->
Saurav Das25190812016-05-27 13:54:07 -0700601 log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
Saurav Das7bcbe702017-06-13 15:35:54 -0700602 ipPrefix, error, targetSw));
603 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
sangho20eff1d2015-04-13 15:15:58 -0700604 rulePopulationCounter.incrementAndGet();
sanghob35a6192015-04-01 13:05:26 -0700605
606 return true;
607 }
608
sanghob35a6192015-04-01 13:05:26 -0700609 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700610 * Revokes IP flow rules for the router IP address from given device.
Charles Chan93e71ba2016-04-29 14:38:22 -0700611 *
Charles Chan2ff1bac2018-03-29 16:03:41 -0700612 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chan93e71ba2016-04-29 14:38:22 -0700613 * @param ipPrefix the IP address of the destination router
614 * @return true if all rules are removed successfully, false otherwise
615 */
Charles Chan2ff1bac2018-03-29 16:03:41 -0700616 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre968da122016-12-09 17:26:04 -0800617 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chan93e71ba2016-04-29 14:38:22 -0700618 TrafficSelector selector = sbuilder.build();
619 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
620
621 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
622 .builder()
623 .fromApp(srManager.appId)
624 .makePermanent()
625 .withSelector(selector)
626 .withTreatment(dummyTreatment)
627 .withPriority(getPriorityFromPrefix(ipPrefix))
628 .withFlag(ForwardingObjective.Flag.SPECIFIC);
629
Charles Chan2ff1bac2018-03-29 16:03:41 -0700630 ObjectiveContext context = new DefaultObjectiveContext(
631 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
632 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
633 ipPrefix, targetSw, error));
634 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chan93e71ba2016-04-29 14:38:22 -0700635
636 return true;
637 }
638
639 /**
Saurav Dasa4020382018-02-14 14:14:54 -0800640 * Populates MPLS flow rules in the target device to point towards the
641 * destination device.
642 *
643 * @param targetSwId target device ID of the switch to set the rules
644 * @param destSwId destination switch device ID
645 * @param nextHops next hops switch ID list
646 * @param routerIp the router ip of the destination switch
647 * @return true if all rules are set successfully, false otherwise
648 */
649 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
650 Set<DeviceId> nextHops, IpAddress routerIp) {
651 int segmentId;
652 try {
653 if (routerIp.isIp4()) {
654 segmentId = config.getIPv4SegmentId(destSwId);
655 } else {
656 segmentId = config.getIPv6SegmentId(destSwId);
657 }
658 } catch (DeviceConfigNotFoundException e) {
659 log.warn(e.getMessage() + " Aborting populateMplsRule.");
660 return false;
661 }
662
663 List<ForwardingObjective> fwdObjs = new ArrayList<>();
664 Collection<ForwardingObjective> fwdObjsMpls;
665 // Generates the transit rules used by the standard "routing".
666 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
667 routerIp, true);
668 if (fwdObjsMpls.isEmpty()) {
669 return false;
670 }
671 fwdObjs.addAll(fwdObjsMpls);
672
673 // Generates the transit rules used by the MPLS Pwaas.
674 int pwSrLabel;
675 try {
676 pwSrLabel = config.getPWRoutingLabel(destSwId);
677 } catch (DeviceConfigNotFoundException e) {
678 log.warn(e.getMessage()
679 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
680 return false;
681 }
682 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
683 routerIp, false);
684 if (fwdObjsMpls.isEmpty()) {
685 return false;
686 }
687 fwdObjs.addAll(fwdObjsMpls);
688
689 for (ForwardingObjective fwdObj : fwdObjs) {
690 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
691 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
692 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
693 rulePopulationCounter.incrementAndGet();
694 }
695
696 return true;
697 }
698
699 /**
700 * Differentiates between popping and swapping labels when building an MPLS
701 * forwarding objective.
Pier Ventre917127a2016-10-31 16:49:19 -0700702 *
703 * @param targetSwId the target sw
704 * @param destSwId the destination sw
705 * @param nextHops the set of next hops
Saurav Dasa4020382018-02-14 14:14:54 -0800706 * @param segmentId the segmentId to match representing the destination
707 * switch
708 * @param routerIp the router ip representing the destination switch
Pier Ventre917127a2016-10-31 16:49:19 -0700709 * @return a collection of fwdobjective
710 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700711 private Collection<ForwardingObjective> handleMpls(
712 DeviceId targetSwId,
713 DeviceId destSwId,
714 Set<DeviceId> nextHops,
715 int segmentId,
716 IpAddress routerIp,
717 boolean isMplsBos) {
Pier Ventre917127a2016-10-31 16:49:19 -0700718
719 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
720 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi3bfe32c2017-01-30 09:47:36 -0800721 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre917127a2016-10-31 16:49:19 -0700722 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
723 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
724 sbuilder.matchMplsBos(isMplsBos);
725 TrafficSelector selector = sbuilder.build();
726
727 // setup metadata to pass to nextObjective - indicate the vlan on egress
728 // if needed by the switch pipeline. Since mpls next-hops are always to
729 // other neighboring routers, there is no subnet assigned on those ports.
730 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Charles Chan59cc16d2017-02-02 16:20:42 -0800731 metabuilder.matchVlanId(SegmentRoutingManager.INTERNAL_VLAN);
Pier Ventre917127a2016-10-31 16:49:19 -0700732
733 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
734 // If the next hop is the destination router for the segment, do pop
735 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das7bcbe702017-06-13 15:35:54 -0700736 + "label {} in switch {} with pop to next-hops {}",
737 segmentId, targetSwId, nextHops);
Saurav Das961beb22017-03-29 19:09:17 -0700738 ForwardingObjective.Builder fwdObjNoBosBuilder =
739 getMplsForwardingObjective(targetSwId,
740 nextHops,
741 true,
742 isMplsBos,
743 metabuilder.build(),
Saurav Dasc88d4662017-05-15 15:34:25 -0700744 routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800745 segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700746 destSwId);
Pier Ventre917127a2016-10-31 16:49:19 -0700747 // Error case, we cannot handle, exit.
748 if (fwdObjNoBosBuilder == null) {
749 return Collections.emptyList();
750 }
751 fwdObjBuilders.add(fwdObjNoBosBuilder);
752
753 } else {
Saurav Dasa4020382018-02-14 14:14:54 -0800754 // next hop is not destination, irrespective of the number of next
755 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das7bcbe702017-06-13 15:35:54 -0700756 log.debug("Installing MPLS forwarding objective for "
757 + "label {} in switch {} without pop to next-hops {}",
758 segmentId, targetSwId, nextHops);
Saurav Das961beb22017-03-29 19:09:17 -0700759 ForwardingObjective.Builder fwdObjNoBosBuilder =
760 getMplsForwardingObjective(targetSwId,
761 nextHops,
762 false,
763 isMplsBos,
764 metabuilder.build(),
Saurav Dasc88d4662017-05-15 15:34:25 -0700765 routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800766 segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700767 destSwId);
Pier Ventre917127a2016-10-31 16:49:19 -0700768 // Error case, we cannot handle, exit.
769 if (fwdObjNoBosBuilder == null) {
770 return Collections.emptyList();
771 }
772 fwdObjBuilders.add(fwdObjNoBosBuilder);
773
774 }
775
776 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
777 // We add the final property to the fwdObjs.
778 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre917127a2016-10-31 16:49:19 -0700779 ((Builder) ((Builder) fwdObjBuilder
780 .fromApp(srManager.appId)
781 .makePermanent())
782 .withSelector(selector)
783 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
784 .withFlag(ForwardingObjective.Flag.SPECIFIC);
785
786 ObjectiveContext context = new DefaultObjectiveContext(
787 (objective) ->
788 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
789 objective.id(), segmentId, targetSwId),
790 (objective, error) ->
791 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
792 objective.id(), segmentId, error, targetSwId));
793
794 ForwardingObjective fob = fwdObjBuilder.add(context);
795 fwdObjs.add(fob);
Pier Ventre917127a2016-10-31 16:49:19 -0700796 }
797
798 return fwdObjs;
799 }
800
801 /**
Saurav Dasa4020382018-02-14 14:14:54 -0800802 * Returns a Forwarding Objective builder for the MPLS rule that references
803 * the desired Next Objective. Creates a DestinationSet that allows the
804 * groupHandler to create or find the required next objective.
sanghob35a6192015-04-01 13:05:26 -0700805 *
Saurav Dasa4020382018-02-14 14:14:54 -0800806 * @param targetSw the target sw
807 * @param nextHops the set of next hops
808 * @param phpRequired true if penultimate-hop-popping is required
809 * @param isBos true if matched label is bottom-of-stack
810 * @param meta metadata for creating next objective
811 * @param routerIp the router ip representing the destination switch
812 * @param destSw the destination sw
813 * @return the mpls forwarding objective builder
sanghob35a6192015-04-01 13:05:26 -0700814 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800815 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das7bcbe702017-06-13 15:35:54 -0700816 DeviceId targetSw,
Saurav Das8a0732e2015-11-20 15:27:53 -0800817 Set<DeviceId> nextHops,
818 boolean phpRequired,
819 boolean isBos,
Pier Ventree0ae7a32016-11-23 09:57:42 -0800820 TrafficSelector meta,
Saurav Dasc88d4662017-05-15 15:34:25 -0700821 IpAddress routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800822 int segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700823 DeviceId destSw) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800824
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700825 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
826 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sanghob35a6192015-04-01 13:05:26 -0700827
828 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Dasa4020382018-02-14 14:14:54 -0800829 DestinationSet ds = null;
830 boolean simple = false;
sanghob35a6192015-04-01 13:05:26 -0700831 if (phpRequired) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800832 // php case - pop should always be flow-action
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700833 log.debug("getMplsForwardingObjective: php required");
sangho1e575652015-05-14 00:39:53 -0700834 tbuilder.deferred().copyTtlIn();
sanghob35a6192015-04-01 13:05:26 -0700835 if (isBos) {
Pier Ventree0ae7a32016-11-23 09:57:42 -0800836 if (routerIp.isIp4()) {
837 tbuilder.deferred().popMpls(EthType.EtherType.IPV4.ethType());
838 } else {
839 tbuilder.deferred().popMpls(EthType.EtherType.IPV6.ethType());
840 }
841 tbuilder.decNwTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800842 // standard case -> BoS == True; pop results in IP packet and forwarding
843 // is via an ECMP group
844 ds = new DestinationSet(false, false, destSw);
sanghob35a6192015-04-01 13:05:26 -0700845 } else {
Saurav Das8a0732e2015-11-20 15:27:53 -0800846 tbuilder.deferred().popMpls(EthType.EtherType.MPLS_UNICAST.ethType())
847 .decMplsTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800848 // double-label case -> BoS == False, pop results in MPLS packet
849 // depending on configuration we can ECMP this packet or choose one output
850 if (srManager.getMplsEcmp()) {
851 ds = new DestinationSet(true, false, destSw);
852 } else {
853 ds = new DestinationSet(true, false, destSw);
854 simple = true;
855 }
sanghob35a6192015-04-01 13:05:26 -0700856 }
857 } else {
Saurav Das8a0732e2015-11-20 15:27:53 -0800858 // swap with self case - SR CONTINUE
Saurav Dasa4020382018-02-14 14:14:54 -0800859 log.debug("getMplsForwardingObjective: swap with self");
sangho1e575652015-05-14 00:39:53 -0700860 tbuilder.deferred().decMplsTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800861 // swap results in MPLS packet with same BoS bit regardless of bit value
862 // depending on configuration we can ECMP this packet or choose one output
Saurav Dase0d4c872018-03-05 14:37:16 -0800863 // XXX reconsider types
Saurav Dasa4020382018-02-14 14:14:54 -0800864 if (srManager.getMplsEcmp()) {
865 ds = new DestinationSet(false, true, segmentId, destSw);
866 } else {
867 ds = new DestinationSet(false, true, segmentId, destSw);
868 simple = true;
869 }
sanghob35a6192015-04-01 13:05:26 -0700870 }
871
Saurav Das8a0732e2015-11-20 15:27:53 -0800872 fwdBuilder.withTreatment(tbuilder.build());
Saurav Dasa4020382018-02-14 14:14:54 -0800873 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
874 targetSw, ds);
Saurav Das7bcbe702017-06-13 15:35:54 -0700875 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
876 if (gh == null) {
877 log.warn("getNextObjectiveId query - groupHandler for device {} "
878 + "not found", targetSw);
879 return null;
880 }
Saurav Dasa4020382018-02-14 14:14:54 -0800881
Saurav Das7bcbe702017-06-13 15:35:54 -0700882 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
883 dstNextHops.put(destSw, nextHops);
Saurav Dasa4020382018-02-14 14:14:54 -0800884 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das8a0732e2015-11-20 15:27:53 -0800885 if (nextId <= 0) {
Saurav Dasa4020382018-02-14 14:14:54 -0800886 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das8a0732e2015-11-20 15:27:53 -0800887 return null;
Saurav Das25190812016-05-27 13:54:07 -0700888 } else {
Saurav Dasa4020382018-02-14 14:14:54 -0800889 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
890 nextId, targetSw, ds);
sanghob35a6192015-04-01 13:05:26 -0700891 }
892
Saurav Das8a0732e2015-11-20 15:27:53 -0800893 fwdBuilder.nextStep(nextId);
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700894 return fwdBuilder;
sanghob35a6192015-04-01 13:05:26 -0700895 }
896
897 /**
Saurav Das822c4e22015-10-23 10:51:11 -0700898 * Creates a filtering objective to permit all untagged packets with a
Saurav Das0e99e2b2015-10-28 12:39:42 -0700899 * dstMac corresponding to the router's MAC address. For those pipelines
900 * that need to internally assign vlans to untagged packets, this method
901 * provides per-subnet vlan-ids as metadata.
Saurav Das837e0bb2015-10-30 17:45:38 -0700902 * <p>
Saurav Das018605f2017-02-18 14:05:44 -0800903 * Note that the vlan assignment and filter programming should only be done by
904 * the master for a switch. This method is typically called at deviceAdd and
905 * programs filters only for the enabled ports of the device. For port-updates,
906 * that enable/disable ports after device add, singlePortFilter methods should
907 * be called.
sanghob35a6192015-04-01 13:05:26 -0700908 *
Saurav Das822c4e22015-10-23 10:51:11 -0700909 * @param deviceId the switch dpid for the router
Saurav Dasd2fded02016-12-02 15:43:47 -0800910 * @return PortFilterInfo information about the processed ports
sanghob35a6192015-04-01 13:05:26 -0700911 */
Charles Chan65238242017-06-22 18:03:14 -0700912 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das0e99e2b2015-10-28 12:39:42 -0700913 log.debug("Installing per-port filtering objective for untagged "
914 + "packets in device {}", deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -0800915
Saurav Das59232cf2016-04-27 18:35:50 -0700916 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hallcbd1b392017-01-18 20:15:44 -0800917 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das59232cf2016-04-27 18:35:50 -0700918 log.warn("Device {} ports not available. Unable to add MacVlan filters",
919 deviceId);
Saurav Dasd2fded02016-12-02 15:43:47 -0800920 return null;
Saurav Das59232cf2016-04-27 18:35:50 -0700921 }
Saurav Das018605f2017-02-18 14:05:44 -0800922 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das59232cf2016-04-27 18:35:50 -0700923 for (Port port : devPorts) {
Saurav Das25190812016-05-27 13:54:07 -0700924 if (!port.isEnabled()) {
925 disabledPorts++;
926 continue;
927 }
Charles Chan7e4f8192017-02-26 22:59:35 -0800928 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Das018605f2017-02-18 14:05:44 -0800929 filteredPorts++;
930 } else {
931 errorPorts++;
Saurav Das25190812016-05-27 13:54:07 -0700932 }
Saurav Das0e99e2b2015-10-28 12:39:42 -0700933 }
Charles Chan7f9737b2017-06-22 14:27:17 -0700934 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Das018605f2017-02-18 14:05:44 -0800935 deviceId, disabledPorts, errorPorts, filteredPorts);
Saurav Dasd2fded02016-12-02 15:43:47 -0800936 return srManager.defaultRoutingHandler.new PortFilterInfo(disabledPorts,
Saurav Das018605f2017-02-18 14:05:44 -0800937 errorPorts, filteredPorts);
938 }
939
940 /**
Charles Chan7e4f8192017-02-26 22:59:35 -0800941 * Creates or removes filtering objectives for a single port. Should only be
942 * called by the master for a switch.
Saurav Das018605f2017-02-18 14:05:44 -0800943 *
944 * @param deviceId device identifier
945 * @param portnum port identifier for port to be filtered
Charles Chan7e4f8192017-02-26 22:59:35 -0800946 * @param install true to install the filtering objective, false to remove
Saurav Das018605f2017-02-18 14:05:44 -0800947 * @return true if no errors occurred during the build of the filtering objective
948 */
Charles Chan65238242017-06-22 18:03:14 -0700949 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800950 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan971d7ba2018-05-01 11:50:20 -0700951 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
952 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
953 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan7ffd81f2017-02-08 15:52:08 -0800954
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700955 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800956 if (taggedVlans.size() != 0) {
957 // Filter for tagged vlans
Charles Chan971d7ba2018-05-01 11:50:20 -0700958 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan7e4f8192017-02-26 22:59:35 -0800959 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800960 return false;
961 }
962 if (nativeVlan != null) {
963 // Filter for native vlan
Charles Chan7e4f8192017-02-26 22:59:35 -0800964 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800965 return false;
966 }
967 }
968 } else if (untaggedVlan != null) {
969 // Filter for untagged vlan
Charles Chan7e4f8192017-02-26 22:59:35 -0800970 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800971 return false;
972 }
Jonghwan Hyun5efd7682018-04-30 09:27:21 -0700973 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700974 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Charles Chan7e4f8192017-02-26 22:59:35 -0800975 if (!processSinglePortFiltersInternal(deviceId, portnum, true, INTERNAL_VLAN, install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800976 return false;
977 }
978 }
979 return true;
980 }
981
Jonghwan Hyun42fe1052017-08-25 17:48:36 -0700982 /**
983 * Updates filtering objectives for a single port. Should only be called by
984 * the master for a switch
985 * @param deviceId device identifier
986 * @param portNum port identifier for port to be filtered
987 * @param pushVlan true to push vlan, false otherwise
988 * @param vlanId vlan identifier
989 * @param install true to install the filtering objective, false to remove
990 */
991 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
992 boolean pushVlan, VlanId vlanId, boolean install) {
993 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
994 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
995 deviceId, portNum, vlanId);
996 }
997 }
998
Charles Chan7e4f8192017-02-26 22:59:35 -0800999 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1000 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburgc1d47e92018-04-30 19:27:19 -04001001 boolean doTMAC = true;
1002
1003 if (!pushVlan) {
1004 // Skip the tagged vlans belonging to an interface without an IP address
1005 Set<Interface> ifaces = srManager.interfaceService
1006 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1007 .stream()
1008 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1009 .collect(Collectors.toSet());
1010 if (!ifaces.isEmpty()) {
1011 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1012 vlanId, deviceId, portnum);
1013 doTMAC = false;
1014 }
1015 }
1016
1017 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Das018605f2017-02-18 14:05:44 -08001018 if (fob == null) {
1019 // error encountered during build
1020 return false;
1021 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001022 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001023 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Das018605f2017-02-18 14:05:44 -08001024 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan7e4f8192017-02-26 22:59:35 -08001025 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Dasc88d4662017-05-15 15:34:25 -07001026 install ? "installed" : "removed"),
Charles Chan7e4f8192017-02-26 22:59:35 -08001027 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001028 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan7e4f8192017-02-26 22:59:35 -08001029 if (install) {
1030 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1031 } else {
1032 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan7ffd81f2017-02-08 15:52:08 -08001033 }
Charles Chan7ffd81f2017-02-08 15:52:08 -08001034 return true;
Saurav Das018605f2017-02-18 14:05:44 -08001035 }
1036
Charles Chan7ffd81f2017-02-08 15:52:08 -08001037 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburgc1d47e92018-04-30 19:27:19 -04001038 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Das018605f2017-02-18 14:05:44 -08001039 MacAddress deviceMac;
1040 try {
1041 deviceMac = config.getDeviceMac(deviceId);
1042 } catch (DeviceConfigNotFoundException e) {
1043 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1044 return null;
1045 }
Saurav Das018605f2017-02-18 14:05:44 -08001046 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburgc1d47e92018-04-30 19:27:19 -04001047
1048 if (doTMAC) {
1049 fob.withKey(Criteria.matchInPort(portnum))
1050 .addCondition(Criteria.matchEthDst(deviceMac))
1051 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1052 } else {
1053 fob.withKey(Criteria.matchInPort(portnum))
1054 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1055 }
Charles Chan7ffd81f2017-02-08 15:52:08 -08001056
Charles Chanc550f2e2017-12-19 19:55:57 -08001057 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1058
Charles Chan7ffd81f2017-02-08 15:52:08 -08001059 if (pushVlan) {
1060 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chanc550f2e2017-12-19 19:55:57 -08001061 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan7ffd81f2017-02-08 15:52:08 -08001062 } else {
1063 fob.addCondition(Criteria.matchVlanId(vlanId));
1064 }
1065
Charles Chanc550f2e2017-12-19 19:55:57 -08001066 // NOTE: Some switch hardware share the same filtering flow among different ports.
1067 // We use this metadata to let the driver know that there is no more enabled port
1068 // within the same VLAN on this device.
Charles Chandd33be52018-02-26 21:33:25 -08001069 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chanc550f2e2017-12-19 19:55:57 -08001070 tBuilder.wipeDeferred();
1071 }
1072
1073 fob.withMeta(tBuilder.build());
1074
Saurav Das018605f2017-02-18 14:05:44 -08001075 fob.permit().fromApp(srManager.appId);
1076 return fob;
sanghob35a6192015-04-01 13:05:26 -07001077 }
1078
1079 /**
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001080 * Creates or removes filtering objectives for a double-tagged host on a port.
1081 *
1082 * @param deviceId device identifier
1083 * @param portNum port identifier for port to be filtered
1084 * @param outerVlan outer VLAN ID
1085 * @param innerVlan inner VLAN ID
1086 * @param install true to install the filtering objective, false to remove
1087 */
1088 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1089 VlanId innerVlan, boolean install) {
1090 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum, outerVlan, innerVlan);
1091 if (fob == null) {
1092 // error encountered during build
1093 return;
1094 }
1095 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1096 install ? "Installing" : "Removing", deviceId, portNum);
1097 ObjectiveContext context = new DefaultObjectiveContext(
1098 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1099 install ? "installed" : "removed"),
1100 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1101 install ? "install" : "remove", deviceId, portNum, error));
1102 if (install) {
1103 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1104 } else {
1105 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1106 }
1107 }
1108
1109 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
1110 VlanId outerVlan, VlanId innerVlan) {
1111 MacAddress deviceMac;
1112 try {
1113 deviceMac = config.getDeviceMac(deviceId);
1114 } catch (DeviceConfigNotFoundException e) {
1115 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1116 return null;
1117 }
1118 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1119 // Outer vlan id match should be appeared before inner vlan id match.
1120 fob.withKey(Criteria.matchInPort(portNum))
1121 .addCondition(Criteria.matchEthDst(deviceMac))
1122 .addCondition(Criteria.matchVlanId(outerVlan))
1123 .addCondition(Criteria.matchVlanId(innerVlan))
1124 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1125
1126 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1127 // Pop outer vlan
1128 tBuilder.popVlan();
1129
1130 // NOTE: Some switch hardware share the same filtering flow among different ports.
1131 // We use this metadata to let the driver know that there is no more enabled port
1132 // within the same VLAN on this device.
1133 if (noMoreEnabledPort(deviceId, outerVlan)) {
1134 tBuilder.wipeDeferred();
1135 }
1136
1137 fob.withMeta(tBuilder.build());
1138
1139 fob.permit().fromApp(srManager.appId);
1140 return fob;
1141 }
1142
1143 /**
Saurav Das822c4e22015-10-23 10:51:11 -07001144 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Das837e0bb2015-10-30 17:45:38 -07001145 * router's port IP addresses, to the controller. Note that the input
Saurav Das822c4e22015-10-23 10:51:11 -07001146 * port should not be matched on, as these packets can come from any input.
Saurav Das837e0bb2015-10-30 17:45:38 -07001147 * Furthermore, these are applied only by the master instance.
sanghob35a6192015-04-01 13:05:26 -07001148 *
Saurav Das822c4e22015-10-23 10:51:11 -07001149 * @param deviceId the switch dpid for the router
sanghob35a6192015-04-01 13:05:26 -07001150 */
Charles Chan65238242017-06-22 18:03:14 -07001151 void populateIpPunts(DeviceId deviceId) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001152 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chan78ec5052017-12-05 21:07:38 -08001153 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan0b4e6182015-11-03 10:42:14 -08001154 try {
Pier Ventree0ae7a32016-11-23 09:57:42 -08001155 routerIpv4 = config.getRouterIpv4(deviceId);
1156 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chan78ec5052017-12-05 21:07:38 -08001157 routerLinkLocalIpv6 = Ip6Address.valueOf(
1158 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1159
Saurav Das7bcbe702017-06-13 15:35:54 -07001160 if (config.isPairedEdge(deviceId)) {
1161 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1162 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1163 }
Charles Chan0b4e6182015-11-03 10:42:14 -08001164 } catch (DeviceConfigNotFoundException e) {
Charles Chanf6ec1532017-02-08 16:10:40 -08001165 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan0b4e6182015-11-03 10:42:14 -08001166 return;
1167 }
1168
Saurav Das837e0bb2015-10-30 17:45:38 -07001169 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1170 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1171 deviceId);
1172 return;
1173 }
Pier Ventree0ae7a32016-11-23 09:57:42 -08001174 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1175 allIps.add(routerIpv4);
Charles Chan78ec5052017-12-05 21:07:38 -08001176 allIps.add(routerLinkLocalIpv6);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001177 if (routerIpv6 != null) {
1178 allIps.add(routerIpv6);
1179 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001180 if (pairRouterIpv4 != null) {
1181 allIps.add(pairRouterIpv4);
1182 }
1183 if (pairRouterIpv6 != null) {
1184 allIps.add(pairRouterIpv6);
1185 }
Pier Ventree0ae7a32016-11-23 09:57:42 -08001186 for (IpAddress ipaddr : allIps) {
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001187 populateSingleIpPunts(deviceId, ipaddr);
1188 }
1189 }
Charles Chan2df0e8a2017-01-09 11:45:08 -08001190
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001191 /**
1192 * Creates a forwarding objective to punt all IP packets, destined to the
1193 * specified IP address, which should be router's port IP address.
1194 *
1195 * @param deviceId the switch dpid for the router
1196 * @param ipAddress the IP address of the router's port
1197 */
1198 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1199 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1200 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1201
1202 srManager.packetService.requestPackets(sbuilder.build(),
1203 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1204 }
1205
1206 /**
1207 * Removes a forwarding objective to punt all IP packets, destined to the
1208 * specified IP address, which should be router's port IP address.
1209 *
1210 * @param deviceId the switch dpid for the router
1211 * @param ipAddress the IP address of the router's port
1212 */
1213 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1214 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1215 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1216
1217 try {
1218 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1219 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1220 srManager.packetService.cancelPackets(sbuilder.build(),
1221 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1222 }
1223 } catch (DeviceConfigNotFoundException e) {
1224 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das822c4e22015-10-23 10:51:11 -07001225 }
sanghob35a6192015-04-01 13:05:26 -07001226 }
1227
Charles Chan68aa62d2015-11-09 16:37:23 -08001228 /**
Pier Ventree0ae7a32016-11-23 09:57:42 -08001229 * Method to build IPv4 or IPv6 selector.
1230 *
1231 * @param addressToMatch the address to match
1232 */
1233 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1234 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1235 }
1236
1237 /**
1238 * Method to build IPv4 or IPv6 selector.
1239 *
1240 * @param prefixToMatch the prefix to match
1241 */
1242 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1243 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre917127a2016-10-31 16:49:19 -07001244 // If the prefix is IPv4
Pier Ventree0ae7a32016-11-23 09:57:42 -08001245 if (prefixToMatch.isIp4()) {
1246 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1247 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1248 return selectorBuilder;
1249 }
Pier Ventre917127a2016-10-31 16:49:19 -07001250 // If the prefix is IPv6
Pier Ventree0ae7a32016-11-23 09:57:42 -08001251 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1252 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1253 return selectorBuilder;
1254 }
1255
1256 /**
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001257 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1258 * Furthermore, these are applied only by the master instance. Deferred actions
1259 * are not cleared such that packets can be flooded in the cross connect use case
1260 *
1261 * @param deviceId the switch dpid for the router
1262 */
Charles Chan65238242017-06-22 18:03:14 -07001263 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre917127a2016-10-31 16:49:19 -07001264 // We are not the master just skip.
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001265 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1266 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1267 deviceId);
1268 return;
1269 }
1270
Charles Chan65238242017-06-22 18:03:14 -07001271 ForwardingObjective fwdObj;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001272 // We punt all ARP packets towards the controller.
Charles Chan78ec5052017-12-05 21:07:38 -08001273 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001274 .add(new ObjectiveContext() {
1275 @Override
1276 public void onError(Objective objective, ObjectiveError error) {
Charles Chan65238242017-06-22 18:03:14 -07001277 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001278 deviceId, error);
1279 }
1280 });
Charles Chan65238242017-06-22 18:03:14 -07001281 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001282
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001283 // We punt all NDP packets towards the controller.
Charles Chan09bf2692018-01-11 11:48:18 -08001284 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1285 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1286 @Override
1287 public void onError(Objective objective, ObjectiveError error) {
1288 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1289 deviceId, error);
1290 }
1291 });
1292 srManager.flowObjectiveService.forward(deviceId, obj);
1293 });
Charles Chan65238242017-06-22 18:03:14 -07001294
Saurav Das9a554292018-04-27 18:42:30 -07001295 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan65238242017-06-22 18:03:14 -07001296 ForwardingObjective pairFwdObj;
1297 // Do not punt ARP packets from pair port
1298 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1299 .add(new ObjectiveContext() {
1300 @Override
1301 public void onError(Objective objective, ObjectiveError error) {
1302 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1303 deviceId, error);
1304 }
1305 });
1306 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1307
1308 // Do not punt NDP packets from pair port
Charles Chan09bf2692018-01-11 11:48:18 -08001309 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1310 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1311 @Override
1312 public void onError(Objective objective, ObjectiveError error) {
1313 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1314 deviceId, error);
1315 }
1316 });
1317 srManager.flowObjectiveService.forward(deviceId, obj);
1318 });
Charles Chan65238242017-06-22 18:03:14 -07001319
1320 // Do not forward DAD packets from pair port
1321 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1322 .add(new ObjectiveContext() {
1323 @Override
1324 public void onError(Objective objective, ObjectiveError error) {
1325 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1326 deviceId, error);
1327 }
1328 });
1329 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1330 });
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001331 }
1332
Charles Chan65238242017-06-22 18:03:14 -07001333 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1334 TrafficTreatment treatment, int priority) {
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001335 return DefaultForwardingObjective.builder()
Charles Chan65238242017-06-22 18:03:14 -07001336 .withPriority(priority)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001337 .withSelector(selector)
1338 .fromApp(srManager.appId)
1339 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan65238242017-06-22 18:03:14 -07001340 .withTreatment(treatment)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001341 .makePermanent();
1342 }
1343
Charles Chan65238242017-06-22 18:03:14 -07001344 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001345 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1346 sBuilder.matchEthType(TYPE_ARP);
Charles Chan65238242017-06-22 18:03:14 -07001347 if (port != null) {
1348 sBuilder.matchInPort(port);
1349 }
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001350
Charles Chan65238242017-06-22 18:03:14 -07001351 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1352 if (punt) {
1353 tBuilder.punt();
1354 }
1355 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001356 }
1357
Charles Chan09bf2692018-01-11 11:48:18 -08001358 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1359 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001360
Charles Chan09bf2692018-01-11 11:48:18 -08001361 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1362 .forEach(type -> {
1363 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1364 sBuilder.matchEthType(TYPE_IPV6)
1365 .matchIPProtocol(PROTOCOL_ICMP6)
1366 .matchIcmpv6Type(type);
1367 if (port != null) {
1368 sBuilder.matchInPort(port);
1369 }
1370
1371 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1372 if (punt) {
1373 tBuilder.punt();
1374 }
1375
1376 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1377 });
1378
1379 return result;
Charles Chan65238242017-06-22 18:03:14 -07001380 }
1381
1382 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1383 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1384 sBuilder.matchEthType(TYPE_IPV6)
Charles Chanc7e36aa2017-08-07 12:39:03 -07001385 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1386 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1387 // .matchIPProtocol(PROTOCOL_ICMP6)
1388 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan65238242017-06-22 18:03:14 -07001389 if (port != null) {
1390 sBuilder.matchInPort(port);
1391 }
1392
1393 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1394 tBuilder.wipeDeferred();
1395 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001396 }
1397
1398 /**
Charles Chan68aa62d2015-11-09 16:37:23 -08001399 * Populates a forwarding objective to send packets that miss other high
1400 * priority Bridging Table entries to a group that contains all ports of
1401 * its subnet.
1402 *
Andrea Campanellad980c6d2018-04-30 11:48:55 +02001403 * @param address the address to block
1404 * @param deviceId switch ID to set the rules
1405 */
1406 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1407 updateDefaultRouteBlackhole(deviceId, address, true);
1408 }
1409
1410 /**
1411 * Populates a forwarding objective to send packets that miss other high
1412 * priority Bridging Table entries to a group that contains all ports of
1413 * its subnet.
1414 *
1415 * @param address the address to block
1416 * @param deviceId switch ID to set the rules
1417 */
1418 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1419 updateDefaultRouteBlackhole(deviceId, address, false);
1420 }
1421
1422 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1423 try {
1424 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1425
1426 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1427 if (address.isIp4()) {
1428 sbuilder.matchIPDst(address);
1429 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1430 } else {
1431 sbuilder.matchIPv6Dst(address);
1432 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1433 }
1434
1435 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1436
1437 tBuilder.transition(60);
1438 tBuilder.wipeDeferred();
1439
1440 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1441 fob.withFlag(Flag.SPECIFIC)
1442 .withSelector(sbuilder.build())
1443 .withTreatment(tBuilder.build())
1444 .withPriority(getPriorityFromPrefix(address))
1445 .fromApp(srManager.appId)
1446 .makePermanent();
1447
1448 log.debug("{} blackhole forwarding objectives for dev: {}",
1449 install ? "Installing" : "Removing", deviceId);
1450 ObjectiveContext context = new DefaultObjectiveContext(
1451 (objective) -> log.debug("Forward for {} {}", deviceId,
1452 install ? "installed" : "removed"),
1453 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1454 install ? "install" : "remove", deviceId, error));
1455 if (install) {
1456 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1457 } else {
1458 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1459 }
1460 }
1461 } catch (DeviceConfigNotFoundException e) {
1462 log.info("Not populating blackhole for un-configured device {}", deviceId);
1463 }
1464
1465 }
1466
1467 /**
1468 * Populates a forwarding objective to send packets that miss other high
1469 * priority Bridging Table entries to a group that contains all ports of
1470 * its subnet.
1471 *
Charles Chan68aa62d2015-11-09 16:37:23 -08001472 * @param deviceId switch ID to set the rules
1473 */
Charles Chan65238242017-06-22 18:03:14 -07001474 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan7ffd81f2017-02-08 15:52:08 -08001475 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001476 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chan68aa62d2015-11-09 16:37:23 -08001477 });
1478 }
1479
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001480 /**
1481 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1482 * @param deviceId switch ID to set the rule
1483 * @param vlanId vlan ID to specify the subnet
1484 * @param install true to install the rule, false to revoke the rule
1485 */
1486 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1487 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1488
1489 if (nextId < 0) {
1490 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1491 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1492 return;
1493 }
1494
1495 // Driver should treat objective with MacAddress.NONE as the
1496 // subnet broadcast rule
1497 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1498 sbuilder.matchVlanId(vlanId);
1499 sbuilder.matchEthDst(MacAddress.NONE);
1500
1501 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1502 fob.withFlag(Flag.SPECIFIC)
1503 .withSelector(sbuilder.build())
1504 .nextStep(nextId)
1505 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1506 .fromApp(srManager.appId)
1507 .makePermanent();
1508 ObjectiveContext context = new DefaultObjectiveContext(
1509 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1510 (objective, error) ->
1511 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1512
1513 if (install) {
1514 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1515 } else {
1516 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1517 }
1518 }
1519
Charles Chan5270ed02016-01-30 23:22:37 -08001520 private int getPriorityFromPrefix(IpPrefix prefix) {
1521 return (prefix.isIp4()) ?
1522 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1523 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapallif3a8bc02015-05-22 13:47:31 -07001524 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001525
1526 /**
1527 * Update Forwarding objective for each host and IP address connected to given port.
1528 * And create corresponding Simple Next objective if it does not exist.
1529 * Applied only when populating Forwarding objective
1530 * @param deviceId switch ID to set the rule
1531 * @param portNumber port number
1532 * @param prefix IP prefix of the route
1533 * @param hostMac MAC address of the next hop
1534 * @param vlanId Vlan ID of the port
1535 * @param popVlan true to pop vlan tag in TrafficTreatment
1536 * @param install true to populate the forwarding objective, false to revoke
1537 */
1538 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1539 VlanId vlanId, boolean popVlan, boolean install) {
1540 ForwardingObjective.Builder fob;
1541 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1542 MacAddress deviceMac;
1543 try {
1544 deviceMac = config.getDeviceMac(deviceId);
1545 } catch (DeviceConfigNotFoundException e) {
1546 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1547 return;
1548 }
1549
1550 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1551 tbuilder.deferred()
1552 .setEthDst(hostMac)
1553 .setEthSrc(deviceMac)
1554 .setOutput(portNumber);
1555
1556 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1557
1558 if (!popVlan) {
1559 tbuilder.setVlanId(vlanId);
1560 } else {
1561 mbuilder.matchVlanId(vlanId);
1562 }
1563
1564 // if the objective is to revoke an existing rule, and for some reason
1565 // the next-objective does not exist, then a new one should not be created
1566 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1567 tbuilder.build(), mbuilder.build(), install);
1568 if (portNextObjId == -1) {
1569 // Warning log will come from getPortNextObjective method
1570 return;
1571 }
1572
1573 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1574 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1575 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1576
1577 ObjectiveContext context = new DefaultObjectiveContext(
1578 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1579 (objective, error) ->
1580 log.warn("Failed to {} IP rule for route {}: {}",
1581 install ? "install" : "revoke", prefix, error));
1582 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1583
1584 if (!install) {
1585 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1586 if (grpHandler == null) {
1587 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1588 } else {
1589 // Remove L3UG for the given port and host
1590 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1591 }
1592 }
1593 }
Charles Chandd33be52018-02-26 21:33:25 -08001594
1595 /**
1596 * Checks if there is other enabled port within the given VLAN on the given device.
1597 *
1598 * @param deviceId device ID
1599 * @param vlanId VLAN ID
1600 * @return true if there is no more port enabled within the given VLAN on the given device
1601 */
1602 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1603 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1604 .filter(Port::isEnabled)
1605 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1606 .collect(Collectors.toSet());
1607
1608 return enabledPorts.stream().noneMatch(cp ->
1609 // Given vlanId is included in the vlan-tagged configuration
Charles Chan971d7ba2018-05-01 11:50:20 -07001610 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chandd33be52018-02-26 21:33:25 -08001611 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan971d7ba2018-05-01 11:50:20 -07001612 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Charles Chandd33be52018-02-26 21:33:25 -08001613 vlanId.equals(INTERNAL_VLAN)) ||
1614 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1615 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1616 );
1617 }
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001618
1619 /**
1620 * Returns a forwarding objective builder for egress forwarding rules.
1621 * <p>
1622 * The forwarding objective installs flow rules to egress pipeline to push
1623 * two vlan headers with given inner, outer vlan ids and outer tpid.
1624 *
1625 * @param portNumber port where the next hop attaches to
1626 * @param dummyVlanId vlan ID of the packet to match
1627 * @param innerVlan inner vlan ID of the next hop
1628 * @param outerVlan outer vlan ID of the next hop
1629 * @param outerTpid outer TPID of the next hop
1630 * @return forwarding objective builder
1631 */
1632 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1633 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1634 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1635 sbuilder.matchVlanId(dummyVlanId);
1636 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1637 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1638
1639 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1640 tbuilder.pushVlan(outerTpid);
1641 } else {
1642 tbuilder.pushVlan();
1643 }
1644
1645 tbuilder.setVlanId(outerVlan);
1646 return DefaultForwardingObjective.builder()
1647 .withSelector(sbuilder.build())
1648 .withTreatment(tbuilder.build())
1649 .fromApp(srManager.appId)
1650 .makePermanent()
1651 .withPriority(DEFAULT_PRIORITY)
1652 .withFlag(ForwardingObjective.Flag.EGRESS);
1653 }
1654
1655 /**
1656 * Populates IP rules for a route that has double-tagged next hop.
1657 *
1658 * @param deviceId device ID of the device that next hop attaches to
1659 * @param prefix IP prefix of the route
1660 * @param hostMac MAC address of the next hop
1661 * @param dummyVlan Dummy Vlan ID allocated for this route
1662 * @param innerVlan inner Vlan ID of the next hop
1663 * @param outerVlan outer Vlan ID of the next hop
1664 * @param outerTpid outer TPID of the next hop
1665 * @param outPort port where the next hop attaches to
1666 */
1667 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId dummyVlan,
1668 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1669 ForwardingObjective.Builder fwdBuilder;
1670 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1671 prefix, deviceId, outPort);
1672
1673 ForwardingObjective.Builder egressFwdBuilder = egressFwdObjBuilder(
1674 outPort, dummyVlan, innerVlan, outerVlan, outerTpid);
1675 DefaultObjectiveContext egressFwdContext = new DefaultObjectiveContext(
1676 objective -> log.debug("Egress rule for IP {} is populated", prefix.address()),
1677 (objective, error) -> {
1678 log.warn("Failed to populate egress rule for IP {}: {}", prefix.address(), error);
1679 srManager.dummyVlanIdStore().remove(new DummyVlanIdStoreKey(
1680 new ConnectPoint(deviceId, outPort), prefix.address()
1681 ));
1682 });
1683 try {
1684 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, dummyVlan, outPort, false);
1685 } catch (DeviceConfigNotFoundException e) {
1686 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1687 return;
1688 }
1689 if (fwdBuilder == null) {
1690 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1691 deviceId, prefix);
1692 return;
1693 }
1694
1695 // Egress forwarding objective should be installed after the nextObjective for the output port is installed.
1696 // Installation of routingFwdObj will ensure the installation of the nextObjective.
1697 int nextId = fwdBuilder.add().nextId();
1698 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1699 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
1700 srManager.flowObjectiveService.forward(deviceId, egressFwdBuilder.add(egressFwdContext));
1701 }, (objective, error) ->
1702 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1703 );
1704 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1705 rulePopulationCounter.incrementAndGet();
1706 }
1707
1708 /**
1709 * Revokes IP rules for a route that has double-tagged next hop.
1710 *
1711 * @param deviceId device ID of the device that next hop attaches to
1712 * @param prefix IP prefix of the route
1713 * @param hostMac MAC address of the next hop
1714 * @param hostVlan Vlan ID of the next hop
1715 * @param innerVlan inner Vlan ID of the next hop
1716 * @param outerVlan outer Vlan ID of the next hop
1717 * @param outerTpid outer TPID of the next hop
1718 * @param outPort port where the next hop attaches to
1719 */
1720 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
1721 VlanId hostVlan, VlanId innerVlan, VlanId outerVlan,
1722 EthType outerTpid, PortNumber outPort) {
1723 revokeRoute(deviceId, prefix, hostMac, hostVlan, outPort);
1724
1725 DummyVlanIdStoreKey key = new DummyVlanIdStoreKey(
1726 new ConnectPoint(deviceId, outPort), prefix.address());
1727 VlanId dummyVlanId = srManager.dummyVlanIdStore().get(key);
1728 if (dummyVlanId == null) {
1729 log.warn("Failed to retrieve dummy VLAN ID for {}/{} and {}",
1730 deviceId, outPort, prefix.address());
1731 return;
1732 }
1733 ForwardingObjective.Builder fob = egressFwdObjBuilder(
1734 outPort, dummyVlanId, innerVlan, outerVlan, outerTpid);
1735 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1736 log.debug("Egress rule for IP {} revoked", prefix.address());
1737 srManager.dummyVlanIdStore().remove(key);
1738 }, (objective, error) -> {
1739 log.warn("Failed to revoke egress rule for IP {}: {}", prefix.address(), error);
1740 });
1741 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1742 }
1743
Jonghwan Hyun5efd7682018-04-30 09:27:21 -07001744 /**
1745 * Checks whether the specified port has IP configuration or not.
1746 *
1747 * @param cp ConnectPoint to check the existance of IP configuration
1748 * @return true if the port has IP configuration; false otherwise.
1749 */
1750 private boolean hasIPConfiguration(ConnectPoint cp) {
1751 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1752 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1753 }
sanghob35a6192015-04-01 13:05:26 -07001754}