blob: b49b18f650ca25985368521eea4dfc49a9d3dc10 [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 Das09c2c4d2018-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 Hyun5efd7682018-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 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;
Jonghwan Hyun800d9d02018-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;
Saurav Das822c4e22015-10-23 10:51:11 -070093
sanghob35a6192015-04-01 13:05:26 -070094 /**
95 * Creates a RoutingRulePopulator object.
96 *
Thomas Vachuskae10f56b2015-04-15 18:20:08 -070097 * @param srManager segment routing manager reference
sanghob35a6192015-04-01 13:05:26 -070098 */
Charles Chan65238242017-06-22 18:03:14 -070099 RoutingRulePopulator(SegmentRoutingManager srManager) {
sanghob35a6192015-04-01 13:05:26 -0700100 this.srManager = srManager;
sangho666cd6d2015-04-14 16:27:13 -0700101 this.config = checkNotNull(srManager.deviceConfiguration);
sangho20eff1d2015-04-13 15:15:58 -0700102 this.rulePopulationCounter = new AtomicLong(0);
103 }
104
105 /**
106 * Resets the population counter.
107 */
Charles Chan65238242017-06-22 18:03:14 -0700108 void resetCounter() {
sangho20eff1d2015-04-13 15:15:58 -0700109 rulePopulationCounter.set(0);
110 }
111
112 /**
113 * Returns the number of rules populated.
Thomas Vachuska266b4432015-04-30 18:13:25 -0700114 *
115 * @return number of rules
sangho20eff1d2015-04-13 15:15:58 -0700116 */
Charles Chan65238242017-06-22 18:03:14 -0700117 long getCounter() {
sangho20eff1d2015-04-13 15:15:58 -0700118 return rulePopulationCounter.get();
sanghob35a6192015-04-01 13:05:26 -0700119 }
120
121 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700122 * Populate a bridging rule on given deviceId that matches given mac, given vlan and
123 * output to given port.
124 *
125 * @param deviceId device ID
126 * @param port port
127 * @param mac mac address
128 * @param vlanId VLAN ID
129 */
130 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
131 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, false);
132 if (fob == null) {
133 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
134 return;
135 }
136
137 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das2f2c9d02018-04-07 16:51:09 -0700138 (objective) -> log.debug("Brigding rule for {}/{} populated", mac, vlanId),
139 (objective, error) -> log.warn("Failed to populate bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chan2ff1bac2018-03-29 16:03:41 -0700140 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
141 }
142
143 /**
144 * Revoke a bridging rule on given deviceId that matches given mac, given vlan and
145 * output to given port.
146 *
147 * @param deviceId device ID
148 * @param port port
149 * @param mac mac address
150 * @param vlanId VLAN ID
151 */
152 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
153 ForwardingObjective.Builder fob = bridgingFwdObjBuilder(deviceId, mac, vlanId, port, true);
154 if (fob == null) {
155 log.warn("Fail to build fwd obj for host {}/{}. Abort.", mac, vlanId);
156 return;
157 }
158
159 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das2f2c9d02018-04-07 16:51:09 -0700160 (objective) -> log.debug("Brigding rule for {}/{} revoked", mac, vlanId),
161 (objective, error) -> log.warn("Failed to revoke bridging rule for {}/{}: {}", mac, vlanId, error));
Charles Chan2ff1bac2018-03-29 16:03:41 -0700162 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
163 }
164
165 /**
166 * Generates a forwarding objective builder for bridging rules.
167 * <p>
168 * The forwarding objective bridges packets destined to a given MAC to
169 * given port on given device.
170 *
171 * @param deviceId Device that host attaches to
172 * @param mac MAC address of the host
173 * @param hostVlanId VLAN ID of the host
174 * @param outport Port that host attaches to
175 * @param revoke true if forwarding objective is meant to revoke forwarding rule
176 * @return Forwarding objective builder
177 */
178 private ForwardingObjective.Builder bridgingFwdObjBuilder(
179 DeviceId deviceId, MacAddress mac, VlanId hostVlanId, PortNumber outport, boolean revoke) {
180 ConnectPoint connectPoint = new ConnectPoint(deviceId, outport);
Charles Chan971d7ba2018-05-01 11:50:20 -0700181 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
182 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
183 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan2ff1bac2018-03-29 16:03:41 -0700184
185 // Create host selector
186 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
187 sbuilder.matchEthDst(mac);
188
189 // Create host treatment
190 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
191 tbuilder.immediate().setOutput(outport);
192
193 // Create host meta
194 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
195
196 // Adjust the selector, treatment and meta according to VLAN configuration
197 if (taggedVlans.contains(hostVlanId)) {
198 sbuilder.matchVlanId(hostVlanId);
199 mbuilder.matchVlanId(hostVlanId);
200 } else if (hostVlanId.equals(VlanId.NONE)) {
201 if (untaggedVlan != null) {
202 sbuilder.matchVlanId(untaggedVlan);
203 mbuilder.matchVlanId(untaggedVlan);
204 tbuilder.immediate().popVlan();
205 } else if (nativeVlan != null) {
206 sbuilder.matchVlanId(nativeVlan);
207 mbuilder.matchVlanId(nativeVlan);
208 tbuilder.immediate().popVlan();
209 } else {
210 log.warn("Untagged host {}/{} is not allowed on {} without untagged or native" +
211 "vlan config", mac, hostVlanId, connectPoint);
212 return null;
213 }
214 } else {
215 log.warn("Tagged host {}/{} is not allowed on {} without VLAN listed in tagged vlan",
216 mac, hostVlanId, connectPoint);
217 return null;
218 }
219
220 // All forwarding is via Groups. Drivers can re-purpose to flow-actions if needed.
221 // If the objective is to revoke an existing rule, and for some reason
222 // the next-objective does not exist, then a new one should not be created
223 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outport,
224 tbuilder.build(), mbuilder.build(), !revoke);
225 if (portNextObjId == -1) {
226 // Warning log will come from getPortNextObjective method
227 return null;
228 }
229
230 return DefaultForwardingObjective.builder()
231 .withFlag(ForwardingObjective.Flag.SPECIFIC)
232 .withSelector(sbuilder.build())
233 .nextStep(portNextObjId)
234 .withPriority(100)
235 .fromApp(srManager.appId)
236 .makePermanent();
237 }
238
239 /**
240 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
241 * and hostMAC connected to given port, and output to given port only when
242 * vlan information is valid.
243 *
244 * @param deviceId device ID that host attaches to
245 * @param portNum port number that host attaches to
246 * @param hostMac mac address of the host connected to the switch port
247 * @param vlanId Vlan ID configured on the switch port
248 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
249 * @param install true to populate the objective, false to revoke
250 */
251 // TODO Refactor. There are a lot of duplications between this method, populateBridging,
252 // revokeBridging and bridgingFwdObjBuilder.
253 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
254 VlanId vlanId, boolean popVlan, boolean install) {
255 // Create host selector
256 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
257 sbuilder.matchEthDst(hostMac);
258
259 // Create host meta
260 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
261
262 sbuilder.matchVlanId(vlanId);
263 mbuilder.matchVlanId(vlanId);
264
265 // Create host treatment
266 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
267 tbuilder.immediate().setOutput(portNum);
268
269 if (popVlan) {
270 tbuilder.immediate().popVlan();
271 }
272
273 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
274 tbuilder.build(), mbuilder.build(), install);
275 if (portNextObjId != -1) {
276 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
277 .withFlag(ForwardingObjective.Flag.SPECIFIC)
278 .withSelector(sbuilder.build())
279 .nextStep(portNextObjId)
280 .withPriority(100)
281 .fromApp(srManager.appId)
282 .makePermanent();
283
284 ObjectiveContext context = new DefaultObjectiveContext(
285 (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
286 install ? "populated" : "revoked"),
287 (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
288 install ? "populate" : "revoke", hostMac, vlanId, error));
289 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
290 } else {
291 log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
292 }
293 }
294
295 /**
296 * Populates IP rules for a route that has direct connection to the switch.
297 * This method should not be invoked directly without going through DefaultRoutingHandler.
sanghob35a6192015-04-01 13:05:26 -0700298 *
Charles Chan1cdecff2016-10-27 14:19:48 -0700299 * @param deviceId device ID of the device that next hop attaches to
300 * @param prefix IP prefix of the route
301 * @param hostMac MAC address of the next hop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800302 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700303 * @param outPort port where the next hop attaches to
sanghob35a6192015-04-01 13:05:26 -0700304 */
Charles Chan2fde6d42017-08-23 14:46:43 -0700305 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan7ffd81f2017-02-08 15:52:08 -0800306 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700307 log.debug("Populate direct routing entry for route {} at {}:{}",
Charles Chan1cdecff2016-10-27 14:19:48 -0700308 prefix, deviceId, outPort);
Charles Chan68aa62d2015-11-09 16:37:23 -0800309 ForwardingObjective.Builder fwdBuilder;
Charles Chan0b4e6182015-11-03 10:42:14 -0800310 try {
Saurav Das961beb22017-03-29 19:09:17 -0700311 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
312 hostVlanId, outPort, false);
Charles Chan0b4e6182015-11-03 10:42:14 -0800313 } catch (DeviceConfigNotFoundException e) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700314 log.warn(e.getMessage() + " Aborting direct populateRoute");
Charles Chan0b4e6182015-11-03 10:42:14 -0800315 return;
316 }
Saurav Das59232cf2016-04-27 18:35:50 -0700317 if (fwdBuilder == null) {
Saurav Das76ae6812017-03-15 15:15:14 -0700318 log.warn("Aborting host routing table entry due "
Charles Chan1cdecff2016-10-27 14:19:48 -0700319 + "to error for dev:{} route:{}", deviceId, prefix);
Saurav Das59232cf2016-04-27 18:35:50 -0700320 return;
321 }
Charles Chan2fde6d42017-08-23 14:46:43 -0700322
323 int nextId = fwdBuilder.add().nextId();
Charles Chand2990362016-04-18 13:44:03 -0700324 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan2fde6d42017-08-23 14:46:43 -0700325 (objective) -> log.debug("Direct routing rule for route {} populated. nextId={}",
326 prefix, nextId),
Charles Chand2990362016-04-18 13:44:03 -0700327 (objective, error) ->
Saurav Das7bcbe702017-06-13 15:35:54 -0700328 log.warn("Failed to populate direct routing rule for route {}: {}",
Saurav Das76ae6812017-03-15 15:15:14 -0700329 prefix, error));
Charles Chand2990362016-04-18 13:44:03 -0700330 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
Charles Chan68aa62d2015-11-09 16:37:23 -0800331 rulePopulationCounter.incrementAndGet();
332 }
333
Charles Chane849c192016-01-11 18:28:54 -0800334 /**
Charles Chan1cdecff2016-10-27 14:19:48 -0700335 * Removes IP rules for a route when the next hop is gone.
Charles Chan2ff1bac2018-03-29 16:03:41 -0700336 * This method should not be invoked directly without going through DefaultRoutingHandler.
Charles Chane849c192016-01-11 18:28:54 -0800337 *
Charles Chan1cdecff2016-10-27 14:19:48 -0700338 * @param deviceId device ID of the device that next hop attaches to
339 * @param prefix IP prefix of the route
340 * @param hostMac MAC address of the next hop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800341 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700342 * @param outPort port that next hop attaches to
Charles Chane849c192016-01-11 18:28:54 -0800343 */
Charles Chan2fde6d42017-08-23 14:46:43 -0700344 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Charles Chan7ffd81f2017-02-08 15:52:08 -0800345 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Charles Chan1cdecff2016-10-27 14:19:48 -0700346 log.debug("Revoke IP table entry for route {} at {}:{}",
347 prefix, deviceId, outPort);
Charles Chan68aa62d2015-11-09 16:37:23 -0800348 ForwardingObjective.Builder fwdBuilder;
349 try {
Saurav Das961beb22017-03-29 19:09:17 -0700350 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac,
351 hostVlanId, outPort, true);
Charles Chan68aa62d2015-11-09 16:37:23 -0800352 } catch (DeviceConfigNotFoundException e) {
353 log.warn(e.getMessage() + " Aborting revokeIpRuleForHost.");
354 return;
355 }
Charles Chan458b8262016-11-30 11:55:05 -0800356 if (fwdBuilder == null) {
357 log.warn("Aborting host routing table entries due "
358 + "to error for dev:{} route:{}", deviceId, prefix);
359 return;
360 }
Charles Chand2990362016-04-18 13:44:03 -0700361 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan1cdecff2016-10-27 14:19:48 -0700362 (objective) -> log.debug("IP rule for route {} revoked", prefix),
Charles Chand2990362016-04-18 13:44:03 -0700363 (objective, error) ->
Charles Chan1cdecff2016-10-27 14:19:48 -0700364 log.warn("Failed to revoke IP rule for route {}: {}", prefix, error));
Charles Chand2990362016-04-18 13:44:03 -0700365 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.remove(context));
Charles Chan68aa62d2015-11-09 16:37:23 -0800366 }
367
Charles Chan1cdecff2016-10-27 14:19:48 -0700368 /**
Charles Chanf6ec1532017-02-08 16:10:40 -0800369 * Returns a forwarding objective builder for routing rules.
370 * <p>
371 * The forwarding objective routes packets destined to a given prefix to
372 * given port on given device with given destination MAC.
Charles Chan1cdecff2016-10-27 14:19:48 -0700373 *
374 * @param deviceId device ID
375 * @param prefix prefix that need to be routed
376 * @param hostMac MAC address of the nexthop
Charles Chan7ffd81f2017-02-08 15:52:08 -0800377 * @param hostVlanId Vlan ID of the nexthop
Charles Chan1cdecff2016-10-27 14:19:48 -0700378 * @param outPort port where the nexthop attaches to
Saurav Das961beb22017-03-29 19:09:17 -0700379 * @param revoke true if forwarding objective is meant to revoke forwarding rule
Charles Chan1cdecff2016-10-27 14:19:48 -0700380 * @return forwarding objective builder
381 * @throws DeviceConfigNotFoundException if given device is not configured
382 */
Charles Chanf6ec1532017-02-08 16:10:40 -0800383 private ForwardingObjective.Builder routingFwdObjBuilder(
Charles Chan1cdecff2016-10-27 14:19:48 -0700384 DeviceId deviceId, IpPrefix prefix,
Saurav Das961beb22017-03-29 19:09:17 -0700385 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort,
386 boolean revoke)
Charles Chan68aa62d2015-11-09 16:37:23 -0800387 throws DeviceConfigNotFoundException {
388 MacAddress deviceMac;
389 deviceMac = config.getDeviceMac(deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -0800390
Charles Chan7ffd81f2017-02-08 15:52:08 -0800391 ConnectPoint connectPoint = new ConnectPoint(deviceId, outPort);
Charles Chan971d7ba2018-05-01 11:50:20 -0700392 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
393 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
394 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
sanghob35a6192015-04-01 13:05:26 -0700395
Charles Chan7ffd81f2017-02-08 15:52:08 -0800396 // Create route selector
397 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
398
399 // Create route treatment
Charles Chan1cdecff2016-10-27 14:19:48 -0700400 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
sangho1e575652015-05-14 00:39:53 -0700401 tbuilder.deferred()
402 .setEthDst(hostMac)
Charles Chan0b4e6182015-11-03 10:42:14 -0800403 .setEthSrc(deviceMac)
sanghob35a6192015-04-01 13:05:26 -0700404 .setOutput(outPort);
Saurav Das4ce45962015-11-24 23:21:05 -0800405
Charles Chan7ffd81f2017-02-08 15:52:08 -0800406 // Create route meta
407 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
Charles Chan59cc16d2017-02-02 16:20:42 -0800408
Charles Chan7ffd81f2017-02-08 15:52:08 -0800409 // Adjust the meta according to VLAN configuration
410 if (taggedVlans.contains(hostVlanId)) {
411 tbuilder.setVlanId(hostVlanId);
412 } else if (hostVlanId.equals(VlanId.NONE)) {
413 if (untaggedVlan != null) {
414 mbuilder.matchVlanId(untaggedVlan);
415 } else if (nativeVlan != null) {
416 mbuilder.matchVlanId(nativeVlan);
417 } else {
Charles Chan65238242017-06-22 18:03:14 -0700418 log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
419 hostMac, hostVlanId, connectPoint);
420 return null;
Charles Chan7ffd81f2017-02-08 15:52:08 -0800421 }
422 } else {
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700423 // Internally-assigned dummy VLAN id will be given as hostVlanId
424 // when destination is double-tagged.
425 VlanId vlanId = srManager.dummyVlanIdStore().get(
426 new DummyVlanIdStoreKey(connectPoint, prefix.address()));
427 if (vlanId != null && vlanId.equals(hostVlanId)) {
428 tbuilder.setVlanId(hostVlanId);
429 mbuilder.matchVlanId(VlanId.ANY);
430 } else {
431 log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
432 + " in tagged vlan", hostMac, hostVlanId, connectPoint);
433 return null;
434 }
Saurav Das59232cf2016-04-27 18:35:50 -0700435 }
Saurav Das961beb22017-03-29 19:09:17 -0700436 // if the objective is to revoke an existing rule, and for some reason
437 // the next-objective does not exist, then a new one should not be created
Charles Chan7ffd81f2017-02-08 15:52:08 -0800438 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, outPort,
Saurav Das961beb22017-03-29 19:09:17 -0700439 tbuilder.build(), mbuilder.build(), !revoke);
Charles Chan7ffd81f2017-02-08 15:52:08 -0800440 if (portNextObjId == -1) {
441 // Warning log will come from getPortNextObjective method
442 return null;
443 }
444
Charles Chan68aa62d2015-11-09 16:37:23 -0800445 return DefaultForwardingObjective.builder()
Charles Chan7ffd81f2017-02-08 15:52:08 -0800446 .withSelector(sbuilder.build())
Saurav Das4ce45962015-11-24 23:21:05 -0800447 .nextStep(portNextObjId)
Charles Chan68aa62d2015-11-09 16:37:23 -0800448 .fromApp(srManager.appId).makePermanent()
Charles Chan1cdecff2016-10-27 14:19:48 -0700449 .withPriority(getPriorityFromPrefix(prefix))
Charles Chan5270ed02016-01-30 23:22:37 -0800450 .withFlag(ForwardingObjective.Flag.SPECIFIC);
sanghob35a6192015-04-01 13:05:26 -0700451 }
452
453 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700454 * Populates IP flow rules for all the given prefixes reachable from the
455 * destination switch(es).
sanghob35a6192015-04-01 13:05:26 -0700456 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700457 * @param targetSw switch where rules are to be programmed
458 * @param subnets subnets/prefixes being added
459 * @param destSw1 destination switch where the prefixes are reachable
460 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
461 * Should be null if there is no paired destination switch (by config)
462 * or if the given prefixes are reachable only via destSw1
463 * @param nextHops a map containing a set of next-hops for each destination switch.
464 * If destSw2 is not null, then this map must contain an
465 * entry for destSw2 with its next-hops from the targetSw
466 * (although the next-hop set may be empty in certain scenarios).
467 * If destSw2 is null, there should not be an entry in this
468 * map for destSw2.
sanghob35a6192015-04-01 13:05:26 -0700469 * @return true if all rules are set successfully, false otherwise
470 */
Charles Chan65238242017-06-22 18:03:14 -0700471 boolean populateIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets,
Saurav Das7bcbe702017-06-13 15:35:54 -0700472 DeviceId destSw1, DeviceId destSw2, Map<DeviceId, Set<DeviceId>> nextHops) {
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700473 for (IpPrefix subnet : subnets) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700474 if (!populateIpRuleForRouter(targetSw, subnet, destSw1, destSw2, nextHops)) {
sanghob35a6192015-04-01 13:05:26 -0700475 return false;
476 }
477 }
Charles Chan93e71ba2016-04-29 14:38:22 -0700478 return true;
479 }
sanghob35a6192015-04-01 13:05:26 -0700480
Charles Chan93e71ba2016-04-29 14:38:22 -0700481 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700482 * Revokes IP flow rules for the subnets from given device.
Charles Chan93e71ba2016-04-29 14:38:22 -0700483 *
Charles Chan2ff1bac2018-03-29 16:03:41 -0700484 * @param targetSw target switch from which the subnets need to be removed
Charles Chan93e71ba2016-04-29 14:38:22 -0700485 * @param subnets subnet being removed
486 * @return true if all rules are removed successfully, false otherwise
487 */
Charles Chan2ff1bac2018-03-29 16:03:41 -0700488 boolean revokeIpRuleForSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
Charles Chan93e71ba2016-04-29 14:38:22 -0700489 for (IpPrefix subnet : subnets) {
Charles Chan2ff1bac2018-03-29 16:03:41 -0700490 if (!revokeIpRuleForRouter(targetSw, subnet)) {
Charles Chan93e71ba2016-04-29 14:38:22 -0700491 return false;
492 }
493 }
sanghob35a6192015-04-01 13:05:26 -0700494 return true;
495 }
496
497 /**
Saurav Das25190812016-05-27 13:54:07 -0700498 * Populates IP flow rules for an IP prefix in the target device. The prefix
Saurav Das7bcbe702017-06-13 15:35:54 -0700499 * is reachable via destination device(s).
sanghob35a6192015-04-01 13:05:26 -0700500 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700501 * @param targetSw target device ID to set the rules
502 * @param ipPrefix the IP prefix
503 * @param destSw1 destination switch where the prefixes are reachable
504 * @param destSw2 paired destination switch if one exists for the subnets/prefixes.
505 * Should be null if there is no paired destination switch (by config)
506 * or if the given prefixes are reachable only via destSw1
507 * @param nextHops map of destination switches and their next-hops.
508 * Should only contain destination switches that are
509 * actually meant to be routed to. If destSw2 is null, there
510 * should not be an entry for destSw2 in this map.
sanghob35a6192015-04-01 13:05:26 -0700511 * @return true if all rules are set successfully, false otherwise
512 */
Charles Chan65238242017-06-22 18:03:14 -0700513 private boolean populateIpRuleForRouter(DeviceId targetSw,
Saurav Das7bcbe702017-06-13 15:35:54 -0700514 IpPrefix ipPrefix, DeviceId destSw1,
515 DeviceId destSw2,
516 Map<DeviceId, Set<DeviceId>> nextHops) {
517 int segmentId1, segmentId2 = -1;
Charles Chan0b4e6182015-11-03 10:42:14 -0800518 try {
Pier Ventree0ae7a32016-11-23 09:57:42 -0800519 if (ipPrefix.isIp4()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700520 segmentId1 = config.getIPv4SegmentId(destSw1);
521 if (destSw2 != null) {
522 segmentId2 = config.getIPv4SegmentId(destSw2);
523 }
Pier Ventree0ae7a32016-11-23 09:57:42 -0800524 } else {
Saurav Das7bcbe702017-06-13 15:35:54 -0700525 segmentId1 = config.getIPv6SegmentId(destSw1);
526 if (destSw2 != null) {
527 segmentId2 = config.getIPv6SegmentId(destSw2);
528 }
Pier Ventree0ae7a32016-11-23 09:57:42 -0800529 }
Charles Chan0b4e6182015-11-03 10:42:14 -0800530 } catch (DeviceConfigNotFoundException e) {
531 log.warn(e.getMessage() + " Aborting populateIpRuleForRouter.");
532 return false;
533 }
sanghob35a6192015-04-01 13:05:26 -0700534
Pier Ventree0ae7a32016-11-23 09:57:42 -0800535 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chan68aa62d2015-11-09 16:37:23 -0800536 TrafficSelector selector = sbuilder.build();
sanghob35a6192015-04-01 13:05:26 -0700537
Charles Chan68aa62d2015-11-09 16:37:23 -0800538 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Das7bcbe702017-06-13 15:35:54 -0700539 DestinationSet ds;
Charles Chan68aa62d2015-11-09 16:37:23 -0800540 TrafficTreatment treatment;
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700541 DestinationSet.DestinationSetType dsType;
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();
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700550 ds = DestinationSet.createTypePushNone(destSw1);
Saurav Das7bcbe702017-06-13 15:35:54 -0700551 treatment = tbuilder.build();
552 } else {
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700553 ds = DestinationSet.createTypePushBos(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
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700560 ds = DestinationSet.createTypePushBos(segmentId1, destSw1, segmentId2, destSw2);
Charles Chan68aa62d2015-11-09 16:37:23 -0800561 treatment = null;
sanghob35a6192015-04-01 13:05:26 -0700562 }
563
Saurav Das8a0732e2015-11-20 15:27:53 -0800564 // setup metadata to pass to nextObjective - indicate the vlan on egress
565 // if needed by the switch pipeline. Since neighbor sets are always to
566 // other neighboring routers, there is no subnet assigned on those ports.
567 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das09c2c4d2018-08-13 15:34:26 -0700568 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Saurav Das7bcbe702017-06-13 15:35:54 -0700569 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700570 if (grpHandler == null) {
571 log.warn("populateIPRuleForRouter: groupHandler for device {} "
Saurav Das7bcbe702017-06-13 15:35:54 -0700572 + "not found", targetSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700573 return false;
574 }
Saurav Das8a0732e2015-11-20 15:27:53 -0800575
Saurav Das7bcbe702017-06-13 15:35:54 -0700576 int nextId = grpHandler.getNextObjectiveId(ds, nextHops,
Saurav Dasa4020382018-02-14 14:14:54 -0800577 metabuilder.build(), false);
Saurav Das8a0732e2015-11-20 15:27:53 -0800578 if (nextId <= 0) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700579 log.warn("No next objective in {} for ds: {}", targetSw, ds);
sangho834e4b02015-05-01 09:38:25 -0700580 return false;
581 }
582
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700583 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
584 .builder()
585 .fromApp(srManager.appId)
586 .makePermanent()
Saurav Das8a0732e2015-11-20 15:27:53 -0800587 .nextStep(nextId)
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700588 .withSelector(selector)
Charles Chan5270ed02016-01-30 23:22:37 -0800589 .withPriority(getPriorityFromPrefix(ipPrefix))
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700590 .withFlag(ForwardingObjective.Flag.SPECIFIC);
Charles Chan68aa62d2015-11-09 16:37:23 -0800591 if (treatment != null) {
592 fwdBuilder.withTreatment(treatment);
593 }
Saurav Dasc88d4662017-05-15 15:34:25 -0700594 log.debug("Installing IPv4 forwarding objective for router IP/subnet {} "
Saurav Das7bcbe702017-06-13 15:35:54 -0700595 + "in switch {} with nextId: {}", ipPrefix, targetSw, nextId);
Charles Chand2990362016-04-18 13:44:03 -0700596 ObjectiveContext context = new DefaultObjectiveContext(
Saurav Das25190812016-05-27 13:54:07 -0700597 (objective) -> log.debug("IP rule for router {} populated in dev:{}",
Saurav Das7bcbe702017-06-13 15:35:54 -0700598 ipPrefix, targetSw),
Charles Chand2990362016-04-18 13:44:03 -0700599 (objective, error) ->
Saurav Das25190812016-05-27 13:54:07 -0700600 log.warn("Failed to populate IP rule for router {}: {} in dev:{}",
Saurav Das7bcbe702017-06-13 15:35:54 -0700601 ipPrefix, error, targetSw));
602 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.add(context));
sangho20eff1d2015-04-13 15:15:58 -0700603 rulePopulationCounter.incrementAndGet();
sanghob35a6192015-04-01 13:05:26 -0700604
605 return true;
606 }
607
sanghob35a6192015-04-01 13:05:26 -0700608 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -0700609 * Revokes IP flow rules for the router IP address from given device.
Charles Chan93e71ba2016-04-29 14:38:22 -0700610 *
Charles Chan2ff1bac2018-03-29 16:03:41 -0700611 * @param targetSw target switch from which the ipPrefix need to be removed
Charles Chan93e71ba2016-04-29 14:38:22 -0700612 * @param ipPrefix the IP address of the destination router
613 * @return true if all rules are removed successfully, false otherwise
614 */
Charles Chan2ff1bac2018-03-29 16:03:41 -0700615 private boolean revokeIpRuleForRouter(DeviceId targetSw, IpPrefix ipPrefix) {
Pier Ventre968da122016-12-09 17:26:04 -0800616 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(ipPrefix);
Charles Chan93e71ba2016-04-29 14:38:22 -0700617 TrafficSelector selector = sbuilder.build();
618 TrafficTreatment dummyTreatment = DefaultTrafficTreatment.builder().build();
619
620 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
621 .builder()
622 .fromApp(srManager.appId)
623 .makePermanent()
624 .withSelector(selector)
625 .withTreatment(dummyTreatment)
626 .withPriority(getPriorityFromPrefix(ipPrefix))
627 .withFlag(ForwardingObjective.Flag.SPECIFIC);
628
Charles Chan2ff1bac2018-03-29 16:03:41 -0700629 ObjectiveContext context = new DefaultObjectiveContext(
630 (objective) -> log.debug("IP rule for router {} revoked from {}", ipPrefix, targetSw),
631 (objective, error) -> log.warn("Failed to revoke IP rule for router {} from {}: {}",
632 ipPrefix, targetSw, error));
633 srManager.flowObjectiveService.forward(targetSw, fwdBuilder.remove(context));
Charles Chan93e71ba2016-04-29 14:38:22 -0700634
635 return true;
636 }
637
638 /**
Saurav Dasa4020382018-02-14 14:14:54 -0800639 * Populates MPLS flow rules in the target device to point towards the
640 * destination device.
641 *
642 * @param targetSwId target device ID of the switch to set the rules
643 * @param destSwId destination switch device ID
644 * @param nextHops next hops switch ID list
645 * @param routerIp the router ip of the destination switch
646 * @return true if all rules are set successfully, false otherwise
647 */
648 boolean populateMplsRule(DeviceId targetSwId, DeviceId destSwId,
649 Set<DeviceId> nextHops, IpAddress routerIp) {
650 int segmentId;
651 try {
652 if (routerIp.isIp4()) {
653 segmentId = config.getIPv4SegmentId(destSwId);
654 } else {
655 segmentId = config.getIPv6SegmentId(destSwId);
656 }
657 } catch (DeviceConfigNotFoundException e) {
658 log.warn(e.getMessage() + " Aborting populateMplsRule.");
659 return false;
660 }
661
662 List<ForwardingObjective> fwdObjs = new ArrayList<>();
663 Collection<ForwardingObjective> fwdObjsMpls;
664 // Generates the transit rules used by the standard "routing".
665 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, segmentId,
666 routerIp, true);
667 if (fwdObjsMpls.isEmpty()) {
668 return false;
669 }
670 fwdObjs.addAll(fwdObjsMpls);
671
672 // Generates the transit rules used by the MPLS Pwaas.
673 int pwSrLabel;
674 try {
675 pwSrLabel = config.getPWRoutingLabel(destSwId);
676 } catch (DeviceConfigNotFoundException e) {
677 log.warn(e.getMessage()
678 + " Aborting populateMplsRule. No label for PseudoWire traffic.");
679 return false;
680 }
681 fwdObjsMpls = handleMpls(targetSwId, destSwId, nextHops, pwSrLabel,
682 routerIp, false);
683 if (fwdObjsMpls.isEmpty()) {
684 return false;
685 }
686 fwdObjs.addAll(fwdObjsMpls);
687
688 for (ForwardingObjective fwdObj : fwdObjs) {
689 log.debug("Sending MPLS fwd obj {} for SID {}-> next {} in sw: {}",
690 fwdObj.id(), segmentId, fwdObj.nextId(), targetSwId);
691 srManager.flowObjectiveService.forward(targetSwId, fwdObj);
692 rulePopulationCounter.incrementAndGet();
693 }
694
695 return true;
696 }
697
698 /**
699 * Differentiates between popping and swapping labels when building an MPLS
700 * forwarding objective.
Pier Ventre917127a2016-10-31 16:49:19 -0700701 *
702 * @param targetSwId the target sw
703 * @param destSwId the destination sw
704 * @param nextHops the set of next hops
Saurav Dasa4020382018-02-14 14:14:54 -0800705 * @param segmentId the segmentId to match representing the destination
706 * switch
707 * @param routerIp the router ip representing the destination switch
Pier Ventre917127a2016-10-31 16:49:19 -0700708 * @return a collection of fwdobjective
709 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700710 private Collection<ForwardingObjective> handleMpls(
711 DeviceId targetSwId,
712 DeviceId destSwId,
713 Set<DeviceId> nextHops,
714 int segmentId,
715 IpAddress routerIp,
716 boolean isMplsBos) {
Pier Ventre917127a2016-10-31 16:49:19 -0700717
718 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
719 List<ForwardingObjective.Builder> fwdObjBuilders = Lists.newArrayList();
Pier Luigi3bfe32c2017-01-30 09:47:36 -0800720 // For the transport of Pwaas we can use two or three MPLS label
Pier Ventre917127a2016-10-31 16:49:19 -0700721 sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
722 sbuilder.matchMplsLabel(MplsLabel.mplsLabel(segmentId));
723 sbuilder.matchMplsBos(isMplsBos);
724 TrafficSelector selector = sbuilder.build();
725
726 // setup metadata to pass to nextObjective - indicate the vlan on egress
727 // if needed by the switch pipeline. Since mpls next-hops are always to
728 // other neighboring routers, there is no subnet assigned on those ports.
729 TrafficSelector.Builder metabuilder = DefaultTrafficSelector.builder(selector);
Saurav Das09c2c4d2018-08-13 15:34:26 -0700730 metabuilder.matchVlanId(srManager.getDefaultInternalVlan());
Pier Ventre917127a2016-10-31 16:49:19 -0700731
732 if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
733 // If the next hop is the destination router for the segment, do pop
734 log.debug("populateMplsRule: Installing MPLS forwarding objective for "
Saurav Das7bcbe702017-06-13 15:35:54 -0700735 + "label {} in switch {} with pop to next-hops {}",
736 segmentId, targetSwId, nextHops);
Saurav Das961beb22017-03-29 19:09:17 -0700737 ForwardingObjective.Builder fwdObjNoBosBuilder =
738 getMplsForwardingObjective(targetSwId,
739 nextHops,
740 true,
741 isMplsBos,
742 metabuilder.build(),
Saurav Dasc88d4662017-05-15 15:34:25 -0700743 routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800744 segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700745 destSwId);
Pier Ventre917127a2016-10-31 16:49:19 -0700746 // Error case, we cannot handle, exit.
747 if (fwdObjNoBosBuilder == null) {
748 return Collections.emptyList();
749 }
750 fwdObjBuilders.add(fwdObjNoBosBuilder);
751
752 } else {
Saurav Dasa4020382018-02-14 14:14:54 -0800753 // next hop is not destination, irrespective of the number of next
754 // hops (1 or more) -- SR CONTINUE case (swap with self)
Saurav Das7bcbe702017-06-13 15:35:54 -0700755 log.debug("Installing MPLS forwarding objective for "
756 + "label {} in switch {} without pop to next-hops {}",
757 segmentId, targetSwId, nextHops);
Saurav Das961beb22017-03-29 19:09:17 -0700758 ForwardingObjective.Builder fwdObjNoBosBuilder =
759 getMplsForwardingObjective(targetSwId,
760 nextHops,
761 false,
762 isMplsBos,
763 metabuilder.build(),
Saurav Dasc88d4662017-05-15 15:34:25 -0700764 routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800765 segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700766 destSwId);
Pier Ventre917127a2016-10-31 16:49:19 -0700767 // Error case, we cannot handle, exit.
768 if (fwdObjNoBosBuilder == null) {
769 return Collections.emptyList();
770 }
771 fwdObjBuilders.add(fwdObjNoBosBuilder);
772
773 }
774
775 List<ForwardingObjective> fwdObjs = Lists.newArrayList();
776 // We add the final property to the fwdObjs.
777 for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
Pier Ventre917127a2016-10-31 16:49:19 -0700778 ((Builder) ((Builder) fwdObjBuilder
779 .fromApp(srManager.appId)
780 .makePermanent())
781 .withSelector(selector)
782 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY))
783 .withFlag(ForwardingObjective.Flag.SPECIFIC);
784
785 ObjectiveContext context = new DefaultObjectiveContext(
786 (objective) ->
787 log.debug("MPLS rule {} for SID {} populated in dev:{} ",
788 objective.id(), segmentId, targetSwId),
789 (objective, error) ->
790 log.warn("Failed to populate MPLS rule {} for SID {}: {} in dev:{}",
791 objective.id(), segmentId, error, targetSwId));
792
793 ForwardingObjective fob = fwdObjBuilder.add(context);
794 fwdObjs.add(fob);
Pier Ventre917127a2016-10-31 16:49:19 -0700795 }
796
797 return fwdObjs;
798 }
799
800 /**
Saurav Dasa4020382018-02-14 14:14:54 -0800801 * Returns a Forwarding Objective builder for the MPLS rule that references
802 * the desired Next Objective. Creates a DestinationSet that allows the
803 * groupHandler to create or find the required next objective.
sanghob35a6192015-04-01 13:05:26 -0700804 *
Saurav Dasa4020382018-02-14 14:14:54 -0800805 * @param targetSw the target sw
806 * @param nextHops the set of next hops
807 * @param phpRequired true if penultimate-hop-popping is required
808 * @param isBos true if matched label is bottom-of-stack
809 * @param meta metadata for creating next objective
810 * @param routerIp the router ip representing the destination switch
811 * @param destSw the destination sw
812 * @return the mpls forwarding objective builder
sanghob35a6192015-04-01 13:05:26 -0700813 */
Saurav Das8a0732e2015-11-20 15:27:53 -0800814 private ForwardingObjective.Builder getMplsForwardingObjective(
Saurav Das7bcbe702017-06-13 15:35:54 -0700815 DeviceId targetSw,
Saurav Das8a0732e2015-11-20 15:27:53 -0800816 Set<DeviceId> nextHops,
817 boolean phpRequired,
818 boolean isBos,
Pier Ventree0ae7a32016-11-23 09:57:42 -0800819 TrafficSelector meta,
Saurav Dasc88d4662017-05-15 15:34:25 -0700820 IpAddress routerIp,
Saurav Dasa4020382018-02-14 14:14:54 -0800821 int segmentId,
Saurav Dasc88d4662017-05-15 15:34:25 -0700822 DeviceId destSw) {
Saurav Das8a0732e2015-11-20 15:27:53 -0800823
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700824 ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
825 .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
sanghob35a6192015-04-01 13:05:26 -0700826
827 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
Saurav Dasa4020382018-02-14 14:14:54 -0800828 DestinationSet ds = null;
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700829 DestinationSet.DestinationSetType dstType = null;
Saurav Dasa4020382018-02-14 14:14:54 -0800830 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
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700844 ds = DestinationSet.createTypePopBos(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
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700850 ds = DestinationSet.createTypePopNotBos(destSw);
851 if (!srManager.getMplsEcmp()) {
852 simple = true;
Saurav Dasa4020382018-02-14 14:14:54 -0800853 }
sanghob35a6192015-04-01 13:05:26 -0700854 }
855 } else {
Saurav Das8a0732e2015-11-20 15:27:53 -0800856 // swap with self case - SR CONTINUE
Saurav Dasa4020382018-02-14 14:14:54 -0800857 log.debug("getMplsForwardingObjective: swap with self");
sangho1e575652015-05-14 00:39:53 -0700858 tbuilder.deferred().decMplsTtl();
Saurav Dasa4020382018-02-14 14:14:54 -0800859 // swap results in MPLS packet with same BoS bit regardless of bit value
860 // depending on configuration we can ECMP this packet or choose one output
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700861 // differentiate here between swap with not bos or swap with bos
862 ds = isBos ? DestinationSet.createTypeSwapBos(segmentId, destSw) :
863 DestinationSet.createTypeSwapNotBos(segmentId, destSw);
864 if (!srManager.getMplsEcmp()) {
Saurav Dasa4020382018-02-14 14:14:54 -0800865 simple = true;
866 }
sanghob35a6192015-04-01 13:05:26 -0700867 }
868
Saurav Das8a0732e2015-11-20 15:27:53 -0800869 fwdBuilder.withTreatment(tbuilder.build());
Saurav Dasa4020382018-02-14 14:14:54 -0800870 log.debug("Trying to get a nextObjId for mpls rule on device:{} to ds:{}",
871 targetSw, ds);
Saurav Das7bcbe702017-06-13 15:35:54 -0700872 DefaultGroupHandler gh = srManager.getGroupHandler(targetSw);
873 if (gh == null) {
874 log.warn("getNextObjectiveId query - groupHandler for device {} "
875 + "not found", targetSw);
876 return null;
877 }
Saurav Dasa4020382018-02-14 14:14:54 -0800878
Saurav Das7bcbe702017-06-13 15:35:54 -0700879 Map<DeviceId, Set<DeviceId>> dstNextHops = new HashMap<>();
880 dstNextHops.put(destSw, nextHops);
Saurav Dasa4020382018-02-14 14:14:54 -0800881 int nextId = gh.getNextObjectiveId(ds, dstNextHops, meta, simple);
Saurav Das8a0732e2015-11-20 15:27:53 -0800882 if (nextId <= 0) {
Saurav Dasa4020382018-02-14 14:14:54 -0800883 log.warn("No next objective in {} for ds: {}", targetSw, ds);
Saurav Das8a0732e2015-11-20 15:27:53 -0800884 return null;
Saurav Das25190812016-05-27 13:54:07 -0700885 } else {
Saurav Dasa4020382018-02-14 14:14:54 -0800886 log.debug("nextObjId found:{} for mpls rule on device:{} to ds:{}",
887 nextId, targetSw, ds);
sanghob35a6192015-04-01 13:05:26 -0700888 }
889
Saurav Das8a0732e2015-11-20 15:27:53 -0800890 fwdBuilder.nextStep(nextId);
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -0700891 return fwdBuilder;
sanghob35a6192015-04-01 13:05:26 -0700892 }
893
894 /**
Saurav Das822c4e22015-10-23 10:51:11 -0700895 * Creates a filtering objective to permit all untagged packets with a
Saurav Das0e99e2b2015-10-28 12:39:42 -0700896 * dstMac corresponding to the router's MAC address. For those pipelines
897 * that need to internally assign vlans to untagged packets, this method
898 * provides per-subnet vlan-ids as metadata.
Saurav Das837e0bb2015-10-30 17:45:38 -0700899 * <p>
Saurav Das018605f2017-02-18 14:05:44 -0800900 * Note that the vlan assignment and filter programming should only be done by
901 * the master for a switch. This method is typically called at deviceAdd and
902 * programs filters only for the enabled ports of the device. For port-updates,
903 * that enable/disable ports after device add, singlePortFilter methods should
904 * be called.
sanghob35a6192015-04-01 13:05:26 -0700905 *
Saurav Das822c4e22015-10-23 10:51:11 -0700906 * @param deviceId the switch dpid for the router
Saurav Dasd2fded02016-12-02 15:43:47 -0800907 * @return PortFilterInfo information about the processed ports
sanghob35a6192015-04-01 13:05:26 -0700908 */
Charles Chan65238242017-06-22 18:03:14 -0700909 PortFilterInfo populateVlanMacFilters(DeviceId deviceId) {
Saurav Das0e99e2b2015-10-28 12:39:42 -0700910 log.debug("Installing per-port filtering objective for untagged "
911 + "packets in device {}", deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -0800912
Saurav Das59232cf2016-04-27 18:35:50 -0700913 List<Port> devPorts = srManager.deviceService.getPorts(deviceId);
Jon Hallcbd1b392017-01-18 20:15:44 -0800914 if (devPorts == null || devPorts.isEmpty()) {
Saurav Das59232cf2016-04-27 18:35:50 -0700915 log.warn("Device {} ports not available. Unable to add MacVlan filters",
916 deviceId);
Saurav Dasd2fded02016-12-02 15:43:47 -0800917 return null;
Saurav Das59232cf2016-04-27 18:35:50 -0700918 }
Saurav Das018605f2017-02-18 14:05:44 -0800919 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das59232cf2016-04-27 18:35:50 -0700920 for (Port port : devPorts) {
Saurav Das25190812016-05-27 13:54:07 -0700921 if (!port.isEnabled()) {
922 disabledPorts++;
923 continue;
924 }
Charles Chan7e4f8192017-02-26 22:59:35 -0800925 if (processSinglePortFilters(deviceId, port.number(), true)) {
Saurav Das018605f2017-02-18 14:05:44 -0800926 filteredPorts++;
927 } else {
928 errorPorts++;
Saurav Das25190812016-05-27 13:54:07 -0700929 }
Saurav Das0e99e2b2015-10-28 12:39:42 -0700930 }
Charles Chan7f9737b2017-06-22 14:27:17 -0700931 log.debug("Filtering on dev:{}, disabledPorts:{}, errorPorts:{}, filteredPorts:{}",
Saurav Das018605f2017-02-18 14:05:44 -0800932 deviceId, disabledPorts, errorPorts, filteredPorts);
Charles Chan5adc6282018-06-19 20:56:33 -0700933 return new PortFilterInfo(disabledPorts, errorPorts, filteredPorts);
Saurav Das018605f2017-02-18 14:05:44 -0800934 }
935
936 /**
Charles Chan7e4f8192017-02-26 22:59:35 -0800937 * Creates or removes filtering objectives for a single port. Should only be
938 * called by the master for a switch.
Saurav Das018605f2017-02-18 14:05:44 -0800939 *
940 * @param deviceId device identifier
941 * @param portnum port identifier for port to be filtered
Charles Chan7e4f8192017-02-26 22:59:35 -0800942 * @param install true to install the filtering objective, false to remove
Saurav Das018605f2017-02-18 14:05:44 -0800943 * @return true if no errors occurred during the build of the filtering objective
944 */
Charles Chan65238242017-06-22 18:03:14 -0700945 boolean processSinglePortFilters(DeviceId deviceId, PortNumber portnum, boolean install) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800946 ConnectPoint connectPoint = new ConnectPoint(deviceId, portnum);
Charles Chan971d7ba2018-05-01 11:50:20 -0700947 VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
948 Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
949 VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);
Charles Chan7ffd81f2017-02-08 15:52:08 -0800950
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700951 // Do not configure filter for edge ports where double-tagged hosts are connected.
Charles Chan7ffd81f2017-02-08 15:52:08 -0800952 if (taggedVlans.size() != 0) {
953 // Filter for tagged vlans
Charles Chan971d7ba2018-05-01 11:50:20 -0700954 if (!srManager.interfaceService.getTaggedVlanId(connectPoint).stream().allMatch(taggedVlanId ->
Charles Chan7e4f8192017-02-26 22:59:35 -0800955 processSinglePortFiltersInternal(deviceId, portnum, false, taggedVlanId, install))) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800956 return false;
957 }
958 if (nativeVlan != null) {
959 // Filter for native vlan
Charles Chan7e4f8192017-02-26 22:59:35 -0800960 if (!processSinglePortFiltersInternal(deviceId, portnum, true, nativeVlan, install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800961 return false;
962 }
963 }
964 } else if (untaggedVlan != null) {
965 // Filter for untagged vlan
Charles Chan7e4f8192017-02-26 22:59:35 -0800966 if (!processSinglePortFiltersInternal(deviceId, portnum, true, untaggedVlan, install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800967 return false;
968 }
Jonghwan Hyun5efd7682018-04-30 09:27:21 -0700969 } else if (!hasIPConfiguration(connectPoint)) {
Jonghwan Hyun800d9d02018-04-09 09:40:50 -0700970 // Filter for unconfigured upstream port, using INTERNAL_VLAN
Saurav Das09c2c4d2018-08-13 15:34:26 -0700971 if (!processSinglePortFiltersInternal(deviceId, portnum, true,
972 srManager.getDefaultInternalVlan(),
973 install)) {
Charles Chan7ffd81f2017-02-08 15:52:08 -0800974 return false;
975 }
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700976 // Filter for receiveing pseudowire traffic
Saurav Das09c2c4d2018-08-13 15:34:26 -0700977 if (!processSinglePortFiltersInternal(deviceId, portnum, false,
978 srManager.getPwTransportVlan(),
979 install)) {
Andreas Pantelopoulos192284c2018-05-01 14:56:05 -0700980 return false;
981 }
Charles Chan7ffd81f2017-02-08 15:52:08 -0800982 }
983 return true;
984 }
985
Jonghwan Hyun42fe1052017-08-25 17:48:36 -0700986 /**
987 * Updates filtering objectives for a single port. Should only be called by
988 * the master for a switch
989 * @param deviceId device identifier
990 * @param portNum port identifier for port to be filtered
991 * @param pushVlan true to push vlan, false otherwise
992 * @param vlanId vlan identifier
993 * @param install true to install the filtering objective, false to remove
994 */
995 void updateSinglePortFilters(DeviceId deviceId, PortNumber portNum,
996 boolean pushVlan, VlanId vlanId, boolean install) {
997 if (!processSinglePortFiltersInternal(deviceId, portNum, pushVlan, vlanId, install)) {
998 log.warn("Failed to update FilteringObjective for {}/{} with vlan {}",
999 deviceId, portNum, vlanId);
1000 }
1001 }
1002
Charles Chan7e4f8192017-02-26 22:59:35 -08001003 private boolean processSinglePortFiltersInternal(DeviceId deviceId, PortNumber portnum,
1004 boolean pushVlan, VlanId vlanId, boolean install) {
Daniel Ginsburgc1d47e92018-04-30 19:27:19 -04001005 boolean doTMAC = true;
1006
1007 if (!pushVlan) {
1008 // Skip the tagged vlans belonging to an interface without an IP address
1009 Set<Interface> ifaces = srManager.interfaceService
1010 .getInterfacesByPort(new ConnectPoint(deviceId, portnum))
1011 .stream()
1012 .filter(intf -> intf.vlanTagged().contains(vlanId) && intf.ipAddressesList().isEmpty())
1013 .collect(Collectors.toSet());
1014 if (!ifaces.isEmpty()) {
1015 log.debug("processSinglePortFiltersInternal: skipping TMAC for vlan {} at {}/{} - no IP",
1016 vlanId, deviceId, portnum);
1017 doTMAC = false;
1018 }
1019 }
1020
1021 FilteringObjective.Builder fob = buildFilteringObjective(deviceId, portnum, pushVlan, vlanId, doTMAC);
Saurav Das018605f2017-02-18 14:05:44 -08001022 if (fob == null) {
1023 // error encountered during build
1024 return false;
1025 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001026 log.debug("{} filtering objectives for dev/port: {}/{}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001027 install ? "Installing" : "Removing", deviceId, portnum);
Saurav Das018605f2017-02-18 14:05:44 -08001028 ObjectiveContext context = new DefaultObjectiveContext(
Charles Chan7e4f8192017-02-26 22:59:35 -08001029 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portnum,
Saurav Dasc88d4662017-05-15 15:34:25 -07001030 install ? "installed" : "removed"),
Charles Chan7e4f8192017-02-26 22:59:35 -08001031 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001032 install ? "install" : "remove", deviceId, portnum, error));
Charles Chan7e4f8192017-02-26 22:59:35 -08001033 if (install) {
1034 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1035 } else {
1036 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
Charles Chan7ffd81f2017-02-08 15:52:08 -08001037 }
Charles Chan7ffd81f2017-02-08 15:52:08 -08001038 return true;
Saurav Das018605f2017-02-18 14:05:44 -08001039 }
1040
Charles Chan7ffd81f2017-02-08 15:52:08 -08001041 private FilteringObjective.Builder buildFilteringObjective(DeviceId deviceId, PortNumber portnum,
Daniel Ginsburgc1d47e92018-04-30 19:27:19 -04001042 boolean pushVlan, VlanId vlanId, boolean doTMAC) {
Saurav Das018605f2017-02-18 14:05:44 -08001043 MacAddress deviceMac;
1044 try {
1045 deviceMac = config.getDeviceMac(deviceId);
1046 } catch (DeviceConfigNotFoundException e) {
1047 log.warn(e.getMessage() + " Processing SinglePortFilters aborted");
1048 return null;
1049 }
Saurav Das018605f2017-02-18 14:05:44 -08001050 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
Daniel Ginsburgc1d47e92018-04-30 19:27:19 -04001051
1052 if (doTMAC) {
1053 fob.withKey(Criteria.matchInPort(portnum))
1054 .addCondition(Criteria.matchEthDst(deviceMac))
1055 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1056 } else {
1057 fob.withKey(Criteria.matchInPort(portnum))
1058 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1059 }
Charles Chan7ffd81f2017-02-08 15:52:08 -08001060
Charles Chanc550f2e2017-12-19 19:55:57 -08001061 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1062
Charles Chan7ffd81f2017-02-08 15:52:08 -08001063 if (pushVlan) {
1064 fob.addCondition(Criteria.matchVlanId(VlanId.NONE));
Charles Chanc550f2e2017-12-19 19:55:57 -08001065 tBuilder.pushVlan().setVlanId(vlanId);
Charles Chan7ffd81f2017-02-08 15:52:08 -08001066 } else {
1067 fob.addCondition(Criteria.matchVlanId(vlanId));
1068 }
1069
Charles Chanc550f2e2017-12-19 19:55:57 -08001070 // NOTE: Some switch hardware share the same filtering flow among different ports.
1071 // We use this metadata to let the driver know that there is no more enabled port
1072 // within the same VLAN on this device.
Charles Chandd33be52018-02-26 21:33:25 -08001073 if (noMoreEnabledPort(deviceId, vlanId)) {
Charles Chanc550f2e2017-12-19 19:55:57 -08001074 tBuilder.wipeDeferred();
1075 }
1076
1077 fob.withMeta(tBuilder.build());
1078
Saurav Das018605f2017-02-18 14:05:44 -08001079 fob.permit().fromApp(srManager.appId);
1080 return fob;
sanghob35a6192015-04-01 13:05:26 -07001081 }
1082
1083 /**
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001084 * Creates or removes filtering objectives for a double-tagged host on a port.
1085 *
1086 * @param deviceId device identifier
1087 * @param portNum port identifier for port to be filtered
1088 * @param outerVlan outer VLAN ID
1089 * @param innerVlan inner VLAN ID
1090 * @param install true to install the filtering objective, false to remove
1091 */
1092 void processDoubleTaggedFilter(DeviceId deviceId, PortNumber portNum, VlanId outerVlan,
1093 VlanId innerVlan, boolean install) {
1094 FilteringObjective.Builder fob = buildDoubleTaggedFilteringObj(deviceId, portNum, outerVlan, innerVlan);
1095 if (fob == null) {
1096 // error encountered during build
1097 return;
1098 }
1099 log.debug("{} double-tagged filtering objectives for dev/port: {}/{}",
1100 install ? "Installing" : "Removing", deviceId, portNum);
1101 ObjectiveContext context = new DefaultObjectiveContext(
1102 (objective) -> log.debug("Filter for {}/{} {}", deviceId, portNum,
1103 install ? "installed" : "removed"),
1104 (objective, error) -> log.warn("Failed to {} filter for {}/{}: {}",
1105 install ? "install" : "remove", deviceId, portNum, error));
1106 if (install) {
1107 srManager.flowObjectiveService.filter(deviceId, fob.add(context));
1108 } else {
1109 srManager.flowObjectiveService.filter(deviceId, fob.remove(context));
1110 }
1111 }
1112
1113 private FilteringObjective.Builder buildDoubleTaggedFilteringObj(DeviceId deviceId, PortNumber portNum,
1114 VlanId outerVlan, VlanId innerVlan) {
1115 MacAddress deviceMac;
1116 try {
1117 deviceMac = config.getDeviceMac(deviceId);
1118 } catch (DeviceConfigNotFoundException e) {
1119 log.warn(e.getMessage() + " Processing DoubleTaggedFilters aborted");
1120 return null;
1121 }
1122 FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
1123 // Outer vlan id match should be appeared before inner vlan id match.
1124 fob.withKey(Criteria.matchInPort(portNum))
1125 .addCondition(Criteria.matchEthDst(deviceMac))
1126 .addCondition(Criteria.matchVlanId(outerVlan))
1127 .addCondition(Criteria.matchVlanId(innerVlan))
1128 .withPriority(SegmentRoutingService.DEFAULT_PRIORITY);
1129
1130 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1131 // Pop outer vlan
1132 tBuilder.popVlan();
1133
1134 // NOTE: Some switch hardware share the same filtering flow among different ports.
1135 // We use this metadata to let the driver know that there is no more enabled port
1136 // within the same VLAN on this device.
1137 if (noMoreEnabledPort(deviceId, outerVlan)) {
1138 tBuilder.wipeDeferred();
1139 }
1140
1141 fob.withMeta(tBuilder.build());
1142
1143 fob.permit().fromApp(srManager.appId);
1144 return fob;
1145 }
1146
1147 /**
Saurav Das822c4e22015-10-23 10:51:11 -07001148 * Creates a forwarding objective to punt all IP packets, destined to the
Saurav Das837e0bb2015-10-30 17:45:38 -07001149 * router's port IP addresses, to the controller. Note that the input
Saurav Das822c4e22015-10-23 10:51:11 -07001150 * port should not be matched on, as these packets can come from any input.
Saurav Das837e0bb2015-10-30 17:45:38 -07001151 * Furthermore, these are applied only by the master instance.
sanghob35a6192015-04-01 13:05:26 -07001152 *
Saurav Das822c4e22015-10-23 10:51:11 -07001153 * @param deviceId the switch dpid for the router
sanghob35a6192015-04-01 13:05:26 -07001154 */
Charles Chan65238242017-06-22 18:03:14 -07001155 void populateIpPunts(DeviceId deviceId) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001156 Ip4Address routerIpv4, pairRouterIpv4 = null;
Charles Chan78ec5052017-12-05 21:07:38 -08001157 Ip6Address routerIpv6, routerLinkLocalIpv6, pairRouterIpv6 = null;
Charles Chan0b4e6182015-11-03 10:42:14 -08001158 try {
Pier Ventree0ae7a32016-11-23 09:57:42 -08001159 routerIpv4 = config.getRouterIpv4(deviceId);
1160 routerIpv6 = config.getRouterIpv6(deviceId);
Charles Chan78ec5052017-12-05 21:07:38 -08001161 routerLinkLocalIpv6 = Ip6Address.valueOf(
1162 IPv6.getLinkLocalAddress(config.getDeviceMac(deviceId).toBytes()));
1163
Saurav Das7bcbe702017-06-13 15:35:54 -07001164 if (config.isPairedEdge(deviceId)) {
1165 pairRouterIpv4 = config.getRouterIpv4(config.getPairDeviceId(deviceId));
1166 pairRouterIpv6 = config.getRouterIpv6(config.getPairDeviceId(deviceId));
1167 }
Charles Chan0b4e6182015-11-03 10:42:14 -08001168 } catch (DeviceConfigNotFoundException e) {
Charles Chanf6ec1532017-02-08 16:10:40 -08001169 log.warn(e.getMessage() + " Aborting populateIpPunts.");
Charles Chan0b4e6182015-11-03 10:42:14 -08001170 return;
1171 }
1172
Saurav Das837e0bb2015-10-30 17:45:38 -07001173 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1174 log.debug("Not installing port-IP punts - not the master for dev:{} ",
1175 deviceId);
1176 return;
1177 }
Pier Ventree0ae7a32016-11-23 09:57:42 -08001178 Set<IpAddress> allIps = new HashSet<>(config.getPortIPs(deviceId));
1179 allIps.add(routerIpv4);
1180 if (routerIpv6 != null) {
1181 allIps.add(routerIpv6);
Charles Chanf27ef092018-08-29 14:55:53 -07001182 allIps.add(routerLinkLocalIpv6);
Pier Ventree0ae7a32016-11-23 09:57:42 -08001183 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001184 if (pairRouterIpv4 != null) {
1185 allIps.add(pairRouterIpv4);
1186 }
1187 if (pairRouterIpv6 != null) {
1188 allIps.add(pairRouterIpv6);
1189 }
Pier Ventree0ae7a32016-11-23 09:57:42 -08001190 for (IpAddress ipaddr : allIps) {
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001191 populateSingleIpPunts(deviceId, ipaddr);
1192 }
1193 }
Charles Chan2df0e8a2017-01-09 11:45:08 -08001194
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001195 /**
1196 * Creates a forwarding objective to punt all IP packets, destined to the
1197 * specified IP address, which should be router's port IP address.
1198 *
1199 * @param deviceId the switch dpid for the router
1200 * @param ipAddress the IP address of the router's port
1201 */
1202 void populateSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1203 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1204 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1205
1206 srManager.packetService.requestPackets(sbuilder.build(),
1207 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1208 }
1209
1210 /**
1211 * Removes a forwarding objective to punt all IP packets, destined to the
1212 * specified IP address, which should be router's port IP address.
1213 *
1214 * @param deviceId the switch dpid for the router
1215 * @param ipAddress the IP address of the router's port
1216 */
1217 void revokeSingleIpPunts(DeviceId deviceId, IpAddress ipAddress) {
1218 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpAddress(ipAddress);
1219 Optional<DeviceId> optDeviceId = Optional.of(deviceId);
1220
1221 try {
1222 if (!ipAddress.equals(config.getRouterIpv4(deviceId)) &&
1223 !ipAddress.equals(config.getRouterIpv6(deviceId))) {
1224 srManager.packetService.cancelPackets(sbuilder.build(),
1225 PacketPriority.CONTROL, srManager.appId, optDeviceId);
1226 }
1227 } catch (DeviceConfigNotFoundException e) {
1228 log.warn(e.getMessage() + " Aborting revokeSingleIpPunts");
Saurav Das822c4e22015-10-23 10:51:11 -07001229 }
sanghob35a6192015-04-01 13:05:26 -07001230 }
1231
Charles Chan68aa62d2015-11-09 16:37:23 -08001232 /**
Pier Ventree0ae7a32016-11-23 09:57:42 -08001233 * Method to build IPv4 or IPv6 selector.
1234 *
1235 * @param addressToMatch the address to match
1236 */
1237 private TrafficSelector.Builder buildIpSelectorFromIpAddress(IpAddress addressToMatch) {
1238 return buildIpSelectorFromIpPrefix(addressToMatch.toIpPrefix());
1239 }
1240
1241 /**
1242 * Method to build IPv4 or IPv6 selector.
1243 *
1244 * @param prefixToMatch the prefix to match
1245 */
1246 private TrafficSelector.Builder buildIpSelectorFromIpPrefix(IpPrefix prefixToMatch) {
1247 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
Pier Ventre917127a2016-10-31 16:49:19 -07001248 // If the prefix is IPv4
Pier Ventree0ae7a32016-11-23 09:57:42 -08001249 if (prefixToMatch.isIp4()) {
1250 selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
1251 selectorBuilder.matchIPDst(prefixToMatch.getIp4Prefix());
1252 return selectorBuilder;
1253 }
Pier Ventre917127a2016-10-31 16:49:19 -07001254 // If the prefix is IPv6
Pier Ventree0ae7a32016-11-23 09:57:42 -08001255 selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
1256 selectorBuilder.matchIPv6Dst(prefixToMatch.getIp6Prefix());
1257 return selectorBuilder;
1258 }
1259
1260 /**
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001261 * Creates forwarding objectives to punt ARP and NDP packets, to the controller.
1262 * Furthermore, these are applied only by the master instance. Deferred actions
1263 * are not cleared such that packets can be flooded in the cross connect use case
1264 *
1265 * @param deviceId the switch dpid for the router
1266 */
Charles Chan65238242017-06-22 18:03:14 -07001267 void populateArpNdpPunts(DeviceId deviceId) {
Pier Ventre917127a2016-10-31 16:49:19 -07001268 // We are not the master just skip.
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001269 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1270 log.debug("Not installing ARP/NDP punts - not the master for dev:{} ",
1271 deviceId);
1272 return;
1273 }
1274
Charles Chan65238242017-06-22 18:03:14 -07001275 ForwardingObjective fwdObj;
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001276 // We punt all ARP packets towards the controller.
Charles Chan78ec5052017-12-05 21:07:38 -08001277 fwdObj = arpFwdObjective(null, true, ARP_NDP_PRIORITY)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001278 .add(new ObjectiveContext() {
1279 @Override
1280 public void onError(Objective objective, ObjectiveError error) {
Charles Chan65238242017-06-22 18:03:14 -07001281 log.warn("Failed to install forwarding objective to punt ARP to {}: {}",
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001282 deviceId, error);
1283 }
1284 });
Charles Chan65238242017-06-22 18:03:14 -07001285 srManager.flowObjectiveService.forward(deviceId, fwdObj);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001286
Charles Chanf27ef092018-08-29 14:55:53 -07001287 if (isIpv6Configured(deviceId)) {
1288 // We punt all NDP packets towards the controller.
1289 ndpFwdObjective(null, true, ARP_NDP_PRIORITY).forEach(builder -> {
1290 ForwardingObjective obj = builder.add(new ObjectiveContext() {
1291 @Override
1292 public void onError(Objective objective, ObjectiveError error) {
1293 log.warn("Failed to install forwarding objective to punt NDP to {}: {}",
1294 deviceId, error);
1295 }
1296 });
1297 srManager.flowObjectiveService.forward(deviceId, obj);
Charles Chan09bf2692018-01-11 11:48:18 -08001298 });
Charles Chanf27ef092018-08-29 14:55:53 -07001299 }
Charles Chan65238242017-06-22 18:03:14 -07001300
Saurav Das9a554292018-04-27 18:42:30 -07001301 srManager.getPairLocalPort(deviceId).ifPresent(port -> {
Charles Chan65238242017-06-22 18:03:14 -07001302 ForwardingObjective pairFwdObj;
1303 // Do not punt ARP packets from pair port
1304 pairFwdObj = arpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1)
1305 .add(new ObjectiveContext() {
1306 @Override
1307 public void onError(Objective objective, ObjectiveError error) {
1308 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
1309 deviceId, error);
1310 }
1311 });
1312 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1313
Charles Chanf27ef092018-08-29 14:55:53 -07001314 if (isIpv6Configured(deviceId)) {
1315 // Do not punt NDP packets from pair port
1316 ndpFwdObjective(port, false, PacketPriority.CONTROL.priorityValue() + 1).forEach(builder -> {
1317 ForwardingObjective obj = builder.add(new ObjectiveContext() {
Charles Chan65238242017-06-22 18:03:14 -07001318 @Override
1319 public void onError(Objective objective, ObjectiveError error) {
Charles Chanf27ef092018-08-29 14:55:53 -07001320 log.warn("Failed to install forwarding objective to ignore ARP to {}: {}",
Charles Chan65238242017-06-22 18:03:14 -07001321 deviceId, error);
1322 }
1323 });
Charles Chanf27ef092018-08-29 14:55:53 -07001324 srManager.flowObjectiveService.forward(deviceId, obj);
1325 });
1326
1327 // Do not forward DAD packets from pair port
1328 pairFwdObj = dad6FwdObjective(port, PacketPriority.CONTROL.priorityValue() + 2)
1329 .add(new ObjectiveContext() {
1330 @Override
1331 public void onError(Objective objective, ObjectiveError error) {
1332 log.warn("Failed to install forwarding objective to drop DAD to {}: {}",
1333 deviceId, error);
1334 }
1335 });
1336 srManager.flowObjectiveService.forward(deviceId, pairFwdObj);
1337 }
Charles Chan65238242017-06-22 18:03:14 -07001338 });
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001339 }
1340
Charles Chan65238242017-06-22 18:03:14 -07001341 private ForwardingObjective.Builder fwdObjBuilder(TrafficSelector selector,
1342 TrafficTreatment treatment, int priority) {
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001343 return DefaultForwardingObjective.builder()
Charles Chan65238242017-06-22 18:03:14 -07001344 .withPriority(priority)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001345 .withSelector(selector)
1346 .fromApp(srManager.appId)
1347 .withFlag(ForwardingObjective.Flag.VERSATILE)
Charles Chan65238242017-06-22 18:03:14 -07001348 .withTreatment(treatment)
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001349 .makePermanent();
1350 }
1351
Charles Chan65238242017-06-22 18:03:14 -07001352 private ForwardingObjective.Builder arpFwdObjective(PortNumber port, boolean punt, int priority) {
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001353 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1354 sBuilder.matchEthType(TYPE_ARP);
Charles Chan65238242017-06-22 18:03:14 -07001355 if (port != null) {
1356 sBuilder.matchInPort(port);
1357 }
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001358
Charles Chan65238242017-06-22 18:03:14 -07001359 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1360 if (punt) {
1361 tBuilder.punt();
1362 }
1363 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001364 }
1365
Charles Chan09bf2692018-01-11 11:48:18 -08001366 private Set<ForwardingObjective.Builder> ndpFwdObjective(PortNumber port, boolean punt, int priority) {
1367 Set<ForwardingObjective.Builder> result = Sets.newHashSet();
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001368
Charles Chan09bf2692018-01-11 11:48:18 -08001369 Lists.newArrayList(NEIGHBOR_SOLICITATION, NEIGHBOR_ADVERTISEMENT, ROUTER_SOLICITATION, ROUTER_ADVERTISEMENT)
1370 .forEach(type -> {
1371 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1372 sBuilder.matchEthType(TYPE_IPV6)
1373 .matchIPProtocol(PROTOCOL_ICMP6)
1374 .matchIcmpv6Type(type);
1375 if (port != null) {
1376 sBuilder.matchInPort(port);
1377 }
1378
1379 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1380 if (punt) {
1381 tBuilder.punt();
1382 }
1383
1384 result.add(fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority));
1385 });
1386
1387 return result;
Charles Chan65238242017-06-22 18:03:14 -07001388 }
1389
1390 private ForwardingObjective.Builder dad6FwdObjective(PortNumber port, int priority) {
1391 TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();
1392 sBuilder.matchEthType(TYPE_IPV6)
Charles Chanc7e36aa2017-08-07 12:39:03 -07001393 .matchIPv6Src(Ip6Address.ZERO.toIpPrefix());
1394 // TODO CORD-1672 Fix this when OFDPA can distinguish ::/0 and ::/128 correctly
1395 // .matchIPProtocol(PROTOCOL_ICMP6)
1396 // .matchIcmpv6Type(NEIGHBOR_SOLICITATION);
Charles Chan65238242017-06-22 18:03:14 -07001397 if (port != null) {
1398 sBuilder.matchInPort(port);
1399 }
1400
1401 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1402 tBuilder.wipeDeferred();
1403 return fwdObjBuilder(sBuilder.build(), tBuilder.build(), priority);
Pier Luigi9e5c5ca2017-01-12 18:14:58 -08001404 }
1405
1406 /**
Charles Chan68aa62d2015-11-09 16:37:23 -08001407 * Populates a forwarding objective to send packets that miss other high
1408 * priority Bridging Table entries to a group that contains all ports of
1409 * its subnet.
1410 *
Andrea Campanellad980c6d2018-04-30 11:48:55 +02001411 * @param address the address to block
1412 * @param deviceId switch ID to set the rules
1413 */
1414 void populateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1415 updateDefaultRouteBlackhole(deviceId, address, true);
1416 }
1417
1418 /**
1419 * Populates a forwarding objective to send packets that miss other high
1420 * priority Bridging Table entries to a group that contains all ports of
1421 * its subnet.
1422 *
1423 * @param address the address to block
1424 * @param deviceId switch ID to set the rules
1425 */
1426 void removeDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address) {
1427 updateDefaultRouteBlackhole(deviceId, address, false);
1428 }
1429
1430 private void updateDefaultRouteBlackhole(DeviceId deviceId, IpPrefix address, boolean install) {
1431 try {
1432 if (srManager.deviceConfiguration.isEdgeDevice(deviceId)) {
1433
1434 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1435 if (address.isIp4()) {
1436 sbuilder.matchIPDst(address);
1437 sbuilder.matchEthType(EthType.EtherType.IPV4.ethType().toShort());
1438 } else {
1439 sbuilder.matchIPv6Dst(address);
1440 sbuilder.matchEthType(EthType.EtherType.IPV6.ethType().toShort());
1441 }
1442
1443 TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
1444
1445 tBuilder.transition(60);
1446 tBuilder.wipeDeferred();
1447
1448 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1449 fob.withFlag(Flag.SPECIFIC)
1450 .withSelector(sbuilder.build())
1451 .withTreatment(tBuilder.build())
1452 .withPriority(getPriorityFromPrefix(address))
1453 .fromApp(srManager.appId)
1454 .makePermanent();
1455
1456 log.debug("{} blackhole forwarding objectives for dev: {}",
1457 install ? "Installing" : "Removing", deviceId);
1458 ObjectiveContext context = new DefaultObjectiveContext(
1459 (objective) -> log.debug("Forward for {} {}", deviceId,
1460 install ? "installed" : "removed"),
1461 (objective, error) -> log.warn("Failed to {} forward for {}: {}",
1462 install ? "install" : "remove", deviceId, error));
1463 if (install) {
1464 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1465 } else {
1466 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1467 }
1468 }
1469 } catch (DeviceConfigNotFoundException e) {
1470 log.info("Not populating blackhole for un-configured device {}", deviceId);
1471 }
1472
1473 }
1474
1475 /**
1476 * Populates a forwarding objective to send packets that miss other high
1477 * priority Bridging Table entries to a group that contains all ports of
1478 * its subnet.
1479 *
Charles Chan68aa62d2015-11-09 16:37:23 -08001480 * @param deviceId switch ID to set the rules
1481 */
Charles Chan65238242017-06-22 18:03:14 -07001482 void populateSubnetBroadcastRule(DeviceId deviceId) {
Charles Chan7ffd81f2017-02-08 15:52:08 -08001483 srManager.getVlanPortMap(deviceId).asMap().forEach((vlanId, ports) -> {
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001484 updateSubnetBroadcastRule(deviceId, vlanId, true);
Charles Chan68aa62d2015-11-09 16:37:23 -08001485 });
1486 }
1487
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001488 /**
1489 * Creates or removes a forwarding objective to broadcast packets to its subnet.
1490 * @param deviceId switch ID to set the rule
1491 * @param vlanId vlan ID to specify the subnet
1492 * @param install true to install the rule, false to revoke the rule
1493 */
1494 void updateSubnetBroadcastRule(DeviceId deviceId, VlanId vlanId, boolean install) {
1495 int nextId = srManager.getVlanNextObjectiveId(deviceId, vlanId);
1496
1497 if (nextId < 0) {
1498 log.error("Cannot install vlan {} broadcast rule in dev:{} due"
1499 + " to vlanId:{} or nextId:{}", vlanId, deviceId, vlanId, nextId);
1500 return;
1501 }
1502
1503 // Driver should treat objective with MacAddress.NONE as the
1504 // subnet broadcast rule
1505 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1506 sbuilder.matchVlanId(vlanId);
1507 sbuilder.matchEthDst(MacAddress.NONE);
1508
1509 ForwardingObjective.Builder fob = DefaultForwardingObjective.builder();
1510 fob.withFlag(Flag.SPECIFIC)
1511 .withSelector(sbuilder.build())
1512 .nextStep(nextId)
1513 .withPriority(SegmentRoutingService.FLOOD_PRIORITY)
1514 .fromApp(srManager.appId)
1515 .makePermanent();
1516 ObjectiveContext context = new DefaultObjectiveContext(
1517 (objective) -> log.debug("Vlan broadcast rule for {} populated", vlanId),
1518 (objective, error) ->
1519 log.warn("Failed to populate vlan broadcast rule for {}: {}", vlanId, error));
1520
1521 if (install) {
1522 srManager.flowObjectiveService.forward(deviceId, fob.add(context));
1523 } else {
1524 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1525 }
1526 }
1527
Charles Chan5270ed02016-01-30 23:22:37 -08001528 private int getPriorityFromPrefix(IpPrefix prefix) {
1529 return (prefix.isIp4()) ?
1530 2000 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY :
1531 500 * prefix.prefixLength() + SegmentRoutingService.MIN_IP_PRIORITY;
Srikanth Vavilapallif3a8bc02015-05-22 13:47:31 -07001532 }
Jonghwan Hyun42fe1052017-08-25 17:48:36 -07001533
1534 /**
1535 * Update Forwarding objective for each host and IP address connected to given port.
1536 * And create corresponding Simple Next objective if it does not exist.
1537 * Applied only when populating Forwarding objective
1538 * @param deviceId switch ID to set the rule
1539 * @param portNumber port number
1540 * @param prefix IP prefix of the route
1541 * @param hostMac MAC address of the next hop
1542 * @param vlanId Vlan ID of the port
1543 * @param popVlan true to pop vlan tag in TrafficTreatment
1544 * @param install true to populate the forwarding objective, false to revoke
1545 */
1546 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1547 VlanId vlanId, boolean popVlan, boolean install) {
1548 ForwardingObjective.Builder fob;
1549 TrafficSelector.Builder sbuilder = buildIpSelectorFromIpPrefix(prefix);
1550 MacAddress deviceMac;
1551 try {
1552 deviceMac = config.getDeviceMac(deviceId);
1553 } catch (DeviceConfigNotFoundException e) {
1554 log.warn(e.getMessage() + " Aborting updateFwdObj.");
1555 return;
1556 }
1557
1558 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1559 tbuilder.deferred()
1560 .setEthDst(hostMac)
1561 .setEthSrc(deviceMac)
1562 .setOutput(portNumber);
1563
1564 TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();
1565
1566 if (!popVlan) {
1567 tbuilder.setVlanId(vlanId);
1568 } else {
1569 mbuilder.matchVlanId(vlanId);
1570 }
1571
1572 // if the objective is to revoke an existing rule, and for some reason
1573 // the next-objective does not exist, then a new one should not be created
1574 int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNumber,
1575 tbuilder.build(), mbuilder.build(), install);
1576 if (portNextObjId == -1) {
1577 // Warning log will come from getPortNextObjective method
1578 return;
1579 }
1580
1581 fob = DefaultForwardingObjective.builder().withSelector(sbuilder.build())
1582 .nextStep(portNextObjId).fromApp(srManager.appId).makePermanent()
1583 .withPriority(getPriorityFromPrefix(prefix)).withFlag(ForwardingObjective.Flag.SPECIFIC);
1584
1585 ObjectiveContext context = new DefaultObjectiveContext(
1586 (objective) -> log.debug("IP rule for route {} {}", prefix, install ? "installed" : "revoked"),
1587 (objective, error) ->
1588 log.warn("Failed to {} IP rule for route {}: {}",
1589 install ? "install" : "revoke", prefix, error));
1590 srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
1591
1592 if (!install) {
1593 DefaultGroupHandler grpHandler = srManager.getGroupHandler(deviceId);
1594 if (grpHandler == null) {
1595 log.warn("updateFwdObj: groupHandler for device {} not found", deviceId);
1596 } else {
1597 // Remove L3UG for the given port and host
1598 grpHandler.removeGroupFromPort(portNumber, tbuilder.build(), mbuilder.build());
1599 }
1600 }
1601 }
Charles Chandd33be52018-02-26 21:33:25 -08001602
1603 /**
1604 * Checks if there is other enabled port within the given VLAN on the given device.
1605 *
1606 * @param deviceId device ID
1607 * @param vlanId VLAN ID
1608 * @return true if there is no more port enabled within the given VLAN on the given device
1609 */
1610 boolean noMoreEnabledPort(DeviceId deviceId, VlanId vlanId) {
1611 Set<ConnectPoint> enabledPorts = srManager.deviceService.getPorts(deviceId).stream()
1612 .filter(Port::isEnabled)
1613 .map(port -> new ConnectPoint(port.element().id(), port.number()))
1614 .collect(Collectors.toSet());
1615
1616 return enabledPorts.stream().noneMatch(cp ->
1617 // Given vlanId is included in the vlan-tagged configuration
Charles Chan971d7ba2018-05-01 11:50:20 -07001618 srManager.interfaceService.getTaggedVlanId(cp).contains(vlanId) ||
Charles Chandd33be52018-02-26 21:33:25 -08001619 // Given vlanId is INTERNAL_VLAN and the interface is not configured
Charles Chan971d7ba2018-05-01 11:50:20 -07001620 (srManager.interfaceService.getTaggedVlanId(cp).isEmpty() && srManager.getInternalVlanId(cp) == null &&
Saurav Das09c2c4d2018-08-13 15:34:26 -07001621 vlanId.equals(srManager.getDefaultInternalVlan())) ||
Charles Chandd33be52018-02-26 21:33:25 -08001622 // interface is configured and either vlan-untagged or vlan-native matches given vlanId
1623 (srManager.getInternalVlanId(cp) != null && srManager.getInternalVlanId(cp).equals(vlanId))
1624 );
1625 }
Jonghwan Hyun800d9d02018-04-09 09:40:50 -07001626
1627 /**
1628 * Returns a forwarding objective builder for egress forwarding rules.
1629 * <p>
1630 * The forwarding objective installs flow rules to egress pipeline to push
1631 * two vlan headers with given inner, outer vlan ids and outer tpid.
1632 *
1633 * @param portNumber port where the next hop attaches to
1634 * @param dummyVlanId vlan ID of the packet to match
1635 * @param innerVlan inner vlan ID of the next hop
1636 * @param outerVlan outer vlan ID of the next hop
1637 * @param outerTpid outer TPID of the next hop
1638 * @return forwarding objective builder
1639 */
1640 private ForwardingObjective.Builder egressFwdObjBuilder(PortNumber portNumber, VlanId dummyVlanId,
1641 VlanId innerVlan, VlanId outerVlan, EthType outerTpid) {
1642 TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
1643 sbuilder.matchVlanId(dummyVlanId);
1644 TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
1645 tbuilder.setOutput(portNumber).setVlanId(innerVlan);
1646
1647 if (outerTpid.equals(EthType.EtherType.QINQ.ethType())) {
1648 tbuilder.pushVlan(outerTpid);
1649 } else {
1650 tbuilder.pushVlan();
1651 }
1652
1653 tbuilder.setVlanId(outerVlan);
1654 return DefaultForwardingObjective.builder()
1655 .withSelector(sbuilder.build())
1656 .withTreatment(tbuilder.build())
1657 .fromApp(srManager.appId)
1658 .makePermanent()
1659 .withPriority(DEFAULT_PRIORITY)
1660 .withFlag(ForwardingObjective.Flag.EGRESS);
1661 }
1662
1663 /**
1664 * Populates IP rules for a route that has double-tagged next hop.
1665 *
1666 * @param deviceId device ID of the device that next hop attaches to
1667 * @param prefix IP prefix of the route
1668 * @param hostMac MAC address of the next hop
1669 * @param dummyVlan Dummy Vlan ID allocated for this route
1670 * @param innerVlan inner Vlan ID of the next hop
1671 * @param outerVlan outer Vlan ID of the next hop
1672 * @param outerTpid outer TPID of the next hop
1673 * @param outPort port where the next hop attaches to
1674 */
1675 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId dummyVlan,
1676 VlanId innerVlan, VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1677 ForwardingObjective.Builder fwdBuilder;
1678 log.debug("Populate direct routing entry for double-tagged host route {} at {}:{}",
1679 prefix, deviceId, outPort);
1680
1681 ForwardingObjective.Builder egressFwdBuilder = egressFwdObjBuilder(
1682 outPort, dummyVlan, innerVlan, outerVlan, outerTpid);
1683 DefaultObjectiveContext egressFwdContext = new DefaultObjectiveContext(
1684 objective -> log.debug("Egress rule for IP {} is populated", prefix.address()),
1685 (objective, error) -> {
1686 log.warn("Failed to populate egress rule for IP {}: {}", prefix.address(), error);
1687 srManager.dummyVlanIdStore().remove(new DummyVlanIdStoreKey(
1688 new ConnectPoint(deviceId, outPort), prefix.address()
1689 ));
1690 });
1691 try {
1692 fwdBuilder = routingFwdObjBuilder(deviceId, prefix, hostMac, dummyVlan, outPort, false);
1693 } catch (DeviceConfigNotFoundException e) {
1694 log.error(e.getMessage() + " Aborting populateDoubleTaggedRoute");
1695 return;
1696 }
1697 if (fwdBuilder == null) {
1698 log.error("Aborting double-tagged host routing table entry due to error for dev:{} route:{}",
1699 deviceId, prefix);
1700 return;
1701 }
1702
1703 // Egress forwarding objective should be installed after the nextObjective for the output port is installed.
1704 // Installation of routingFwdObj will ensure the installation of the nextObjective.
1705 int nextId = fwdBuilder.add().nextId();
1706 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1707 log.debug("Direct routing rule for double-tagged host route {} populated. nextId={}", prefix, nextId);
1708 srManager.flowObjectiveService.forward(deviceId, egressFwdBuilder.add(egressFwdContext));
1709 }, (objective, error) ->
1710 log.warn("Failed to populate direct routing rule for double-tagged host route {}: {}", prefix, error)
1711 );
1712 srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add(context));
1713 rulePopulationCounter.incrementAndGet();
1714 }
1715
1716 /**
1717 * Revokes IP rules for a route that has double-tagged next hop.
1718 *
1719 * @param deviceId device ID of the device that next hop attaches to
1720 * @param prefix IP prefix of the route
1721 * @param hostMac MAC address of the next hop
1722 * @param hostVlan Vlan ID of the next hop
1723 * @param innerVlan inner Vlan ID of the next hop
1724 * @param outerVlan outer Vlan ID of the next hop
1725 * @param outerTpid outer TPID of the next hop
1726 * @param outPort port where the next hop attaches to
1727 */
1728 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac,
1729 VlanId hostVlan, VlanId innerVlan, VlanId outerVlan,
1730 EthType outerTpid, PortNumber outPort) {
1731 revokeRoute(deviceId, prefix, hostMac, hostVlan, outPort);
1732
1733 DummyVlanIdStoreKey key = new DummyVlanIdStoreKey(
1734 new ConnectPoint(deviceId, outPort), prefix.address());
1735 VlanId dummyVlanId = srManager.dummyVlanIdStore().get(key);
1736 if (dummyVlanId == null) {
1737 log.warn("Failed to retrieve dummy VLAN ID for {}/{} and {}",
1738 deviceId, outPort, prefix.address());
1739 return;
1740 }
1741 ForwardingObjective.Builder fob = egressFwdObjBuilder(
1742 outPort, dummyVlanId, innerVlan, outerVlan, outerTpid);
1743 DefaultObjectiveContext context = new DefaultObjectiveContext(objective -> {
1744 log.debug("Egress rule for IP {} revoked", prefix.address());
1745 srManager.dummyVlanIdStore().remove(key);
1746 }, (objective, error) -> {
1747 log.warn("Failed to revoke egress rule for IP {}: {}", prefix.address(), error);
1748 });
1749 srManager.flowObjectiveService.forward(deviceId, fob.remove(context));
1750 }
1751
Jonghwan Hyun5efd7682018-04-30 09:27:21 -07001752 /**
1753 * Checks whether the specified port has IP configuration or not.
1754 *
1755 * @param cp ConnectPoint to check the existance of IP configuration
1756 * @return true if the port has IP configuration; false otherwise.
1757 */
1758 private boolean hasIPConfiguration(ConnectPoint cp) {
1759 Set<Interface> interfaces = srManager.interfaceService.getInterfacesByPort(cp);
1760 return interfaces.stream().anyMatch(intf -> intf.ipAddressesList().size() > 0);
1761 }
Saurav Das09c2c4d2018-08-13 15:34:26 -07001762
1763 /**
1764 * Updates filtering rules for unconfigured ports on all devices for which
1765 * this controller instance is master.
1766 *
1767 * @param pushVlan true if the filtering rule requires a push vlan action
1768 * @param oldVlanId the vlanId to be removed
1769 * @param newVlanId the vlanId to be added
1770 */
1771 void updateSpecialVlanFilteringRules(boolean pushVlan, VlanId oldVlanId,
1772 VlanId newVlanId) {
1773 for (Device dev : srManager.deviceService.getAvailableDevices()) {
1774 if (srManager.mastershipService.isLocalMaster(dev.id())) {
1775 for (Port p : srManager.deviceService.getPorts(dev.id())) {
1776 if (!hasIPConfiguration(new ConnectPoint(dev.id(), p.number()))
1777 && p.isEnabled()) {
1778 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1779 oldVlanId, false);
1780 updateSinglePortFilters(dev.id(), p.number(), pushVlan,
1781 newVlanId, true);
1782 }
1783 }
1784 }
1785 }
1786 }
1787
Charles Chanf27ef092018-08-29 14:55:53 -07001788 private boolean isIpv6Configured(DeviceId deviceId) {
1789 boolean isIpv6Configured;
1790 try {
1791 isIpv6Configured = (config.getRouterIpv6(deviceId) != null);
1792 } catch (DeviceConfigNotFoundException e) {
1793 isIpv6Configured = false;
1794 }
1795 return isIpv6Configured;
1796 }
sanghob35a6192015-04-01 13:05:26 -07001797}